-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache.go
690 lines (637 loc) · 19.2 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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
package dcache
import (
"bytes"
"context"
"errors"
"fmt"
"reflect"
"strings"
"sync"
"time"
"github.com/coocood/freecache"
"github.com/klauspost/compress/s2"
"github.com/redis/go-redis/v9"
"github.com/rs/zerolog/log"
uuid "github.com/satori/go.uuid"
"github.com/vmihailenco/msgpack/v5"
"golang.org/x/sync/singleflight"
)
const (
lockSuffix = "_LOCK"
delimiter = "~|~"
// Duration to sleep before try to get another distributed lock for single flight.
lockSleep = 50 * time.Millisecond
// invalidate can support up to ~ (100 * 100 ops / second)
// without blocking.
redisCacheInvalidateTopic = "CacheInvalidatePubSub"
maxInvalidate = 100
invalidateChSize = 100
// the maximum read interval to warn about inappropriately large value.
maxReadInterval = 3 * time.Second
// update redis connection pool status.
connPoolUpdateInterval = 1 * time.Second
)
// Hardcap for memory cache TTL, changeable for testing.
var defaultMemCacheMaxTTLSeconds int64 = 5
var memCacheMaxTTLHardCapSeconds int64 = 120
// compression constants
const (
compressionThreshold = 64
timeLen = 4
noCompression = 0x0
s2Compression = 0x1
)
var (
// ErrTimeout is timeout error
ErrTimeout = errors.New("timeout")
// ErrInternal should never happen
ErrInternal = errors.New("internal")
// ErrNotPointer value passed to get functions is not a pointer.
ErrNotPointer = errors.New("value is not a pointer")
// ErrTypeMismatch value passed to get functions is not a pointer.
ErrTypeMismatch = errors.New("value type mismatches cached type")
)
var (
getNow = time.Now
)
// SetNowFunc is a helper function to replace time.Now(), usually used for testing.
func SetNowFunc(f func() time.Time) { getNow = f }
// ReadFunc is the actual call to underlying data source
type ReadFunc = func() (any, error)
// ReadWithTtlFunc is the actual call to underlying data source while
// returning a duration as expire timer
type ReadWithTtlFunc = func() (any, time.Duration, error)
// ValueBytesExpiredAt is how we store value and expiration time to Redis.
type ValueBytesExpiredAt struct {
ValueBytes []byte `msgpack:"v,omitempty"`
ExpiredAt int64 `msgpack:"e,omitempty"` // UNIX timestamp in Milliseconds.
}
// DCache implements cache.
type DCache struct {
conn redis.UniversalClient
readInterval time.Duration
group singleflight.Group
stats *metricSet
tracer *tracer
// In memory cache related
inMemCache *freecache.Cache
memCacheMaxTTLSeconds int64
pubsub *redis.PubSub
id string
invalidateKeys map[string]struct{}
invalidateMu *sync.Mutex
invalidateCh chan struct{}
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
}
// NewDCache creates a new cache client with in-memory cache if not @p inMemCache not nil.
// Cache MUST be explicitly closed by calling Close().
// It will also register several Prometheus metrics to the default register.
// @p readInterval specify the duration between each read per key.
func NewDCache(
appName string,
primaryClient redis.UniversalClient,
inMemCache *freecache.Cache,
readInterval time.Duration,
enableStats bool,
enableTracer bool,
) (*DCache, error) {
var stats *metricSet = nil
if enableStats {
stats = newMetricSet(appName)
stats.Register()
}
var tracer *tracer = nil
if enableTracer {
tracer = newTracer()
}
if readInterval > maxReadInterval {
log.Warn().Msgf("read interval might be too large, suggest: %s, got: %s ",
maxReadInterval.String(), readInterval.String())
}
ctx, cancel := context.WithCancel(context.Background())
c := &DCache{
conn: primaryClient,
stats: stats,
tracer: tracer,
id: uuid.NewV4().String(),
invalidateKeys: make(map[string]struct{}),
invalidateMu: &sync.Mutex{},
invalidateCh: make(chan struct{}, invalidateChSize),
inMemCache: inMemCache,
memCacheMaxTTLSeconds: defaultMemCacheMaxTTLSeconds,
readInterval: readInterval,
ctx: ctx,
cancel: cancel,
}
if inMemCache != nil {
c.pubsub = c.conn.Subscribe(ctx, redisCacheInvalidateTopic)
c.wg.Add(2)
go c.aggregateSend()
go c.listenKeyInvalidate()
}
if enableStats {
c.wg.Add(1)
go c.updateMetrics()
}
return c, nil
}
// Ping checks if the underlying redis connection is alive
func (c *DCache) Ping(ctx context.Context) error {
return c.conn.Ping(ctx).Err()
}
// Close terminates redis pubsub gracefully
func (c *DCache) Close() {
if c.pubsub != nil {
err := c.pubsub.Unsubscribe(c.ctx)
if err != nil {
log.Err(err).Msgf("failed to pubsub.Unsubscribe()")
}
err = c.pubsub.Close()
if err != nil {
log.Err(err).Msgf("failed to close pubsub")
}
}
c.cancel() // should be no-op because pubsub has been closed.
c.wg.Wait() // wait aggregateSend, listenKeyValidate and updateMetrics close.
// unregister after all go routines are closed.
if c.stats != nil {
c.stats.Unregister()
}
}
func (c *DCache) SetMemCacheMaxTTLSeconds(ttl int64) error {
if (ttl <= 0) || (ttl > memCacheMaxTTLHardCapSeconds) {
return fmt.Errorf(
"invalid ttl: %d, should be in range (0, %d]", ttl, memCacheMaxTTLHardCapSeconds)
}
c.memCacheMaxTTLSeconds = ttl
return nil
}
func (c *DCache) makeHitRecorder(label metricHitLabel, startedAt time.Time) func() {
if c.stats != nil {
return c.stats.MakeHitObserver(label, startedAt)
}
return func() {}
}
func (c *DCache) recordError(label metricErrLabel) {
if c.stats != nil {
c.stats.ObserveError(label)
}
}
func (c *DCache) traceHit(ctx context.Context, hit hitFrom) {
if c.tracer != nil {
c.tracer.TraceHitFrom(ctx, hit)
}
}
// readValue read through using f and cache to @p key if no error and not @p noStore.
// return the marshaled bytes if no error.
func (c *DCache) readValue(
ctx context.Context, key string, f ReadWithTtlFunc, noStore bool) ([]byte, error) {
c.traceHit(ctx, hitDB)
// valueTtl is an internal helper struct that bundles value and ttl.
type valueTtl struct {
Val any
Ttl time.Duration
}
// per-pod single flight for calling @p f.
// NOTE: This is mostly useful when user call cache layer with noCache flag, because
// when cache is used, call to this function is protected by a distributed lock.
rv, err, _ := c.group.Do(key, func() (any, error) {
defer c.makeHitRecorder(hitLabelDB, getNow())()
dbres, ttl, err := f()
return &valueTtl{
Val: dbres,
Ttl: ttl,
}, err
})
if err != nil {
return nil, err
}
valTtl := rv.(*valueTtl)
valueBytes, err := marshal(valTtl.Val)
if err != nil {
return nil, err
}
if !noStore {
// If failed to set cache, we do not return error because value has been
// successfully retrieved.
err := c.setKey(ctx, key, valueBytes, valTtl.Ttl, false)
if err != nil {
log.Ctx(ctx).Err(err).Msgf("Failed to set Redis cache for %s", key)
c.recordError(errLabelSetRedis)
}
}
return valueBytes, nil
}
// setKey set key in redis and inMemCache
func (c *DCache) setKey(ctx context.Context, key string, valueBytes []byte, ttl time.Duration, isExplicitSet bool) error {
ve := &ValueBytesExpiredAt{
ValueBytes: valueBytes,
ExpiredAt: getNow().Add(ttl).UnixMilli(),
}
veBytes, err := msgpack.Marshal(ve)
if err != nil {
return err
}
err = c.conn.Set(ctx, storeKey(key), veBytes, ttl).Err()
if err != nil {
return err
}
c.updateMemoryCache(ctx, key, ve, isExplicitSet)
return nil
}
// tryReadFromRedis try to read value from Redis.
func (c *DCache) tryReadFromRedis(ctx context.Context, key string) (*ValueBytesExpiredAt, error) {
veBytes, err := c.conn.Get(ctx, storeKey(key)).Bytes()
if err != nil {
return nil, err
}
ve := &ValueBytesExpiredAt{}
err = msgpack.Unmarshal(veBytes, ve)
return ve, err
}
// isExplicitSet = true, calling from Set. Otherwise, value is backfilled from Redis.
func (c *DCache) updateMemoryCache(
ctx context.Context, key string, ve *ValueBytesExpiredAt, isExplicitSet bool) {
// update memory cache.
// sub-second TTL will be ignored for memory cache.
ttl := time.UnixMilli(ve.ExpiredAt).Unix() - getNow().Unix()
if ttl > c.memCacheMaxTTLSeconds {
ttl = c.memCacheMaxTTLSeconds
}
if c.inMemCache != nil && ttl > 0 {
memValue, err := c.inMemCache.Get([]byte(storeKey(key)))
// Broadcast invalidation request only when value is explicitly set to new one,
// by Set(), instead of backfilled from Redis, and if
// (1) The value does not exist before
// so that we do not know if the new value will make any difference, or
// (2) we have value cached before and they are different from new value.
if isExplicitSet {
if err == freecache.ErrNotFound ||
(err == nil && !bytes.Equal(ve.ValueBytes, memValue)) {
c.broadcastKeyInvalidate(storeKey(key))
}
}
// ignore in memory cache error
err = c.inMemCache.Set([]byte(storeKey(key)), ve.ValueBytes, int(ttl))
if err != nil {
log.Ctx(ctx).Err(err).Msgf("Failed to set memory cache for key %s", storeKey(key))
c.recordError(errLabelSetMemCache)
}
}
}
// deleteKey delete key in redis and inMemCache
func (c *DCache) deleteKey(ctx context.Context, key string) error {
n, err := c.conn.Del(ctx, storeKey(key)).Result()
if err != nil {
return err
}
if n > 0 {
if c.inMemCache != nil {
c.inMemCache.Del([]byte(storeKey(key)))
c.broadcastKeyInvalidate(key)
}
}
return nil
}
// broadcastKeyInvalidate pushes key into a list and wait for broadcast
func (c *DCache) broadcastKeyInvalidate(key string) {
c.invalidateMu.Lock()
c.invalidateKeys[storeKey(key)] = struct{}{}
l := len(c.invalidateKeys)
c.invalidateMu.Unlock()
if l == maxInvalidate {
c.invalidateCh <- struct{}{}
}
}
// aggregateSend waits for 1 seconds or list accumulating more than maxInvalidate
// to send to redis pubsub
func (c *DCache) aggregateSend() {
defer c.wg.Done()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
case <-c.invalidateCh:
case <-c.ctx.Done():
return
}
c.wg.Add(1)
go func() {
defer c.wg.Done()
c.invalidateMu.Lock()
if len(c.invalidateKeys) == 0 {
c.invalidateMu.Unlock()
return
}
toSend := c.invalidateKeys
c.invalidateKeys = make(map[string]struct{})
c.invalidateMu.Unlock()
keys := make([]string, 0)
for key := range toSend {
keys = append(keys, key)
}
msg := c.id + delimiter + strings.Join(keys, delimiter)
c.conn.Publish(c.ctx, redisCacheInvalidateTopic, msg)
}()
}
}
// listenKeyInvalidate subscribe to invalidate key requests and invalidates memory cache.
func (c *DCache) listenKeyInvalidate() {
defer c.wg.Done()
ch := c.pubsub.Channel()
for {
msg, ok := <-ch
if !ok {
return
}
payload := msg.Payload
c.wg.Add(1)
go func(payload string) {
defer c.wg.Done()
l := strings.Split(payload, delimiter)
if len(l) < 2 {
// Invalid payload
log.Error().Msgf("Received invalidate payload %s", payload)
c.recordError(errLabelInvalidate)
return
}
if l[0] == c.id {
// Receive message from self
return
}
// Invalidate key
for _, key := range l[1:] {
c.inMemCache.Del([]byte(key))
}
}(payload)
}
}
func (c *DCache) updateMetrics() {
defer c.wg.Done()
if c.stats == nil {
return
}
ticker := time.NewTicker(connPoolUpdateInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
case <-c.ctx.Done():
return
}
stats := c.conn.PoolStats()
c.stats.UpdateConnPoolStatus(stats.TotalConns, stats.IdleConns)
}
}
func storeKey(key string) string {
return fmt.Sprintf(":{%s}", key)
}
func lockKey(key string) string {
return fmt.Sprintf(":%s%s", storeKey(key), lockSuffix)
}
// Get will read the value from cache if exists or call read() to retrieve the value and
// cache it in both the memory and Redis by @p ttl.
// Inputs:
// @p key: Key used in cache
// @p value: A pointer to the memory piece of the type of the value.
//
// For example, if we are caching string, then target must be of type *string.
// if we caching a null-able string, using *string to represent it, then the
// target must be of type **string, i.e., pointer to the pointer of string.
//
// @p ttl: Expiration of cache key
// @p read: Actual call that hits underlying data source.
// @p noCache: The response value will be fetched through @p read(). The new value will be
//
// cached, unless @p noStore is specified.
//
// @p noStore: The response value will not be saved into the cache.
func (c *DCache) Get(ctx context.Context, key string, target any, expire time.Duration, read ReadFunc, noCache bool, noStore bool) error {
readWithTtl := func() (any, time.Duration, error) {
res, err := read()
return res, expire, err
}
return c.GetWithTtl(ctx, key, target, readWithTtl, noCache, noStore)
}
// GetWithTtl will read the value from cache if exists or call @p read to retrieve the value and
// cache it in both the memory and Redis by the ttl returned in @p read.
// Inputs:
// @p key: Key used in cache
// @p value: A pointer to the memory piece of the type of the value.
//
// For example, if we are caching string, then target must be of type *string.
// if we caching a null-able string, using *string to represent it, then the
// target must be of type **string, i.e., pointer to the pointer of string.
//
// @p read: Actual call that hits underlying data source that also returns a ttl for cache.
// @p noCache: The response value will be fetched through @p read(). The new value will be
//
// cached, unless @p noStore is specified.
//
// @p noStore: The response value will not be saved into the cache.
func (c *DCache) GetWithTtl(ctx context.Context, key string, target any, read ReadWithTtlFunc, noCache bool, noStore bool) (err error) {
startedAt := getNow()
if c.tracer != nil {
ctx = c.tracer.TraceStart(ctx,
"GetWithTtl",
[]string{
fmt.Sprintf("key=%s", key),
fmt.Sprintf("noCache=%v", noCache),
fmt.Sprintf("noStore=%v", noStore),
})
defer c.tracer.TraceEnd(ctx, err)
}
if noCache {
var targetBytes []byte
targetBytes, err = c.readValue(ctx, key, read, noStore)
if err != nil {
return
}
err = unmarshal(targetBytes, target)
return
}
// lookup in memory cache, return only when unmarshal succeeded.
if c.inMemCache != nil {
var targetBytes []byte
targetBytes, err = c.inMemCache.Get([]byte(storeKey(key)))
if err == nil {
err = unmarshal(targetBytes, target)
if err == nil {
c.makeHitRecorder(hitLabelMemory, startedAt)()
c.traceHit(ctx, hitMem)
return
} else {
log.Ctx(ctx).Err(err).Msgf("Failed to unmarshal from memory cache for %s", key)
c.recordError(errLabelMemoryUnmarshalFailed)
}
}
}
var anyTypedBytes any
var targetHasUnmarshalled bool
anyTypedBytes, err, _ = c.group.Do(lockKey(key), func() (any, error) {
// distributed single flight to query db for value.
for {
ve, e := c.tryReadFromRedis(ctx, key)
if e == nil {
// NOTE: must check if bytes stored in Redis can be correctly
// unmarshalled into target, because it may not when data structure changes.
// When that happens, we will still fetch from DB.
e = unmarshal(ve.ValueBytes, target)
if e == nil {
targetHasUnmarshalled = true
// Value was retrieved from Redis, backfill memory cache and return.
defer c.makeHitRecorder(hitLabelRedis, startedAt)()
c.traceHit(ctx, hitRedis)
if !noStore {
c.updateMemoryCache(ctx, key, ve, false)
}
return ve.ValueBytes, nil
} else {
log.Ctx(ctx).Err(err).Msgf("Failed to unmarshal from Redis for %s", key)
c.recordError(errLabelRedisUnmarshalFailed)
}
}
// If failed to retrieve value from Redis, try to get a lock and query DB.
// To avoid spamming Redis with SetNX requests, only one request should try to get
// the lock per-pod.
// If timeout or not cache-able error, another thread will obtain lock after sleep.
updated, err := c.conn.SetNX(ctx, lockKey(key), "", c.readInterval).Result()
if err != nil {
log.Ctx(ctx).Err(err).Msgf("Failed to get lock by SetNX for %s", key)
c.recordError(errLabelSetRedis)
}
if updated {
return c.readValue(ctx, key, read, noStore)
}
// Did not obtain lock, sleep and retry to wait for update
select {
case <-ctx.Done():
// NOTE: for requests grouped into one flight, if the earliest request
// timeout, all of them will timeout.
return nil, ErrTimeout
case <-time.After(lockSleep):
// TODO(yumin): we can further optimize this part by
// check TTL of lockKey(key), and sleep wisely.
continue
}
}
})
if err != nil {
return
}
if !targetHasUnmarshalled {
err = unmarshal(anyTypedBytes.([]byte), target)
}
return
}
// Invalidate explicitly invalidates a cache key
// Inputs:
// key - key to invalidate
func (c *DCache) Invalidate(ctx context.Context, key string) (err error) {
if c.tracer != nil {
ctx = c.tracer.TraceStart(ctx, "Invalidate", []string{fmt.Sprintf("key=%s", key)})
defer c.tracer.TraceEnd(ctx, nil)
}
err = c.deleteKey(ctx, key)
return
}
// Set explicitly set a cache key to a val
// Inputs:
// key - key to set
// val - val to set
// ttl - ttl of key
func (c *DCache) Set(ctx context.Context, key string, val any, ttl time.Duration) (err error) {
if c.tracer != nil {
ctx = c.tracer.TraceStart(ctx, "Set",
[]string{
fmt.Sprintf("key=%s", key),
fmt.Sprintf("ttl=%s", ttl),
})
defer c.tracer.TraceEnd(ctx, err)
}
bs, err := marshal(val)
if err != nil {
return
}
err = c.setKey(ctx, key, bs, ttl, true)
return
}
// compress data with s2. Add 1 suffix byte to indicate if it is cached.
func compress(data []byte) []byte {
if len(data) < compressionThreshold {
n := len(data) + 1
b := make([]byte, n, n+timeLen)
copy(b, data)
b[len(b)-1] = noCompression
return b
}
n := s2.MaxEncodedLen(len(data)) + 1
b := make([]byte, n, n+timeLen)
b = s2.Encode(b, data)
b = append(b, s2Compression)
return b
}
// marshal @p value into returned bytes, with compression.
// copy from https://github.com/go-redis/cache/blob/v8/cache.go
func marshal(value interface{}) ([]byte, error) {
switch value := value.(type) {
case nil:
return nil, nil
case []byte:
return value, nil
case string:
return []byte(value), nil
}
b, err := msgpack.Marshal(value)
if err != nil {
return nil, err
}
return compress(b), nil
}
// unmarshal @p b into @p value.
// copy from https://github.com/go-redis/cache/blob/v8/cache.go
func unmarshal(b []byte, value interface{}) error {
if reflect.ValueOf(value).Kind() != reflect.Ptr {
return ErrNotPointer
}
if len(b) == 0 {
// if we cache nil or any zero value, must set *value to
// the same zero value.
v := reflect.ValueOf(value)
if v.Elem().CanSet() {
v.Elem().Set(reflect.Zero(v.Elem().Type()))
} else {
return ErrTypeMismatch
}
return nil
}
switch value := value.(type) {
case nil:
return nil
case *[]byte:
clone := make([]byte, len(b))
copy(clone, b)
*value = clone
return nil
case *string:
*value = string(b)
return nil
}
switch c := b[len(b)-1]; c {
case noCompression:
b = b[:len(b)-1]
case s2Compression:
b = b[:len(b)-1]
var err error
b, err = s2.Decode(nil, b)
if err != nil {
return err
}
default:
return fmt.Errorf("unknown compression method: %x", c)
}
return msgpack.Unmarshal(b, value)
}