-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgokachu.go
More file actions
341 lines (261 loc) · 8.02 KB
/
Copy pathgokachu.go
File metadata and controls
341 lines (261 loc) · 8.02 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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package gokachu
import (
"cmp"
"container/list"
"slices"
"sync"
"sync/atomic"
"time"
)
type Gokachu[K comparable, V any] struct {
elems *list.List // front of list == greater risk of deletion <---------list---------> back of list == less risk of deletion
store map[K]*list.Element
mut *sync.RWMutex
maxRecordThreshold int
clearNum int
replacementStrategy ReplacementStrategy
pollInterval time.Duration
pollCancel chan struct{}
wg *sync.WaitGroup
// Hooks
inc atomic.Uint64
onSetHooks map[uint64]func(key K, value V, ttl time.Duration)
onGetHooks map[uint64]func(key K, value V)
onMissHooks map[uint64]func(key K)
onDeleteHooks map[uint64]func(key K, value V)
}
type Config struct {
ReplacementStrategy ReplacementStrategy // default: ReplacementStrategyNone
MaxRecordThreshold int // This parameter is used to control the maximum number of records in the cache. If the number of records exceeds this threshold, records will be deleted according to the replacement strategy.
ClearNum int // This parameter is used to control the number of records to be deleted.
PollInterval time.Duration // This parameter is used to control the polling interval. If value is 0, uses default = 1 second.
}
// New creates a new Gokachu instance with the given configuration. Do not forgot call Close() function before exit.
func New[K comparable, V any](cfg Config) *Gokachu[K, V] {
g := &Gokachu[K, V]{
elems: list.New(),
store: make(map[K]*list.Element),
mut: new(sync.RWMutex),
maxRecordThreshold: cfg.MaxRecordThreshold,
clearNum: cfg.ClearNum,
replacementStrategy: cfg.ReplacementStrategy,
pollInterval: cmp.Or(cfg.PollInterval, time.Second), // Default poll interval is 1 second
pollCancel: make(chan struct{}),
wg: new(sync.WaitGroup),
// Hooks
onSetHooks: make(map[uint64]func(key K, value V, ttl time.Duration)),
onGetHooks: make(map[uint64]func(key K, value V)),
onMissHooks: make(map[uint64]func(key K)),
onDeleteHooks: make(map[uint64]func(key K, value V)),
}
g.wg.Add(1)
go g.poll()
return g
}
// Set sets a value in the cache with a TTL. If the TTL is 0, the value will not expire.
func (g *Gokachu[K, V]) Set(key K, v V, ttl time.Duration, hooks ...Hook) {
defer g.lock()()
if g.pollCancel == nil {
return
}
g.runOnSetHooks(key, v, ttl)
exp := time.Time{}
if ttl > 0 {
exp = time.Now().Add(ttl)
}
// if exists
if oldElem, ok := g.store[key]; ok {
oldElem.Value.(*valueWithTTL[K, V]).value = v
oldElem.Value.(*valueWithTTL[K, V]).expireTime = exp
// set individual hooks
for _, hook := range hooks {
if hook.OnGet != nil {
oldElem.Value.(*valueWithTTL[K, V]).hook.OnGet = hook.OnGet
}
if hook.OnDelete != nil {
oldElem.Value.(*valueWithTTL[K, V]).hook.OnDelete = hook.OnDelete
}
}
switch g.replacementStrategy {
case ReplacementStrategyLRU:
g.elems.MoveToBack(oldElem)
case ReplacementStrategyMRU:
g.elems.MoveToFront(oldElem)
}
return
}
// if not exists
// clear if cache is full
if g.maxRecordThreshold > 0 && g.clearNum > 0 && g.replacementStrategy > ReplacementStrategyNone && len(g.store) >= g.maxRecordThreshold {
g.clear()
}
value := &valueWithTTL[K, V]{
key: key,
value: v,
expireTime: exp,
}
// set individual hooks
for _, hook := range hooks {
if hook.OnGet != nil {
value.hook.OnGet = hook.OnGet
}
if hook.OnDelete != nil {
value.hook.OnDelete = hook.OnDelete
}
}
switch g.replacementStrategy {
case ReplacementStrategyFIFO, ReplacementStrategyLRU, ReplacementStrategyLFU, ReplacementStrategyMFU, ReplacementStrategyNone:
g.store[key] = g.elems.PushBack(value)
case ReplacementStrategyLIFO, ReplacementStrategyMRU:
g.store[key] = g.elems.PushFront(value)
}
}
// Get gets a value from the cache. Returns false in second value if the key does not exist.
func (g *Gokachu[K, V]) Get(key K) (V, bool) {
defer g.lock()()
item, ok := g.store[key]
if !ok {
g.runOnMissHooks(key)
return *new(V), false
}
value := item.Value.(*valueWithTTL[K, V])
switch g.replacementStrategy {
case ReplacementStrategyLRU:
g.elems.MoveToBack(item)
case ReplacementStrategyMRU:
g.elems.MoveToFront(item)
case ReplacementStrategyMFU, ReplacementStrategyLFU:
value.hitCount++
g.moveByHits(item)
}
// run hooks before getting value
g.runOnGetHooks(key, value.value)
if value.hook.OnGet != nil {
value.hook.OnGet()
}
return value.value, true
}
// GetFunc retrieves a first matching value from the cache using a callback function. If all matches return false, the second value also returns false.
func (g *Gokachu[K, V]) GetFunc(cb func(key K, value V) bool) (V, bool) {
unlock := g.rlock()
var foundKey K
found := false
for k, v := range g.store {
if cb(k, v.Value.(*valueWithTTL[K, V]).value) {
foundKey = k
found = true
break
}
}
unlock()
if found {
return g.Get(foundKey)
}
var zeroV V
return zeroV, false
}
// Delete deletes a value from the cache and returns true if the key existed.
func (g *Gokachu[K, V]) Delete(key K) bool {
defer g.lock()()
value, ok := g.store[key]
if ok {
// run hooks before delete
g.runOnDeleteHooks(key, value.Value.(*valueWithTTL[K, V]).value)
if value.Value.(*valueWithTTL[K, V]).hook.OnDelete != nil {
value.Value.(*valueWithTTL[K, V]).hook.OnDelete()
}
// delete
g.elems.Remove(value)
delete(g.store, key)
}
return ok
}
// DeleteFunc deletes values from the cache for which the callback returns true and returns the number of deleted values.
func (g *Gokachu[K, V]) DeleteFunc(cb func(key K, value V) bool) int {
defer g.lock()()
count := 0 // deleted count
for key, value := range g.store {
if cb(key, value.Value.(*valueWithTTL[K, V]).value) {
// run hooks before delete
g.runOnDeleteHooks(key, value.Value.(*valueWithTTL[K, V]).value)
if value.Value.(*valueWithTTL[K, V]).hook.OnDelete != nil {
value.Value.(*valueWithTTL[K, V]).hook.OnDelete()
}
// delete
g.elems.Remove(value)
delete(g.store, key)
count++
}
}
return count
}
// Flush deletes all values from the cache and return the number of deleted values.
func (g *Gokachu[K, V]) Flush() int {
defer g.lock()()
g.elems.Init()
count := len(g.store)
clear(g.store)
return count
}
// Keys returns all keys in the cache.
func (g *Gokachu[K, V]) Keys() []K {
defer g.rlock()()
keys := make([]K, 0, len(g.store))
for e := g.elems.Front(); e != nil; e = e.Next() {
keys = append(keys, e.Value.(*valueWithTTL[K, V]).key)
}
return keys
}
// KeysFunc returns all keys in the cache for which the callback returns true.
func (g *Gokachu[K, V]) KeysFunc(cb func(key K, value V) bool) []K {
defer g.rlock()()
keys := make([]K, 0, len(g.store))
for e := g.elems.Front(); e != nil; e = e.Next() {
if cb(e.Value.(*valueWithTTL[K, V]).key, e.Value.(*valueWithTTL[K, V]).value) {
keys = append(keys, e.Value.(*valueWithTTL[K, V]).key)
}
}
return slices.Clip(keys)
}
// Count returns the number of values in the cache.
func (g *Gokachu[K, V]) Count() int {
defer g.rlock()()
return g.elems.Len()
}
// CountFunc returns the number of values in the cache for which the callback returns true.
func (g *Gokachu[K, V]) CountFunc(cb func(key K, value V) bool) int {
defer g.rlock()()
count := 0
for key, value := range g.store {
if cb(key, value.Value.(*valueWithTTL[K, V]).value) {
count++
}
}
return count
}
// Close closes the cache and all associated resources.
func (g *Gokachu[K, V]) Close() {
g.mut.Lock()
if g.pollCancel == nil {
g.mut.Unlock()
return
}
close(g.pollCancel)
clear(g.store)
// clear hooks
g.onSetHooks = nil
g.onGetHooks = nil
g.onDeleteHooks = nil
g.onMissHooks = nil
g.elems.Init()
g.mut.Unlock()
g.wg.Wait()
}
func (k *Gokachu[K, V]) lock() func() {
k.mut.Lock()
return k.mut.Unlock
}
func (k *Gokachu[K, V]) rlock() func() {
k.mut.RLock()
return k.mut.RUnlock
}