-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.go
More file actions
77 lines (67 loc) · 1.89 KB
/
fetch.go
File metadata and controls
77 lines (67 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package ttlmap
import (
"errors"
"time"
)
// ErrTypeMismatch is returned when the cached value cannot be cast to the requested generic type.
var ErrTypeMismatch = errors.New("ttlmap: cached value has different type")
// Fetch returns a strictly typed value from the cache, fetching from the provided source function when missing.
func Fetch[T any](m CacheMap, key string, source func(string) (T, error)) (T, error) {
return FetchWithCustomDuration[T](m, key, func(k string) (T, *time.Duration, error) {
value, err := source(k)
return value, nil, err
})
}
func FetchWithCustomDuration[T any](m CacheMap, key string, source func(string) (T, *time.Duration, error)) (T, error) {
var zero T
var returnValue T
var okCast bool
shard := m.GetShard(key)
shard.RLock()
itm, ok := shard.items[key]
if ok {
returnValue, okCast = itm.GetValue().(T)
shard.RUnlock()
if !okCast {
return zero, ErrTypeMismatch
}
if !itm.Expired() {
return returnValue, nil
}
if !itm.isUpdating && itm.updateMutex.TryLock() {
itm.isUpdating = true
go func() {
// Update in the background to avoid cache call slow downs
value, duration, err := source(key)
if err == nil {
m.Set(key, value, duration)
}
itm.updateMutex.Unlock()
itm.isUpdating = false
}()
}
// Item has expired, but another thread is updateMutex
return returnValue, nil
}
shard.RUnlock()
shard.Lock()
defer shard.Unlock()
itm, ok = shard.items[key]
if ok {
// check the value was not already processed when waiting for the lock
returnValue, okCast = itm.GetValue().(T)
if !okCast {
return zero, ErrTypeMismatch
}
return returnValue, nil
}
value, duration, err := source(key)
if err == nil {
if duration == nil {
duration = &m.options.defaultCacheDuration
}
itm = newItem(value, *duration, time.Now().Add(m.options.maxLifetime), nil)
shard.items[key] = itm
}
return value, err
}