-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
436 lines (345 loc) · 9.38 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
package lazy
import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
"github.com/moderntv/deathrow"
"github.com/rs/zerolog"
"github.com/moderntv/lazy-cache/internal/memsize"
metrics_pkg "github.com/moderntv/lazy-cache/internal/metrics"
)
const (
tllWatcherInterval = 100 * time.Millisecond
reloadWatcherInterval = 100 * time.Millisecond
automaticReloadIntervalFraction float64 = 0.9 // if automatic reload is enabled, the next reload is performed at 90% time of data expiration
minAutomaticReloadDuration = 100 * time.Millisecond
)
type Cache[K comparable, T any] struct {
// static attributes (does not change its value after initialization)
ctx context.Context
log zerolog.Logger
metrics *metrics_pkg.Metrics
name string
timeouts Timeouts
loadOneFunc LoadOneFunc[K, T]
loadMultipleFunc LoadMultipleFunc[K, T]
automaticReloadType AutomaticReload
ttlWatcher *deathrow.Prison[K]
reloadWatcher *deathrow.Prison[K]
// dynamic attributes (not using mutex)
memSizeValue atomic.Uint64
// attributes protected by mutex
mu sync.RWMutex
data map[K]*cachedEntry[T]
}
func NewCache[K comparable, T any](params Params[K, T]) (c *Cache[K, T], err error) {
err = params.check()
if err != nil {
return
}
var metrics *metrics_pkg.Metrics
if params.MetricsRegistry != nil {
metrics, err = metrics_pkg.New(params.Name, params.MetricsRegistry)
if err != nil {
return
}
}
log := params.Log.With().Str("cache", params.Name).Logger()
c = &Cache[K, T]{
ctx: params.Context,
log: log,
metrics: metrics,
name: params.Name,
timeouts: params.Timeouts,
loadOneFunc: params.LoadOneFunc,
loadMultipleFunc: params.LoadMultipleFunc,
automaticReloadType: params.AutomaticReload,
ttlWatcher: deathrow.NewPrison[K](),
reloadWatcher: deathrow.NewPrison[K](),
data: make(map[K]*cachedEntry[T]),
}
if params.PreloadChan != nil {
go c.startPreloading(params.PreloadChan)
} else {
c.log.Info().Msg("preloading disabled")
}
go c.startTTLWatcher()
if c.automaticReloadType != AutomaticReloadDisabled {
realMinReloadInterval := time.Duration(
float64(params.Timeouts.ReloadInterval.Milliseconds())*
(1-params.Timeouts.Randomizer)*
automaticReloadIntervalFraction) *
time.Millisecond
if realMinReloadInterval < minAutomaticReloadDuration {
c.log.Warn().
Dur("givenMinInterval", realMinReloadInterval).
Dur("defaultMinInterval", minAutomaticReloadDuration).
Msg("combination of automatic reload interval is too short, setting to minimum default value")
}
go c.startReloadWatcher()
} else {
c.log.Info().Msg("automatic reload disabled")
}
if c.metrics != nil && params.Timeouts.MemsizeUpdate > 0 {
go c.startMemoryMeassurement(params.Timeouts.MemsizeUpdate)
} else {
c.log.Info().Msg("memory size calculation is disabled")
}
return
}
func (c *Cache[K, T]) Get(ID K) *T {
c.mu.RLock()
entry, exists := c.data[ID]
c.mu.RUnlock()
if c.metrics != nil {
c.metrics.ReadsCount.Inc()
}
nowMillis := time.Now().UnixMilli()
// entry found in cache
if exists {
// valid value
if nowMillis < entry.nextReload.Load() {
return entry.get()
}
// data are expired, check if entry is being reloaded
entry.mu.Lock()
// check if entry was loaded by other routine during waiting for lock
if nowMillis < entry.nextReload.Load() {
entry.mu.Unlock()
return entry.get()
}
// reload entry
loadedValue, err := c.loadOneFunc(ID)
ttl := entry.set(loadedValue, err, nowMillis, &c.timeouts, false)
entry.mu.Unlock()
// update watchers
c.setEntryWatchers(ID, ttl, entry, nowMillis)
if c.metrics != nil {
c.metrics.LazyLoadCount.Inc()
if err != nil && !errors.Is(err, ErrNotFound) {
c.metrics.ErrorLoadCount.Inc()
}
}
return entry.get()
}
// not found in cache
entry = &cachedEntry[T]{}
entry.mu.Lock()
c.mu.Lock()
c.data[ID] = entry
c.mu.Unlock()
loadedValue, err := c.loadOneFunc(ID)
ttl := entry.set(loadedValue, err, nowMillis, &c.timeouts, true)
entry.mu.Unlock()
// do not store into cache when TTL is 0
if ttl == 0 {
c.mu.Lock()
delete(c.data, ID)
c.mu.Unlock()
return entry.value.Load()
}
// update watchers
c.setEntryWatchers(ID, ttl, entry, nowMillis)
if c.metrics != nil {
c.metrics.LazyLoadCount.Inc()
if err != nil && !errors.Is(err, ErrNotFound) {
c.metrics.ErrorLoadCount.Inc()
}
}
return entry.get()
}
func (c *Cache[K, T]) Remove(ID K) {
c.mu.Lock()
_, exists := c.data[ID]
if !exists {
c.mu.Unlock()
return
}
delete(c.data, ID)
c.mu.Unlock()
// remove watchers
c.ttlWatcher.Drop(ID)
c.reloadWatcher.Drop(ID)
if c.metrics != nil {
c.metrics.ItemsCount.Dec()
}
}
func (c *Cache[K, T]) Invalidate(ID K) {
c.mu.RLock()
entry, exists := c.data[ID]
c.mu.RUnlock()
if !exists {
return
}
entry.nextReload.Store(0)
if c.automaticReloadType != AutomaticReloadDisabled {
c.reloadWatcher.Push(ID, 0)
}
}
// func (c *Cache[K, T]) IsCached(ID K) bool {
// return false
// }
func (c *Cache[K, T]) startPreloading(preloadChan <-chan LoadedEntry[K, T]) {
// read data from reload channel and store it to cache
for {
select {
case loadedEntry, more := <-preloadChan:
if !more {
return
}
c.addLoadedEntry(loadedEntry, time.Now().UnixMilli())
case <-c.ctx.Done():
return
}
}
}
// addLoadedEntry adds already loaded entry to cache (if it makes sense)
func (c *Cache[K, T]) addLoadedEntry(loadedEntry LoadedEntry[K, T], nowMillis int64) {
entry := &cachedEntry[T]{}
ttl := entry.set(loadedEntry.Value, loadedEntry.Err, nowMillis, &c.timeouts, true)
ID := loadedEntry.ID
c.mu.Lock()
_, exists := c.data[ID]
// do not override existing entry in case of error (except NotFound)
if exists && loadedEntry.Err != nil && !errors.Is(loadedEntry.Err, ErrNotFound) {
c.mu.Unlock()
if c.metrics != nil {
c.metrics.ErrorLoadCount.Inc()
}
return
}
c.data[ID] = entry
c.mu.Unlock()
// update TTL watcher
c.setEntryWatchers(ID, ttl, entry, nowMillis)
if c.metrics != nil {
c.metrics.ItemsCount.Inc()
// c.memSizeValue.Add(entry.memSize())
}
}
func (c *Cache[K, T]) startTTLWatcher() {
ch := c.ttlWatcher.PopperWithResolution(c.ctx, tllWatcherInterval)
// read data from TTL watcher and remove expired entries from cache
// channel is closed when context is done
for {
item, more := <-ch
if !more {
break
}
ID := item.ID()
c.mu.Lock()
_, exists := c.data[ID]
if !exists {
c.mu.Unlock()
continue
}
delete(c.data, ID)
c.mu.Unlock()
// remove from TTL watcher
c.reloadWatcher.Drop(ID)
if c.metrics != nil {
c.metrics.ItemsCount.Dec()
}
}
}
func (c *Cache[K, T]) startReloadWatcher() {
ch := c.reloadWatcher.PopperWithResolution(c.ctx, reloadWatcherInterval)
// read data from reload watcher and reload expired entries
// channel is closed when context is done
for {
item, more := <-ch
if !more {
break
}
id := item.ID()
c.mu.Lock()
entry, exists := c.data[id]
c.mu.Unlock()
if !exists {
continue
}
// prevent unnecessary reloads of entries that are not used
// if entry is later accessed, it is lazy-reloaded
if c.automaticReloadType == AutomaticReloadAccessedEntries && !entry.accessed.Load() {
continue
}
entry.mu.Lock()
nowMillis := time.Now().UnixMilli()
loadedValue, err := c.loadOneFunc(id)
accessed := entry.accessed.Load()
ttl := entry.set(loadedValue, err, nowMillis, &c.timeouts, false)
if !accessed {
ttl = -1 // do not prolong TTL for not accessed entries
}
entry.mu.Unlock()
// update watchers
c.setEntryWatchers(id, ttl, entry, nowMillis)
if c.metrics != nil {
c.metrics.AutomaticLoadCount.Inc()
if err != nil && !errors.Is(err, ErrNotFound) {
c.metrics.ErrorLoadCount.Inc()
}
}
}
}
func (c *Cache[K, T]) setEntryWatchers(
entryID K,
ttl time.Duration,
entry *cachedEntry[T],
nowMillis int64,
) {
if ttl >= 0 {
c.ttlWatcher.Push(entryID, ttl)
}
if c.automaticReloadType == AutomaticReloadDisabled {
return
}
nextAutomaticReloadDuration := time.Duration(float64(entry.nextReload.Load()-nowMillis)*automaticReloadIntervalFraction) * time.Millisecond
if nextAutomaticReloadDuration < minAutomaticReloadDuration {
nextAutomaticReloadDuration = minAutomaticReloadDuration
}
c.reloadWatcher.Push(entryID, nextAutomaticReloadDuration)
}
func (c *Cache[K, T]) startMemoryMeassurement(interval time.Duration) {
for {
timer := time.NewTimer(interval)
select {
case <-c.ctx.Done():
timer.Stop()
return
case <-timer.C:
c.updateMemsize()
}
}
}
func (c *Cache[K, T]) updateMemsize() {
// handle potential panic (calculating size should not affect running app)
defer func() {
err := recover()
if err != nil {
c.log.Warn().
Interface("err", err).
Msg("panic occurred during cache size calculation")
}
}()
// get list of entries using read lock
c.mu.RLock()
entries := make([]*cachedEntry[T], 0, len(c.data))
for id := range c.data {
entries = append(entries, c.data[id])
}
c.mu.RUnlock()
// get memory size of each entry
var size uint64
for _, entry := range entries {
value := entry.value.Load()
if value == nil {
continue
}
size += memsize.Entry(value)
}
c.memSizeValue.Store(size)
c.metrics.MemoryUsage.Set(float64(size))
}