-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathcache_impl.go
More file actions
1871 lines (1672 loc) · 51.3 KB
/
cache_impl.go
File metadata and controls
1871 lines (1672 loc) · 51.3 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
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2023 Alexey Mayshev and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package otter
import (
"cmp"
"context"
"errors"
"fmt"
"iter"
"math"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/maypok86/otter/v2/internal/deque/queue"
"github.com/maypok86/otter/v2/internal/expiration"
"github.com/maypok86/otter/v2/internal/generated/node"
"github.com/maypok86/otter/v2/internal/hashmap"
"github.com/maypok86/otter/v2/internal/lossy"
"github.com/maypok86/otter/v2/internal/xiter"
"github.com/maypok86/otter/v2/internal/xmath"
"github.com/maypok86/otter/v2/internal/xruntime"
"github.com/maypok86/otter/v2/stats"
)
const (
unreachableExpiresAt = int64(xruntime.MaxDuration)
unreachableRefreshableAt = int64(xruntime.MaxDuration)
noTime = int64(0)
minWriteBufferSize = 4
writeBufferRetries = 100
)
const (
// A drain is not taking place.
idle uint32 = 0
// A drain is required due to a pending write modification.
required uint32 = 1
// A drain is in progress and will transition to idle.
processingToIdle uint32 = 2
// A drain is in progress and will transition to required.
processingToRequired uint32 = 3
)
var (
maxWriteBufferSize uint32
maxStripedBufferSize int
)
func init() {
parallelism := xruntime.Parallelism()
roundedParallelism := int(xmath.RoundUpPowerOf2(parallelism))
//nolint:gosec // there will never be an overflow
maxWriteBufferSize = uint32(128 * roundedParallelism)
maxStripedBufferSize = 4 * roundedParallelism
}
func zeroValue[V any]() V {
var v V
return v
}
// cache is a structure performs a best-effort bounding of a hash table using eviction algorithm
// to determine which entries to evict when the capacity is exceeded.
type cache[K comparable, V any] struct {
drainStatus atomic.Uint32
_ [xruntime.CacheLineSize - 4]byte
nodeManager *node.Manager[K, V]
hashmap *hashmap.Map[K, V, node.Node[K, V]]
evictionPolicy *policy[K, V]
expirationPolicy *expiration.Variable[K, V]
stats stats.Recorder
statsSnapshoter stats.Snapshoter
logger Logger
clock timeSource
statsClock *realSource
readBuffer *lossy.Striped[K, V]
writeBuffer *queue.MPSC[task[K, V]]
executor func(fn func())
singleflight *group[K, V]
evictionMutex sync.Mutex
doneStop chan struct{}
stopOnce sync.Once
weigher func(key K, value V) uint32
onDeletion func(e DeletionEvent[K, V])
onAtomicDeletion func(e DeletionEvent[K, V])
expiryCalculator ExpiryCalculator[K, V]
refreshCalculator RefreshCalculator[K, V]
taskPool sync.Pool
hasDefaultExecutor bool
withTime bool
withExpiration bool
withRefresh bool
withEviction bool
isWeighted bool
withMaintenance bool
withStats bool
}
// newCache returns a new cache instance based on the settings from Options.
func newCache[K comparable, V any](o *Options[K, V]) *cache[K, V] {
withWeight := o.MaximumWeight > 0
nodeManager := node.NewManager[K, V](node.Config{
WithSize: o.MaximumSize > 0,
WithExpiration: o.ExpiryCalculator != nil,
WithRefresh: o.RefreshCalculator != nil,
WithWeight: withWeight,
})
maximum := o.getMaximum()
withEviction := maximum > 0
withStats := o.StatsRecorder != nil
if withStats {
_, ok := o.StatsRecorder.(*stats.NoopRecorder)
withStats = !ok
}
statsRecorder := o.StatsRecorder
if !withStats {
statsRecorder = &stats.NoopRecorder{}
}
var statsSnapshoter stats.Snapshoter
if snapshoter, ok := statsRecorder.(stats.Snapshoter); ok {
statsSnapshoter = snapshoter
} else {
statsSnapshoter = &stats.NoopRecorder{}
}
c := &cache[K, V]{
nodeManager: nodeManager,
hashmap: hashmap.NewWithSize[K, V, node.Node[K, V]](nodeManager, o.getInitialCapacity()),
stats: statsRecorder,
statsSnapshoter: statsSnapshoter,
logger: o.getLogger(),
singleflight: &group[K, V]{},
executor: o.getExecutor(),
hasDefaultExecutor: o.Executor == nil,
weigher: o.getWeigher(),
onDeletion: o.OnDeletion,
onAtomicDeletion: o.OnAtomicDeletion,
clock: newTimeSource(o.Clock),
statsClock: &realSource{},
expiryCalculator: o.ExpiryCalculator,
refreshCalculator: o.RefreshCalculator,
isWeighted: withWeight,
withStats: withStats,
}
if withStats {
c.statsClock.Init()
}
c.withEviction = withEviction
if c.withEviction {
c.evictionPolicy = newPolicy[K, V](withWeight)
if o.hasInitialCapacity() {
//nolint:gosec // there's no overflow
c.evictionPolicy.sketch.ensureCapacity(min(maximum, uint64(o.getInitialCapacity())))
}
}
if o.ExpiryCalculator != nil {
c.expirationPolicy = expiration.NewVariable(nodeManager)
}
c.withExpiration = o.ExpiryCalculator != nil
c.withRefresh = o.RefreshCalculator != nil
c.withTime = c.withExpiration || c.withRefresh
c.withMaintenance = c.withEviction || c.withExpiration
if c.withMaintenance {
c.readBuffer = lossy.NewStriped(maxStripedBufferSize, nodeManager)
c.writeBuffer = queue.NewMPSC[task[K, V]](minWriteBufferSize, maxWriteBufferSize)
}
if c.withTime {
c.clock.Init()
}
if c.withExpiration {
c.doneStop = make(chan struct{})
go c.periodicCleanUp()
}
if c.withEviction {
c.SetMaximum(maximum)
}
return c
}
func (c *cache[K, V]) newNode(key K, value V, old node.Node[K, V]) node.Node[K, V] {
weight := c.weigher(key, value)
expiresAt := unreachableExpiresAt
if c.withExpiration && old != nil {
expiresAt = old.ExpiresAt()
}
refreshableAt := unreachableRefreshableAt
if c.withRefresh && old != nil {
refreshableAt = old.RefreshableAt()
}
return c.nodeManager.Create(key, value, expiresAt, refreshableAt, weight)
}
func (c *cache[K, V]) nodeToEntry(n node.Node[K, V], nanos int64) Entry[K, V] {
nowNano := noTime
if c.withTime {
nowNano = nanos
}
expiresAt := unreachableExpiresAt
if c.withExpiration {
expiresAt = n.ExpiresAt()
}
refreshableAt := unreachableRefreshableAt
if c.withRefresh {
refreshableAt = n.RefreshableAt()
}
return Entry[K, V]{
Key: n.Key(),
Value: n.Value(),
Weight: n.Weight(),
ExpiresAtNano: expiresAt,
RefreshableAtNano: refreshableAt,
SnapshotAtNano: nowNano,
}
}
// has checks if there is an item with the given key in the cache.
func (c *cache[K, V]) has(key K) bool {
_, ok := c.GetIfPresent(key)
return ok
}
// GetIfPresent returns the value associated with the key in this cache.
func (c *cache[K, V]) GetIfPresent(key K) (V, bool) {
nowNano := c.clock.NowNano()
n := c.getNode(key, nowNano)
if n == nil {
return zeroValue[V](), false
}
return n.Value(), true
}
// getNode returns the node associated with the key in this cache.
func (c *cache[K, V]) getNode(key K, nowNano int64) node.Node[K, V] {
n := c.hashmap.Get(key)
if n == nil {
c.stats.RecordMisses(1)
if c.drainStatus.Load() == required {
c.scheduleDrainBuffers()
}
return nil
}
if n.HasExpired(nowNano) {
c.stats.RecordMisses(1)
c.scheduleDrainBuffers()
return nil
}
c.afterRead(n, nowNano, true, true)
return n
}
// getNodeQuietly returns the node associated with the key in this cache.
//
// Unlike getNode, this function does not produce any side effects
// such as updating statistics or the eviction policy.
func (c *cache[K, V]) getNodeQuietly(key K, nowNano int64) node.Node[K, V] {
n := c.hashmap.Get(key)
if n == nil || !n.IsAlive() || n.HasExpired(nowNano) {
return nil
}
return n
}
func (c *cache[K, V]) afterRead(got node.Node[K, V], nowNano int64, recordHit, calcExpiresAt bool) {
if recordHit {
c.stats.RecordHits(1)
}
if calcExpiresAt {
c.calcExpiresAtAfterRead(got, nowNano)
}
delayable := c.skipReadBuffer() || c.readBuffer.Add(got) != lossy.Full
if c.shouldDrainBuffers(delayable) {
c.scheduleDrainBuffers()
}
}
// Set associates the value with the key in this cache.
//
// If the specified key is not already associated with a value, then it returns new value and true.
//
// If the specified key is already associated with a value, then it returns existing value and false.
func (c *cache[K, V]) Set(key K, value V) (V, bool) {
return c.set(key, value, false)
}
// SetIfAbsent if the specified key is not already associated with a value associates it with the given value.
//
// If the specified key is not already associated with a value, then it returns new value and true.
//
// If the specified key is already associated with a value, then it returns existing value and false.
func (c *cache[K, V]) SetIfAbsent(key K, value V) (V, bool) {
return c.set(key, value, true)
}
func (c *cache[K, V]) calcExpiresAtAfterRead(n node.Node[K, V], nowNano int64) {
if !c.withExpiration {
return
}
expiresAfter := c.expiryCalculator.ExpireAfterRead(c.nodeToEntry(n, nowNano))
c.setExpiresAfterRead(n, nowNano, expiresAfter)
}
func (c *cache[K, V]) setExpiresAfterRead(n node.Node[K, V], nowNano int64, expiresAfter time.Duration) {
if expiresAfter <= 0 {
return
}
expiresAt := n.ExpiresAt()
currentDuration := time.Duration(expiresAt - nowNano)
diff := xmath.Abs(int64(expiresAfter - currentDuration))
if diff > 0 {
n.CASExpiresAt(expiresAt, nowNano+int64(expiresAfter))
}
}
// GetEntry returns the cache entry associated with the key in this cache.
func (c *cache[K, V]) GetEntry(key K) (Entry[K, V], bool) {
nowNano := c.clock.NowNano()
n := c.getNode(key, nowNano)
if n == nil {
return Entry[K, V]{}, false
}
return c.nodeToEntry(n, nowNano), true
}
// GetEntryQuietly returns the cache entry associated with the key in this cache.
//
// Unlike GetEntry, this function does not produce any side effects
// such as updating statistics or the eviction policy.
func (c *cache[K, V]) GetEntryQuietly(key K) (Entry[K, V], bool) {
nowNano := c.clock.NowNano()
n := c.getNodeQuietly(key, nowNano)
if n == nil {
return Entry[K, V]{}, false
}
return c.nodeToEntry(n, nowNano), true
}
// SetExpiresAfter specifies that the entry should be automatically removed from the cache once the duration has
// elapsed. The expiration policy determines when the entry's age is reset.
func (c *cache[K, V]) SetExpiresAfter(key K, expiresAfter time.Duration) {
if !c.withExpiration || expiresAfter <= 0 {
return
}
nowNano := c.clock.NowNano()
n := c.hashmap.Get(key)
if n == nil {
return
}
c.setExpiresAfterRead(n, nowNano, expiresAfter)
c.afterRead(n, nowNano, false, false)
}
// SetRefreshableAfter specifies that each entry should be eligible for reloading once a fixed duration has elapsed.
// The refresh policy determines when the entry's age is reset.
func (c *cache[K, V]) SetRefreshableAfter(key K, refreshableAfter time.Duration) {
if !c.withRefresh || refreshableAfter <= 0 {
return
}
nowNano := c.clock.NowNano()
n := c.hashmap.Get(key)
if n == nil {
return
}
entry := c.nodeToEntry(n, nowNano)
currentDuration := entry.RefreshableAfter()
if refreshableAfter > 0 && currentDuration != refreshableAfter {
n.SetRefreshableAt(nowNano + int64(refreshableAfter))
}
}
func (c *cache[K, V]) calcExpiresAtAfterWrite(n, old node.Node[K, V], nowNano int64) {
if !c.withExpiration {
return
}
entry := c.nodeToEntry(n, nowNano)
currentDuration := entry.ExpiresAfter()
var expiresAfter time.Duration
if old == nil || old.HasExpired(nowNano) {
expiresAfter = c.expiryCalculator.ExpireAfterCreate(entry)
} else {
expiresAfter = c.expiryCalculator.ExpireAfterUpdate(entry, old.Value())
}
if expiresAfter > 0 && currentDuration != expiresAfter {
n.SetExpiresAt(nowNano + int64(expiresAfter))
}
}
func (c *cache[K, V]) set(key K, value V, onlyIfAbsent bool) (V, bool) {
var old node.Node[K, V]
nowNano := c.clock.NowNano()
n := c.hashmap.Compute(key, func(current node.Node[K, V]) node.Node[K, V] {
old = current
if onlyIfAbsent && current != nil && !current.HasExpired(nowNano) {
// no op
c.calcExpiresAtAfterRead(old, nowNano)
return current
}
// set
return c.atomicSet(key, value, old, nil, nowNano)
})
if onlyIfAbsent {
if old == nil || old.HasExpired(nowNano) {
c.afterWrite(n, old, nowNano)
return value, true
}
c.afterRead(old, nowNano, false, false)
return old.Value(), false
}
c.afterWrite(n, old, nowNano)
if old != nil {
return old.Value(), false
}
return value, true
}
func (c *cache[K, V]) atomicSet(key K, value V, old node.Node[K, V], cl *call[K, V], nowNano int64) node.Node[K, V] {
if cl == nil {
c.singleflight.delete(key)
}
n := c.newNode(key, value, old)
c.calcExpiresAtAfterWrite(n, old, nowNano)
c.calcRefreshableAt(n, old, cl, nowNano)
c.makeRetired(old)
if old != nil {
cause := getCause(old, nowNano, CauseReplacement)
c.notifyAtomicDeletion(old.Key(), old.Value(), cause)
}
return n
}
//nolint:unparam // it's ok
func (c *cache[K, V]) atomicDelete(key K, old node.Node[K, V], cl *call[K, V], nowNano int64) node.Node[K, V] {
if cl == nil {
c.singleflight.delete(key)
}
if old != nil {
cause := getCause(old, nowNano, CauseInvalidation)
c.makeRetired(old)
c.notifyAtomicDeletion(old.Key(), old.Value(), cause)
}
return nil
}
// Compute either sets the computed new value for the key,
// invalidates the value for the key, or does nothing, based on
// the returned [ComputeOp]. When the op returned by remappingFunc
// is [WriteOp], the value is updated to the new value. If
// it is [InvalidateOp], the entry is removed from the cache
// altogether. And finally, if the op is [CancelOp] then the
// entry is left as-is. In other words, if it did not already
// exist, it is not created, and if it did exist, it is not
// updated. This is useful to synchronously execute some
// operation on the value without incurring the cost of
// updating the cache every time.
//
// The ok result indicates whether the entry is present in the cache after the compute operation.
// The actualValue result contains the value of the cache
// if a corresponding entry is present, or the zero value otherwise.
// You can think of these results as equivalent to regular key-value lookups in a map.
//
// This call locks a hash table bucket while the compute function
// is executed. It means that modifications on other entries in
// the bucket will be blocked until the remappingFunc executes. Consider
// this when the function includes long-running operations.
func (c *cache[K, V]) Compute(
key K,
remappingFunc func(oldValue V, found bool) (newValue V, op ComputeOp),
) (V, bool) {
return c.doCompute(key, remappingFunc, c.clock.NowNano(), true)
}
// ComputeIfAbsent returns the existing value for the key if
// present. Otherwise, it tries to compute the value using the
// provided function. If mappingFunc returns true as the cancel value, the computation is cancelled and the zero value
// for type V is returned.
//
// The ok result indicates whether the entry is present in the cache after the compute operation.
// The actualValue result contains the value of the cache
// if a corresponding entry is present, or the zero value
// otherwise. You can think of these results as equivalent to regular key-value lookups in a map.
//
// This call locks a hash table bucket while the compute function
// is executed. It means that modifications on other entries in
// the bucket will be blocked until the valueFn executes. Consider
// this when the function includes long-running operations.
func (c *cache[K, V]) ComputeIfAbsent(
key K,
mappingFunc func() (newValue V, cancel bool),
) (V, bool) {
nowNano := c.clock.NowNano()
if n := c.getNode(key, nowNano); n != nil {
return n.Value(), true
}
return c.doCompute(key, func(oldValue V, found bool) (newValue V, op ComputeOp) {
if found {
return oldValue, CancelOp
}
newValue, cancel := mappingFunc()
if cancel {
return zeroValue[V](), CancelOp
}
return newValue, WriteOp
}, nowNano, false)
}
// ComputeIfPresent returns the zero value for type V if the key is not found.
// Otherwise, it tries to compute the value using the provided function.
//
// ComputeIfPresent either sets the computed new value for the key,
// invalidates the value for the key, or does nothing, based on
// the returned [ComputeOp]. When the op returned by remappingFunc
// is [WriteOp], the value is updated to the new value. If
// it is [InvalidateOp], the entry is removed from the cache
// altogether. And finally, if the op is [CancelOp] then the
// entry is left as-is. In other words, if it did not already
// exist, it is not created, and if it did exist, it is not
// updated. This is useful to synchronously execute some
// operation on the value without incurring the cost of
// updating the cache every time.
//
// The ok result indicates whether the entry is present in the cache after the compute operation.
// The actualValue result contains the value of the cache
// if a corresponding entry is present, or the zero value
// otherwise. You can think of these results as equivalent to regular key-value lookups in a map.
//
// This call locks a hash table bucket while the compute function
// is executed. It means that modifications on other entries in
// the bucket will be blocked until the valueFn executes. Consider
// this when the function includes long-running operations.
func (c *cache[K, V]) ComputeIfPresent(
key K,
remappingFunc func(oldValue V) (newValue V, op ComputeOp),
) (V, bool) {
nowNano := c.clock.NowNano()
if n := c.getNode(key, nowNano); n == nil {
return zeroValue[V](), false
}
return c.doCompute(key, func(oldValue V, found bool) (newValue V, op ComputeOp) {
if found {
return remappingFunc(oldValue)
}
return zeroValue[V](), CancelOp
}, nowNano, false)
}
func (c *cache[K, V]) doCompute(
key K,
remappingFunc func(oldValue V, found bool) (newValue V, op ComputeOp),
nowNano int64,
recordStats bool,
) (V, bool) {
var (
old node.Node[K, V]
op ComputeOp
notValidOp bool
panicErr error
)
computedNode := c.hashmap.Compute(key, func(oldNode node.Node[K, V]) node.Node[K, V] {
var (
oldValue V
actualValue V
found bool
)
if oldNode != nil && !oldNode.HasExpired(nowNano) {
oldValue = oldNode.Value()
found = true
}
old = oldNode
func() {
defer func() {
if r := recover(); r != nil {
panicErr = newPanicError(r)
}
}()
actualValue, op = remappingFunc(oldValue, found)
}()
if panicErr != nil {
return oldNode
}
if op == CancelOp {
if oldNode != nil && oldNode.HasExpired(nowNano) {
return c.atomicDelete(key, oldNode, nil, nowNano)
}
return oldNode
}
if op == WriteOp {
return c.atomicSet(key, actualValue, old, nil, nowNano)
}
if op == InvalidateOp {
return c.atomicDelete(key, old, nil, nowNano)
}
notValidOp = true
return oldNode
})
if panicErr != nil {
panic(panicErr)
}
if notValidOp {
panic(fmt.Sprintf("otter: invalid ComputeOp: %d", op))
}
if recordStats {
if old != nil && !old.HasExpired(nowNano) {
c.stats.RecordHits(1)
} else {
c.stats.RecordMisses(1)
}
}
switch op {
case CancelOp:
if computedNode == nil {
c.afterDelete(old, nowNano, false)
return zeroValue[V](), false
}
return computedNode.Value(), true
case WriteOp:
c.afterWrite(computedNode, old, nowNano)
case InvalidateOp:
c.afterDelete(old, nowNano, false)
}
if computedNode == nil {
return zeroValue[V](), false
}
return computedNode.Value(), true
}
func (c *cache[K, V]) afterWrite(n, old node.Node[K, V], nowNano int64) {
if !c.withMaintenance {
if old != nil {
c.notifyDeletion(old.Key(), old.Value(), CauseReplacement)
}
return
}
if old == nil {
// insert
c.afterWriteTask(c.getTask(n, nil, addReason, causeUnknown))
return
}
// update
cause := getCause(old, nowNano, CauseReplacement)
c.afterWriteTask(c.getTask(n, old, updateReason, cause))
}
type refreshableKey[K comparable, V any] struct {
key K
old node.Node[K, V]
}
func (c *cache[K, V]) refreshKey(
ctx context.Context,
rk refreshableKey[K, V],
loader Loader[K, V],
isManual bool,
) <-chan RefreshResult[K, V] {
if !c.withRefresh {
return nil
}
var ch chan RefreshResult[K, V]
if isManual {
ch = make(chan RefreshResult[K, V], 1)
}
c.executor(func() {
var refresher func(ctx context.Context, key K) (V, error)
if rk.old != nil {
refresher = func(ctx context.Context, key K) (V, error) {
return loader.Reload(ctx, key, rk.old.Value())
}
} else {
refresher = loader.Load
}
cl, shouldLoad := c.singleflight.startCall(rk.key, true)
if shouldLoad {
//nolint:errcheck // there is no need to check error
_ = c.wrapLoad(func() error {
loadCtx := context.WithoutCancel(ctx)
return c.singleflight.doCall(loadCtx, cl, refresher, c.afterDeleteCall)
})
}
cl.wait()
if cl.err != nil && !cl.isNotFound {
c.logger.Error(ctx, "Returned an error during the refreshing", cl.err)
}
if isManual {
ch <- RefreshResult[K, V]{
Key: cl.key,
Value: cl.value,
Err: cl.err,
}
}
})
return ch
}
// Get returns the value associated with key in this cache, obtaining that value from loader if necessary.
// The method improves upon the conventional "if cached, return; otherwise create, cache and return" pattern.
//
// Get can return an ErrNotFound error if the Loader returns it.
// This means that the entry was not found in the data source.
//
// If another call to Get is currently loading the value for key,
// simply waits for that goroutine to finish and returns its loaded value. Note that
// multiple goroutines can concurrently load values for distinct keys.
//
// No observable state associated with this cache is modified until loading completes.
//
// WARNING: Loader.Load must not attempt to update any mappings of this cache directly.
//
// WARNING: For any given key, every loader used with it should compute the same value.
// Otherwise, a call that passes one loader may return the result of another call
// with a differently behaving loader. For example, a call that requests a short timeout
// for an RPC may wait for a similar call that requests a long timeout, or a call by an
// unprivileged user may return a resource accessible only to a privileged user making a similar call.
func (c *cache[K, V]) Get(ctx context.Context, key K, loader Loader[K, V]) (V, error) {
c.singleflight.init()
nowNano := c.clock.NowNano()
n := c.getNode(key, nowNano)
if n != nil {
if !n.IsFresh(nowNano) {
c.refreshKey(ctx, refreshableKey[K, V]{
key: n.Key(),
old: n,
}, loader, false)
}
return n.Value(), nil
}
cl, shouldLoad := c.singleflight.startCall(key, false)
if shouldLoad {
//nolint:errcheck // there is no need to check error
_ = c.wrapLoad(func() error {
return c.singleflight.doCall(ctx, cl, loader.Load, c.afterDeleteCall)
})
}
cl.wait()
return cl.value, cl.err
}
func (c *cache[K, V]) calcRefreshableAt(n, old node.Node[K, V], cl *call[K, V], nowNano int64) {
if !c.withRefresh {
return
}
var refreshableAfter time.Duration
entry := c.nodeToEntry(n, nowNano)
currentDuration := entry.RefreshableAfter()
//nolint:gocritic // it's ok
if cl != nil && cl.isRefresh && old != nil {
if cl.isNotFound {
return
}
if cl.err != nil {
refreshableAfter = c.refreshCalculator.RefreshAfterReloadFailure(entry, cl.err)
} else {
refreshableAfter = c.refreshCalculator.RefreshAfterReload(entry, old.Value())
}
} else if old != nil {
refreshableAfter = c.refreshCalculator.RefreshAfterUpdate(entry, old.Value())
} else {
refreshableAfter = c.refreshCalculator.RefreshAfterCreate(entry)
}
if refreshableAfter > 0 && currentDuration != refreshableAfter {
n.SetRefreshableAt(nowNano + int64(refreshableAfter))
}
}
func (c *cache[K, V]) afterDeleteCall(cl *call[K, V]) {
var (
inserted bool
deleted bool
old node.Node[K, V]
)
nowNano := c.clock.NowNano()
newNode := c.hashmap.Compute(cl.key, func(oldNode node.Node[K, V]) node.Node[K, V] {
isCorrectCall := cl.isFake || c.singleflight.deleteCall(cl)
old = oldNode
if isCorrectCall && cl.isNotFound {
deleted = oldNode != nil
return c.atomicDelete(cl.key, oldNode, cl, nowNano)
}
if cl.err != nil {
if cl.isRefresh && oldNode != nil {
c.calcRefreshableAt(oldNode, oldNode, cl, nowNano)
}
return oldNode
}
if !isCorrectCall {
return oldNode
}
inserted = true
return c.atomicSet(cl.key, cl.value, old, cl, nowNano)
})
cl.cancel()
if deleted {
c.afterDelete(old, nowNano, false)
}
if inserted {
c.afterWrite(newNode, old, nowNano)
}
}
func (c *cache[K, V]) bulkRefreshKeys(
ctx context.Context,
rks []refreshableKey[K, V],
bulkLoader BulkLoader[K, V],
isManual bool,
) <-chan []RefreshResult[K, V] {
if !c.withRefresh {
return nil
}
var ch chan []RefreshResult[K, V]
if isManual {
ch = make(chan []RefreshResult[K, V], 1)
}
if len(rks) == 0 {
if isManual {
ch <- []RefreshResult[K, V]{}
}
return ch
}
c.executor(func() {
var (
toLoadCalls map[K]*call[K, V]
toReloadCalls map[K]*call[K, V]
foundCalls []*call[K, V]
results []RefreshResult[K, V]
)
if isManual {
results = make([]RefreshResult[K, V], 0, len(rks))
}
i := 0
for _, rk := range rks {
cl, shouldLoad := c.singleflight.startCall(rk.key, true)
if shouldLoad {
if rk.old != nil {
if toReloadCalls == nil {
toReloadCalls = make(map[K]*call[K, V], len(rks)-i)
}
cl.value = rk.old.Value()
toReloadCalls[rk.key] = cl
} else {
if toLoadCalls == nil {
toLoadCalls = make(map[K]*call[K, V], len(rks)-i)
}
toLoadCalls[rk.key] = cl
}
} else {
if foundCalls == nil {
foundCalls = make([]*call[K, V], 0, len(rks)-i)
}
foundCalls = append(foundCalls, cl)
}
i++
}
loadCtx := context.WithoutCancel(ctx)
if len(toLoadCalls) > 0 {
loadErr := c.wrapLoad(func() error {
return c.singleflight.doBulkCall(loadCtx, toLoadCalls, bulkLoader.BulkLoad, c.afterDeleteCall)
})
if loadErr != nil {
c.logger.Error(ctx, "BulkLoad returned an error", loadErr)
}
if isManual {
for _, cl := range toLoadCalls {
results = append(results, RefreshResult[K, V]{
Key: cl.key,
Value: cl.value,
Err: cl.err,
})
}
}
}
if len(toReloadCalls) > 0 {
reload := func(ctx context.Context, keys []K) (map[K]V, error) {
oldValues := make([]V, 0, len(keys))
for _, k := range keys {
cl := toReloadCalls[k]
oldValues = append(oldValues, cl.value)
cl.value = zeroValue[V]()
}
return bulkLoader.BulkReload(ctx, keys, oldValues)
}
reloadErr := c.wrapLoad(func() error {
return c.singleflight.doBulkCall(loadCtx, toReloadCalls, reload, c.afterDeleteCall)
})
if reloadErr != nil {
c.logger.Error(ctx, "BulkReload returned an error", reloadErr)
}
if isManual {
for _, cl := range toReloadCalls {
results = append(results, RefreshResult[K, V]{
Key: cl.key,
Value: cl.value,
Err: cl.err,
})
}
}
}
for _, cl := range foundCalls {
cl.wait()
if isManual {
results = append(results, RefreshResult[K, V]{
Key: cl.key,
Value: cl.value,
Err: cl.err,
})
}
}
if isManual {
ch <- results
}
})
return ch
}
// BulkGet returns the value associated with key in this cache, obtaining that value from loader if necessary.
// The method improves upon the conventional "if cached, return; otherwise create, cache and return" pattern.
//
// If another call to Get (BulkGet) is currently loading the value for key,
// simply waits for that goroutine to finish and returns its loaded value. Note that
// multiple goroutines can concurrently load values for distinct keys.
//
// No observable state associated with this cache is modified until loading completes.
//
// WARNING: BulkLoader.BulkLoad must not attempt to update any mappings of this cache directly.
//
// WARNING: For any given key, every bulkLoader used with it should compute the same value.
// Otherwise, a call that passes one bulkLoader may return the result of another call
// with a differently behaving bulkLoader. For example, a call that requests a short timeout
// for an RPC may wait for a similar call that requests a long timeout, or a call by an
// unprivileged user may return a resource accessible only to a privileged user making a similar call.
func (c *cache[K, V]) BulkGet(ctx context.Context, keys []K, bulkLoader BulkLoader[K, V]) (map[K]V, error) {
c.singleflight.init()
nowNano := c.clock.NowNano()
result := make(map[K]V, len(keys))
var (
misses map[K]*call[K, V]
toRefresh []refreshableKey[K, V]