-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
cache.go
351 lines (294 loc) · 7 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
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
342
343
344
345
346
347
348
349
350
351
package utils
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/Laisky/golang-fifo/sieve"
"github.com/Laisky/go-utils/v5/algorithm"
"github.com/Laisky/go-utils/v5/log"
)
// NewLruCache new lru cache
func NewLruCache[K comparable, V any](size int, ttl time.Duration) *sieve.Sieve[K, V] {
return sieve.New[K, V](size, ttl)
}
// TtlCache cache with ttl
type TtlCache[T any] struct {
ctx context.Context
cancel func()
sk algorithm.SkipList[int64]
kv sync.Map
}
// NewTtlCache new cache with ttl
func NewTtlCache[T any]() *TtlCache[T] {
c := &TtlCache[T]{
sk: algorithm.NewSkiplist[int64](),
}
c.ctx, c.cancel = context.WithCancel(context.Background())
go c.clean()
return c
}
// Close close cache
func (c *TtlCache[T]) Close() {
c.cancel()
}
func (c *TtlCache[T]) clean() {
now := time.Now()
for {
select {
case <-c.ctx.Done():
return
default:
}
if c.sk.Len() == 0 {
time.Sleep(time.Second)
now = time.Now()
continue
}
ele := c.sk.Front()
if ele.Key() > now.UnixNano() {
time.Sleep(min(time.Duration(ele.Key()-now.UnixNano()), time.Second))
now = time.Now()
continue
}
c.sk.Remove(ele.Key())
}
}
// Set set data with ttl
func (c *TtlCache[T]) Set(key string, val T, ttl time.Duration) {
select {
case <-c.ctx.Done():
log.Shared.Panic("this cache already closed")
default:
}
exp := time.Now().Add(ttl)
c.sk.Set(exp.UnixNano(), key)
c.kv.Store(key, expCacheItem{exp, val})
}
// Get get data
func (c *TtlCache[T]) Get(key string) (val T, ok bool) {
select {
case <-c.ctx.Done():
log.Shared.Panic("this cache already closed")
default:
}
v, ok := c.kv.Load(key)
if !ok {
return
}
exp := v.(expCacheItem).exp //nolint:forcetypeassert
if exp.Before(time.Now()) {
c.kv.Delete(key)
c.sk.Remove(exp.UnixNano())
return
}
return v.(expCacheItem).data.(T), true //nolint:forcetypeassert
}
// Delete remove key
func (c *TtlCache[T]) Delete(key string) {
select {
case <-c.ctx.Done():
log.Shared.Panic("this cache already closed")
default:
}
vi, ok := c.kv.LoadAndDelete(key)
if ok {
c.sk.Remove(vi.(expCacheItem).exp.UnixNano()) //nolint:forcetypeassert
}
}
// SingleItemExpCache single item with expires
type SingleItemExpCache[T any] struct {
expiredAt time.Time
ttl time.Duration
data T
mu sync.RWMutex
}
// NewSingleItemExpCache new expcache contains single data
func NewSingleItemExpCache[T any](ttl time.Duration) *SingleItemExpCache[T] {
return &SingleItemExpCache[T]{
ttl: ttl,
}
}
// Set set data and refresh expires
func (c *SingleItemExpCache[T]) Set(data T) {
c.mu.Lock()
c.data = data
c.expiredAt = Clock.GetUTCNow().Add(c.ttl)
c.mu.Unlock()
}
// Get get data
//
// if data is expired, ok=false
func (c *SingleItemExpCache[T]) Get() (data T, ok bool) {
c.mu.RLock()
data = c.data
ok = Clock.GetUTCNow().Before(c.expiredAt)
c.mu.RUnlock()
return
}
// ExpCache cache with expires
//
// can Store/Load like map
type ExpCache[T any] struct {
data sync.Map
ttl time.Duration
}
type expCacheItem struct {
exp time.Time
data any
}
// ExpCacheInterface cache with expire duration
type ExpCacheInterface[T any] interface {
// Store store new key and val into cache
Store(key string, val T)
// Delete remove key
Delete(key string)
// LoadAndDelete load and delete val from cache
LoadAndDelete(key string) (data T, ok bool)
// Load load val from cache
Load(key string) (data T, ok bool)
}
// NewExpCache new cache manager
//
// use with generic:
//
// cc := NewExpCache[string](context.Background(), 100*time.Millisecond)
// cc.Store("key", "val")
// val, ok := cc.Load("key")
func NewExpCache[T any](ctx context.Context, ttl time.Duration) *ExpCache[T] {
c := &ExpCache[T]{
ttl: ttl,
}
go c.runClean(ctx)
return c
}
func (c *ExpCache[T]) runClean(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
}
now := time.Now()
c.data.Range(func(k, v any) bool {
if v.(*expCacheItem).exp.Before(now) { //nolint:forcetypeassert
// delete expired
//
// if new expCacheItem stored just before delete,
// may delete item that not expired.
// but this condition is rare, so may just add a little cost.
c.data.Delete(k)
}
return true
})
time.Sleep(c.ttl)
}
}
// Store store new key and val into cache
func (c *ExpCache[T]) Store(key string, val T) {
c.data.Store(key, &expCacheItem{
data: val,
exp: Clock.GetUTCNow().Add(c.ttl),
})
}
// Delete remove key
func (c *ExpCache[T]) Delete(key string) {
c.data.Delete(key)
}
// LoadAndDelete load and delete val from cache
func (c *ExpCache[T]) LoadAndDelete(key string) (data T, ok bool) {
//nolint:forcetypeassert
if datai, ok := c.data.LoadAndDelete(key); ok && Clock.GetUTCNow().Before(datai.(*expCacheItem).exp) {
return datai.(*expCacheItem).data.(T), ok //nolint:forcetypeassert
}
return data, false
}
// Load load val from cache
func (c *ExpCache[T]) Load(key string) (data T, ok bool) {
//nolint:forcetypeassert
if datai, ok := c.data.Load(key); ok && Clock.GetUTCNow().Before(datai.(*expCacheItem).exp) {
return datai.(*expCacheItem).data.(T), ok //nolint:forcetypeassert
} else if ok {
// delete expired
c.data.Delete(key)
}
return data, false
}
type expiredMapItem[T any] struct {
sync.RWMutex
data T
t *int64
}
func (e *expiredMapItem[T]) getTime() time.Time {
return ParseUnix2UTC(atomic.LoadInt64(e.t))
}
func (e *expiredMapItem[T]) refreshTime() {
atomic.StoreInt64(e.t, Clock.GetUTCNow().Unix())
}
// LRUExpiredMap map with expire time, auto delete expired item.
//
// `Get` will auto refresh item's expires.
// `Get` will auto create new item if key not exists.
type LRUExpiredMap[T any] struct {
m sync.Map
ttl time.Duration
new func() T
}
// NewLRUExpiredMap new ExpiredMap
func NewLRUExpiredMap[T any](ctx context.Context,
ttl time.Duration,
newIns func() T) (el *LRUExpiredMap[T], err error) {
el = &LRUExpiredMap[T]{
ttl: ttl,
new: newIns,
}
go el.clean(ctx)
return el, nil
}
func (e *LRUExpiredMap[T]) clean(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
}
now := time.Now()
e.m.Range(func(k, v any) bool {
//nolint:forcetypeassert
if v.(*expiredMapItem[T]).getTime().Add(e.ttl).After(now) {
return true
}
// lock is expired
v.(*expiredMapItem[T]).Lock() //nolint:forcetypeassert
defer v.(*expiredMapItem[T]).Unlock() //nolint:forcetypeassert
//nolint:forcetypeassert
if v.(*expiredMapItem[T]).getTime().Add(e.ttl).Before(now) {
// lock still expired
e.m.Delete(k)
}
return true
})
time.Sleep(e.ttl / 2)
}
}
// Get get item
//
// will auto refresh key's ttl
func (e *LRUExpiredMap[T]) Get(key string) T {
l, _ := e.m.Load(key)
if l == nil {
t := Clock.GetUTCNow().Unix()
l, _ = e.m.LoadOrStore(key, &expiredMapItem[T]{
t: &t,
data: e.new(),
})
} else {
ol := l.(*expiredMapItem[T]) //nolint:forcetypeassert
ol.RLock()
ol.refreshTime()
l, _ = e.m.LoadOrStore(key, ol)
ol.RUnlock()
}
//nolint:forcetypeassert
return l.(*expiredMapItem[T]).data
}