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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package ttlcache
import (
"container/list"
"context"
"strconv"
"sync"
"time"
"golang.org/x/sync/singleflight"
)
type Options struct {
TTL time.Duration
MaxEntries int
Now func() time.Time
}
type Cache[K comparable, V any] struct {
ttl time.Duration
max int
now func() time.Time
mu sync.Mutex
order *list.List
items map[K]*list.Element
flights map[K]*flight
seq uint64
nextPrune int
onEvict func(K, V)
group singleflight.Group
}
type entry[K comparable, V any] struct {
key K
value V
expires time.Time
}
type flight struct {
id string
stale bool
}
const minPrune = 64
func New[K comparable, V any](opts Options) *Cache[K, V] {
if opts.Now == nil {
opts.Now = time.Now
}
return &Cache[K, V]{
ttl: opts.TTL,
max: opts.MaxEntries,
now: opts.Now,
order: list.New(),
items: make(map[K]*list.Element),
flights: make(map[K]*flight),
nextPrune: minPrune,
}
}
func (c *Cache[K, V]) OnEvict(f func(K, V)) *Cache[K, V] {
c.mu.Lock()
defer c.mu.Unlock()
c.onEvict = f
return c
}
func (c *Cache[K, V]) Get(key K) (V, bool) {
c.mu.Lock()
defer c.mu.Unlock()
return c.getLocked(key)
}
func (c *Cache[K, V]) Set(key K, value V) {
c.SetTTL(key, value, 0)
}
func (c *Cache[K, V]) SetTTL(key K, value V, ttl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.setLocked(key, value, ttl)
}
func (c *Cache[K, V]) Add(key K, value V, ttl time.Duration) bool {
c.mu.Lock()
defer c.mu.Unlock()
if _, ok := c.getLocked(key); ok {
return false
}
c.setLocked(key, value, ttl)
return true
}
func (c *Cache[K, V]) Delete(key K) {
c.mu.Lock()
defer c.mu.Unlock()
if el, ok := c.items[key]; ok {
c.removeLocked(el)
}
if f, ok := c.flights[key]; ok {
f.stale = true
delete(c.flights, key)
}
}
func (c *Cache[K, V]) DeleteFunc(drop func(K, V) bool) int {
c.mu.Lock()
defer c.mu.Unlock()
dropped := 0
for el := c.order.Front(); el != nil; {
next := el.Next()
e := el.Value.(*entry[K, V])
if drop(e.key, e.value) {
c.removeLocked(el)
dropped++
}
el = next
}
return dropped
}
func (c *Cache[K, V]) DeleteKeys(drop func(K) bool) int {
c.mu.Lock()
defer c.mu.Unlock()
dropped := 0
for key, f := range c.flights {
if drop(key) {
f.stale = true
delete(c.flights, key)
dropped++
}
}
for el := c.order.Front(); el != nil; {
next := el.Next()
if drop(el.Value.(*entry[K, V]).key) {
c.removeLocked(el)
dropped++
}
el = next
}
return dropped
}
func (c *Cache[K, V]) Range(visit func(K, V) bool) {
c.mu.Lock()
now := c.now()
keys := make([]K, 0, len(c.items))
values := make([]V, 0, len(c.items))
for el := c.order.Front(); el != nil; el = el.Next() {
e := el.Value.(*entry[K, V])
if e.expired(now) {
continue
}
keys = append(keys, e.key)
values = append(values, e.value)
}
c.mu.Unlock()
for i := range keys {
if !visit(keys[i], values[i]) {
return
}
}
}
func (c *Cache[K, V]) Len() int {
c.mu.Lock()
defer c.mu.Unlock()
c.pruneLocked()
return len(c.items)
}
func (c *Cache[K, V]) Prune() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.pruneLocked()
}
func (c *Cache[K, V]) Loading() int {
c.mu.Lock()
defer c.mu.Unlock()
return len(c.flights)
}
func (c *Cache[K, V]) GetOrLoad(ctx context.Context, key K, load func(context.Context) (V, time.Duration, error)) (V, error) {
c.mu.Lock()
if value, ok := c.getLocked(key); ok {
c.mu.Unlock()
return value, nil
}
f, ok := c.flights[key]
if !ok {
c.seq++
f = &flight{id: strconv.FormatUint(c.seq, 36)}
c.flights[key] = f
}
c.mu.Unlock()
ch := c.group.DoChan(f.id, func() (any, error) {
value, ttl, err := load(ctx)
c.mu.Lock()
defer c.mu.Unlock()
if c.flights[key] == f {
delete(c.flights, key)
}
if err == nil && !f.stale {
c.setLocked(key, value, ttl)
}
return value, err
})
select {
case res := <-ch:
value, _ := res.Val.(V)
return value, res.Err
case <-ctx.Done():
var zero V
return zero, ctx.Err()
}
}
func (c *Cache[K, V]) getLocked(key K) (V, bool) {
el, ok := c.items[key]
if !ok {
var zero V
return zero, false
}
e := el.Value.(*entry[K, V])
if e.expired(c.now()) {
c.removeLocked(el)
var zero V
return zero, false
}
c.order.MoveToFront(el)
return e.value, true
}
func (c *Cache[K, V]) setLocked(key K, value V, ttl time.Duration) {
if ttl == 0 {
ttl = c.ttl
}
if ttl < 0 {
if el, ok := c.items[key]; ok {
c.removeLocked(el)
}
return
}
var expires time.Time
if ttl > 0 {
expires = c.now().Add(ttl)
}
if el, ok := c.items[key]; ok {
e := el.Value.(*entry[K, V])
if c.onEvict != nil {
c.onEvict(e.key, e.value)
}
e.value = value
e.expires = expires
c.order.MoveToFront(el)
return
}
c.items[key] = c.order.PushFront(&entry[K, V]{key: key, value: value, expires: expires})
if len(c.items) >= c.nextPrune {
c.pruneLocked()
c.nextPrune = max(2*len(c.items), minPrune)
}
for c.max > 0 && len(c.items) > c.max {
c.removeLocked(c.order.Back())
}
}
func (c *Cache[K, V]) pruneLocked() int {
now := c.now()
dropped := 0
for el := c.order.Front(); el != nil; {
next := el.Next()
if el.Value.(*entry[K, V]).expired(now) {
c.removeLocked(el)
dropped++
}
el = next
}
return dropped
}
func (c *Cache[K, V]) removeLocked(el *list.Element) {
e := el.Value.(*entry[K, V])
delete(c.items, e.key)
c.order.Remove(el)
if c.onEvict != nil {
c.onEvict(e.key, e.value)
}
}
func (e *entry[K, V]) expired(now time.Time) bool {
return !e.expires.IsZero() && !now.Before(e.expires)
}