-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweakcache.go
More file actions
109 lines (84 loc) · 1.79 KB
/
weakcache.go
File metadata and controls
109 lines (84 loc) · 1.79 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package weakcache
import (
"runtime"
"sync"
"sync/atomic"
"weak"
"github.com/tmwalaszek/weakcache/singleflight"
)
type WeakCache[T any] struct {
c map[string]weak.Pointer[T]
mx sync.Mutex
stats Stats
sfGroup singleflight.Group[T]
}
type Stats struct {
NumCalls atomic.Int64
NumCacheMisses atomic.Int64
NumCacheHits atomic.Int64
SingleFlightStats *singleflight.Stats
}
func NewWeakCache[T any]() *WeakCache[T] {
sfGroup := singleflight.NewGroup[T]()
return &WeakCache[T]{
c: make(map[string]weak.Pointer[T]),
mx: sync.Mutex{},
sfGroup: *sfGroup,
}
}
func (w *WeakCache[T]) get(key string) (T, bool) {
w.mx.Lock()
defer w.mx.Unlock()
var weakVal weak.Pointer[T]
var b bool
var value T
weakVal, b = w.c[key]
if !b {
return value, false
}
val := weakVal.Value()
if val == nil {
delete(w.c, key)
return value, false
}
return *val, true
}
// XXX What to do when we have key?
func (w *WeakCache[T]) set(key string, value *T) {
w.mx.Lock()
defer w.mx.Unlock()
v := weak.Make(value)
w.c[key] = v
runtime.AddCleanup(&v, func(key string) {
w.mx.Lock()
defer w.mx.Unlock()
if cur, ok := w.c[key]; ok {
if cur.Value() == nil {
delete(w.c, key)
}
}
}, key)
}
func (w *WeakCache[T]) Do(key string, fn func() (T, error)) (T, error) {
var value T
w.stats.NumCalls.Add(1)
v, got := w.get(key)
if !got {
w.stats.NumCacheMisses.Add(1)
r := w.sfGroup.Do(key, fn)
if r.Err != nil {
return value, r.Err
}
// If r.Initial equal true then it's first result from the singleflight.Do and we need to store it in the cache
if r.Initial {
w.set(key, &r.Val)
}
return r.Val, nil
}
w.stats.NumCacheHits.Add(1)
return v, nil
}
func (w *WeakCache[T]) Stats() *Stats {
w.stats.SingleFlightStats = w.sfGroup.Stats()
return &w.stats
}