-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple.go
326 lines (293 loc) · 8.1 KB
/
simple.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
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
package ggcache
import (
"context"
"sync"
"time"
)
// var _ Cacher[int, int] = &SimpleCache[int, int]{}
// SimpleCache has no clear priority for evict cache. It depends on key-value map order.
type SimpleCache[K comparable, V any] struct {
BaseCache[K, V]
items map[K]*CacheValue[V]
itemsMu sync.RWMutex
}
// SimpleCacheBuilder helps configure and build a SimpleCache.
type SimpleCacheBuilder[K comparable, V any] struct {
initSize int
deleteExpiredInterval time.Duration
clock Clock
}
// NewSimpleBuilder creates a new builder with default settings.
func NewSimpleBuilder[K comparable, V any]() *SimpleCacheBuilder[K, V] {
return &SimpleCacheBuilder[K, V]{
initSize: 8,
deleteExpiredInterval: time.Second * 3,
clock: NewRealClock(),
}
}
// InitSize sets the initial size of the cache.
func (b *SimpleCacheBuilder[K, V]) InitSize(size int) *SimpleCacheBuilder[K, V] {
b.initSize = size
return b
}
// DeleteExpiredInterval sets the interval for deleting expired items.
func (b *SimpleCacheBuilder[K, V]) DeleteExpiredInterval(d time.Duration) *SimpleCacheBuilder[K, V] {
b.deleteExpiredInterval = d
return b
}
// Clock sets the clock used for expiration.
func (b *SimpleCacheBuilder[K, V]) Clock(clock Clock) *SimpleCacheBuilder[K, V] {
b.clock = clock
return b
}
// Build constructs the SimpleCache with the configured settings.
func (b *SimpleCacheBuilder[K, V]) Build() *SimpleCache[K, V] {
c := &SimpleCache[K, V]{}
c.items = make(map[K]*CacheValue[V], b.initSize)
c.BaseCache = *newBaseCache[K, V](c.batchRemoveExpired).
withClock(b.clock).withTickerDuration(b.deleteExpiredInterval)
return c
}
// Set inserts or updates the specified key-value pair.
func (s *SimpleCache[K, V]) Set(key K, value V) {
s.SetWithExpire(key, value, time.Time{})
}
// SetWithExpire inserts or updates the specified key-value pair with an expiration time.
// If expireAt is zero, the item will never expire.
func (s *SimpleCache[K, V]) SetWithExpire(key K, value V, expireAt time.Time) {
var val = &CacheValue[V]{value: value, expireAt: expireAt}
s.set(key, val)
}
// set adds or updates a cache entry and manages expiration.
func (s *SimpleCache[K, V]) set(key K, val *CacheValue[V]) {
// needInsertToExpireQueue := val.expireAt != nil
needInsertToExpireQueue := !val.expireAt.IsZero()
s.itemsMu.Lock()
old, exists := s.items[key]
if exists {
if val.expireAt.IsZero() {
needInsertToExpireQueue = false
} else if val.expireAt.Equal(old.expireAt) {
needInsertToExpireQueue = false
} else {
needInsertToExpireQueue = true
}
old.value = val.value
old.expireAt = val.expireAt
}
if !exists {
s.items[key] = val
}
s.itemsMu.Unlock()
if needInsertToExpireQueue {
s.BaseCache.pushExpire(key, val)
}
}
// GetRefresh retrieves a value by key, refreshing the expiration time if it is non-zero.
// It returns false if the item is not found or has expired.
func (s *SimpleCache[K, V]) GetRefresh(key K, expireAt time.Time) (V, bool) {
return s.getRefresh(key, expireAt, true)
}
func (s *SimpleCache[K, V]) getRefresh(key K, expireAt time.Time, setMissCount bool) (V, bool) {
needInsertToExpireQueue := !expireAt.IsZero()
var ok = false
s.itemsMu.RLock()
old, exists := s.items[key]
if exists && !old.IsExpired(s.clock.Now()) {
ok = true
if expireAt.IsZero() {
needInsertToExpireQueue = false
} else if expireAt.Equal(old.expireAt) {
needInsertToExpireQueue = false
} else {
needInsertToExpireQueue = true
}
old.expireAt = expireAt
}
s.itemsMu.RUnlock()
if setMissCount {
if ok {
s.incrHitCount()
} else {
s.incrMissCount()
}
}
if !ok {
return *new(V), false
}
if needInsertToExpireQueue {
s.BaseCache.pushExpire(key, old)
}
return old.value, true
}
// Get retrieves a value by key, returning false if not found or expired.
func (s *SimpleCache[K, V]) Get(key K) (V, bool) {
v, _, ok := s.GetWithExpire(key)
return v, ok
}
// GetWithExpire retrieves a value and its expiration by key.
func (s *SimpleCache[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
var item *CacheValue[V]
s.itemsMu.RLock()
item, ok := s.items[key]
s.itemsMu.RUnlock()
if !ok {
s.incrMissCount()
return *new(V), time.Time{}, false
}
if item.IsExpired(s.clock.Now()) {
s.incrMissCount()
return *new(V), time.Time{}, false
}
s.incrHitCount()
return item.value, item.expireAt, true
}
// GetOrReload retrieves a value by key, automatically reloading and caching it if expired or missing.
// It uses a loader function to fetch the value and leverages loadGroup to prevent redundant loads,
// improving performance by ensuring only one load operation per key at a time.
func (s *SimpleCache[K, V]) GetOrReload(ctx context.Context, key K, loader LoaderExpireFunc[K, V]) (V, error) {
var item *CacheValue[V]
s.itemsMu.RLock()
item, ok := s.items[key]
s.itemsMu.RUnlock()
if ok && !item.IsExpired(s.clock.Now()) {
s.incrHitCount()
return item.value, nil
}
return s.reloadOrWait(key, loader, ctx)
}
func (s *SimpleCache[K, V]) GetRefreshOrReload(ctx context.Context, key K, refreshExpireAt time.Time, loader LoaderExpireFunc[K, V]) (V, error) {
v, ok := s.getRefresh(key, refreshExpireAt, false)
if ok {
s.incrHitCount()
return v, nil
}
return s.reloadOrWait(key, loader, ctx)
}
func (s *SimpleCache[K, V]) reloadOrWait(key K, loader LoaderExpireFunc[K, V], ctx context.Context) (V, error) {
var f = func(key K, ctx context.Context) (*CacheValue[V], error) {
value, expireAt, err := loader(key, ctx)
if err != nil {
return nil, err
}
var item = &CacheValue[V]{value: value, expireAt: expireAt}
s.set(key, item)
return item, err
}
item, loaderCalled, err := s.loadGroup.Do(key, f, ctx)
if err != nil {
s.incrMissCount()
return *new(V), err
}
if loaderCalled {
s.incrMissCount()
} else {
s.incrHitCount()
}
return item.value, nil
}
func (s *SimpleCache[K, V]) GetAllMap() map[K]V {
now := s.clock.Now()
var m = make(map[K]V, len(s.items))
s.itemsMu.RLock()
for k, v := range s.items {
if !v.IsExpired(now) {
m[k] = v.value
}
}
s.itemsMu.RUnlock()
return m
}
func (s *SimpleCache[K, V]) GetAll() ([]K, []V) {
now := s.clock.Now()
var retK = make([]K, 0, len(s.items))
var retV = make([]V, 0, len(s.items))
s.itemsMu.RLock()
for k, v := range s.items {
if !v.IsExpired(now) {
retK = append(retK, k)
retV = append(retV, v.value)
}
}
s.itemsMu.RUnlock()
return retK, retV
}
// Remove deletes a key from the cache, returning the value and whether it was found.
func (s *SimpleCache[K, V]) Remove(key K) (V, bool) {
s.itemsMu.Lock()
defer s.itemsMu.Unlock()
val, ok := s.items[key]
if ok {
delete(s.items, key)
val.deleted = true
return val.value, ok
}
return *new(V), ok
}
// RemoveBatch deletes multiple keys from the cache.
func (s *SimpleCache[K, V]) RemoveBatch(keys []K) {
if len(keys) == 0 {
return
}
s.itemsMu.Lock()
defer s.itemsMu.Unlock()
var val *CacheValue[V]
var ok bool
for _, k := range keys {
val, ok = s.items[k]
if ok {
delete(s.items, k)
val.deleted = true
}
}
}
// batchRemoveExpired removes only expired keys from the cache.
func (s *SimpleCache[K, V]) batchRemoveExpired(keys []K) {
if len(keys) == 0 {
return
}
now := s.clock.Now()
s.itemsMu.Lock()
defer s.itemsMu.Unlock()
var val *CacheValue[V]
var ok bool
for _, k := range keys {
val, ok = s.items[k]
if ok && val.IsExpired(now) {
delete(s.items, k)
val.deleted = true
}
}
}
// Purge clears all items from the cache.
func (s *SimpleCache[K, V]) Purge() {
s.itemsMu.Lock()
clear(s.items)
s.itemsMu.Unlock()
s.BaseCache.reset()
}
func (s *SimpleCache[K, V]) Keys() []K {
now := s.clock.Now()
var ret = make([]K, 0, len(s.items))
s.itemsMu.RLock()
for k, v := range s.items {
if !v.IsExpired(now) {
ret = append(ret, k)
}
}
s.itemsMu.RUnlock()
return ret
}
// Len returns the number of items in the cache, including expired items that have not been cleaned up yet.
func (s *SimpleCache[K, V]) Len() int {
return len(s.items)
}
func (s *SimpleCache[K, V]) Has(key K) bool {
s.itemsMu.RLock()
val, ok := s.items[key]
s.itemsMu.RUnlock()
if !ok {
return false
}
return !val.IsExpired(s.clock.Now())
}