-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.go
83 lines (68 loc) · 1.58 KB
/
cache.go
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
78
79
80
81
82
83
package fixenv
import (
"errors"
"sync"
)
type cache struct {
m sync.RWMutex
store map[cacheKey]cacheVal
setLocks map[cacheKey]*sync.Once
}
type cacheKey string
type cacheVal struct {
res *Result
err error
}
func newCache() *cache {
return &cache{
store: make(map[cacheKey]cacheVal),
setLocks: make(map[cacheKey]*sync.Once),
}
}
// GetOrSet atomic get exist values from cache or call f for set new value and return it.
// it has guarantee about only one f will execute same time for the key.
// but many f may execute simultaneously for different keys
func (c *cache) GetOrSet(key cacheKey, f FixtureFunction) (*Result, error) {
res, ok := c.get(key)
if ok {
return res.res, res.err
}
c.setOnce(key, f)
res, _ = c.get(key)
return res.res, res.err
}
func (c *cache) DeleteKeys(keys ...cacheKey) {
c.m.Lock()
defer c.m.Unlock()
for _, key := range keys {
delete(c.store, key)
delete(c.setLocks, key)
}
}
func (c *cache) get(key cacheKey) (cacheVal, bool) {
c.m.RLock()
defer c.m.RUnlock()
val, ok := c.store[key]
return val, ok
}
func (c *cache) setOnce(key cacheKey, f FixtureFunction) {
c.m.Lock()
setOnce := c.setLocks[key]
if setOnce == nil {
setOnce = &sync.Once{}
c.setLocks[key] = setOnce
}
c.m.Unlock()
setOnce.Do(func() {
var err = errors.New("unexpected exit from function")
var res *Result
// save result must be deferred because f() may stop goroutine without result
// for example by panic or GoExit
defer func() {
c.m.Lock()
c.store[key] = cacheVal{res: res, err: err}
c.m.Unlock()
}()
res, err = f()
})
}