Repository navigation
Expand file tree
/
Copy pathcache_impl.go
More file actions
2506 lines (2310 loc) · 86.6 KB
/
Copy pathcache_impl.go
File metadata and controls
2506 lines (2310 loc) · 86.6 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 (
"context"
"errors"
"fmt"
"iter"
"math"
"runtime"
"sync"
"sync/atomic"
"time"
"weak"
"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/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, node.Node]
evictionPolicy *policy[K]
timerWheel *expiration.Wheel
stats stats.Recorder
statsSnapshoter stats.Snapshoter
logger Logger
clock timeSource
statsClock *realSource
readBuffer *lossy.Striped
writeBuffer *queue.MPSC[task]
executor func(fn func())
singleflight *group[K, V]
evictionMutex sync.Mutex
stopOnce sync.Once
stop chan struct{}
done chan struct{}
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]
hasDefaultExecutor bool
withTime bool
withExpiration bool
withRefresh bool
withEviction bool
isWeighted bool
withMaintenance bool
withStats bool
// whether a read may change the expiration time: ExpireAfterRead is not called for the
// built-in calculators whose reads always keep it
withReadExpiry bool
// the time of the current maintenance pass, read once when it starts (with expiration only),
// so that the timer wheel and size eviction agree on what has expired; guarded by
// evictionMutex
maintenanceNanos int64
// even while a scheduler that holds evictionMutex waits to learn whether its executor ran the
// drain inline; whoever makes it odd releases that mutex. Each schedule takes a new value, so
// a scheduler releases only its own lock, and only a drain can take over another's release
drainToken atomic.Uint64
drainBuffersFunc func()
}
// 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
}
var logger Logger = &safeLogger{logger: o.getLogger()}
var statsRecorder stats.Recorder = &stats.NoopRecorder{}
var statsSnapshoter stats.Snapshoter = &stats.NoopRecorder{}
if withStats {
statsRecorder = &safeRecorder{recorder: o.StatsRecorder, logger: logger}
if snapshoter, ok := o.StatsRecorder.(stats.Snapshoter); ok {
statsSnapshoter = snapshoter
}
}
c := &cache[K, V]{
nodeManager: nodeManager,
hashmap: hashmap.NewWithSize[K, node.Node](nodeManager, o.getInitialCapacity()),
stats: statsRecorder,
statsSnapshoter: statsSnapshoter,
logger: logger,
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,
}
c.drainBuffersFunc = c.drainBuffers
c.singleflight.commit = c.commitCall
c.singleflight.publish = c.publish
// read on every refresh, so that tests can replace the executor
c.singleflight.executor = func(fn func()) { c.executor(fn) }
c.singleflight.nodeOf = func(key K) node.Node { return c.hashmap.Get(key) }
if withStats {
c.statsClock.Init()
}
c.withEviction = withEviction
if c.withEviction {
var expectedSize uint64
if o.hasInitialCapacity() {
//nolint:gosec // there's no overflow
expectedSize = min(maximum, uint64(o.getInitialCapacity()))
}
c.evictionPolicy = newPolicy[K](nodeManager.Kind, withWeight, expectedSize, nodeManager.KeyOffset(), c.evictNode)
}
if o.ExpiryCalculator != nil {
c.timerWheel = expiration.NewWheel(nodeManager.Kind)
}
c.withExpiration = o.ExpiryCalculator != nil
_, creating := o.ExpiryCalculator.(*varExpiryCreating[K, V])
_, writing := o.ExpiryCalculator.(*varExpiryWriting[K, V])
c.withReadExpiry = c.withExpiration && !creating && !writing
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.Kind)
c.writeBuffer = queue.NewMPSC[task](minWriteBufferSize, maxWriteBufferSize)
}
if c.withTime {
c.clock.Init()
}
if c.withExpiration {
// No cleanup of the Cache stops the goroutine: cleanups run outside testing/synctest
// bubbles, and closing a channel created in one from outside is a fatal error. The
// goroutine returns by itself once the cache is collected.
c.stop = make(chan struct{})
c.done = make(chan struct{})
go periodicCleanUp(weak.Make(c), nil, nil, c.stop, c.done)
}
if c.withEviction {
c.SetMaximum(maximum)
}
return c
}
// newNode creates a node for a write whose weight and timestamps have already been computed.
// With updatable, the node can have its value replaced in place: a value that would be kept
// inline is kept behind an atomic pointer instead.
func (c *cache[K, V]) newNode(key K, value V, weight uint32, expiresAt, refreshableAt int64, updatable bool) node.Node {
if updatable {
return c.nodeManager.CreateUpdatable(key, value, expiresAt, refreshableAt, weight)
}
return c.nodeManager.Create(key, value, expiresAt, refreshableAt, weight)
}
// writeEntry describes a write before it is applied: the new value and weight with the
// timestamps of the entry it replaces, which are kept unless the calculators change them. old is
// what the mutation found, nil for a creation, which sees no timestamps.
func (c *cache[K, V]) writeEntry(key K, value V, weight uint32, old *previous[K, V], nanos int64) Entry[K, V] {
nowNano := noTime
if c.withTime {
nowNano = nanos
}
expiresAt := unreachableExpiresAt
if c.withExpiration && old != nil {
// A read that moved the deadline while the mutation ran user code comes before the
// write, unless it moved it to before nowNano, when the mutation found the entry live.
expiresAt = old.node.ExpiresAt()
if expiresAt <= old.nowNano {
expiresAt = old.nodeExpiresAt
}
}
refreshableAt := unreachableRefreshableAt
if c.withRefresh && old != nil {
refreshableAt = old.node.RefreshableAt()
}
return Entry[K, V]{
Key: key,
Value: value,
Weight: weight,
ExpiresAtNano: expiresAt,
RefreshableAtNano: refreshableAt,
SnapshotAtNano: nowNano,
}
}
func (c *cache[K, V]) nodeToEntry(n node.Node, nanos int64) Entry[K, V] {
return c.nodeValueToEntry(n, c.nodeManager.Value(n), nanos)
}
// nodeValueToEntry is nodeToEntry with the value the caller loaded from the node.
func (c *cache[K, V]) nodeValueToEntry(n node.Node, value 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: c.nodeManager.Key(n),
Value: 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, value := c.getNode(key, nowNano)
if n == nil {
return zeroValue[V](), false
}
return value, true
}
// getNode returns the node associated with the key in this cache, and its value. The value is
// loaded once and is the one ExpireAfterRead is shown, so a read that returns it comes before an
// update in place that replaces it.
func (c *cache[K, V]) getNode(key K, nowNano int64) (n node.Node, value V) {
n = c.hashmap.Get(key)
if n == nil {
c.stats.RecordMisses(1)
if c.drainStatus.Load() == required {
c.scheduleDrainBuffers()
}
return nil, value
}
if n.HasExpired(nowNano) {
c.stats.RecordMisses(1)
c.scheduleDrainBuffers()
return nil, value
}
if c.withReadExpiry {
value = c.calcExpiresAtAfterRead(n, nowNano)
} else {
value = c.nodeManager.Value(n)
}
c.afterRead(n, true)
return n, value
}
// 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. As in getNode, a node that a write is
// replacing or removing is the key's node until the write changes the table.
func (c *cache[K, V]) getNodeQuietly(key K, nowNano int64) node.Node {
n := c.hashmap.Get(key)
if n == nil || n.HasExpired(nowNano) {
return nil
}
return n
}
func (c *cache[K, V]) afterRead(got node.Node, recordHit bool) {
if recordHit {
c.stats.RecordHits(1)
}
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.
// An expired entry that has not been removed yet counts as no value.
//
// 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)
}
// calcExpiresAtAfterRead moves the deadline of n as ExpireAfterRead asks for the entry with the
// value it loads, and returns that value for the read to return. The cache must have read expiry
// (withReadExpiry).
func (c *cache[K, V]) calcExpiresAtAfterRead(n node.Node, nowNano int64) V {
value, valuePtr, valueWord := c.nodeManager.ValueAndIdentity(n)
entry := c.nodeValueToEntry(n, value, nowNano)
// The new deadline is derived from the entry the calculator was shown, so it may only replace
// that entry's deadline. A writer can store a new deadline in place in the meantime, and
// comparing against a fresh read of the node would revert it to one derived from the old value.
if next, ok := expiresAtAfterRead(c.expiryCalculator, entry, nowNano); ok {
// The entry may expire while the calculator runs, and a reader may then find the key
// absent: moving the deadline of an expired entry would bring it back. The clock is
// read again only here, since the deadline rarely moves (see expireTolerance).
if entry.ExpiresAtNano <= c.clock.NowNano() {
return value
}
// The read returns value, so it comes before an update in place that replaced the value
// while the calculator ran, and the update's deadline stands. The CAS alone would not
// tell: the update may store the very deadline the entry had, for example when the clock
// has not moved. An update in the few instructions between this check and the CAS still
// can, as the writer stores the value before the deadline.
if _, p, w := c.nodeManager.ValueAndIdentity(n); p != valuePtr || w != valueWord {
return value
}
n.CASExpiresAt(entry.ExpiresAtNano, next)
}
return value
}
// 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, value := c.getNode(key, nowNano)
if n == nil {
return Entry[K, V]{}, false
}
return c.nodeValueToEntry(n, value, 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. It has no effect on an absent
// or expired entry.
//
// This call locks a hash table bucket, as a write does. Calling it from a function that runs while the
// cache holds a bucket lock, such as a Compute function, OnAtomicDeletion, a weigher or a calculator,
// may deadlock.
func (c *cache[K, V]) SetExpiresAfter(key K, expiresAfter time.Duration) {
if !c.withExpiration || expiresAfter <= 0 {
return
}
c.setExpiresAt(key, func(nowNano int64) int64 { return deadlineAfter(nowNano, expiresAfter) })
}
// setExpiresAt is SetExpiresAfter with the deadline that deadline returns for the current time.
func (c *cache[K, V]) setExpiresAt(key K, deadline func(nowNano int64) int64) {
var (
n node.Node
nowNano int64
earlier bool
)
// The deadline is changed under the key's bucket lock, as a write changes it: a write reads
// the deadline before its calculator runs and stores the result after, so a deadline set
// without the lock in between would be overwritten with one computed from the former. The
// clock is read under the lock too, as in mutate.
c.hashmap.Compute(key, func(cur node.Node) node.Node {
if cur == nil {
return nil
}
nowNano = c.clock.NowNano()
// An expired entry that is still in the table is absent: a new deadline would bring its
// stale value back.
expiresAt := cur.ExpiresAt()
if expiresAt <= nowNano {
return cur
}
n = cur
// The caller asked for this deadline, so it is set exactly.
if next := deadline(nowNano); next != expiresAt {
cur.SetExpiresAt(next)
earlier = next < expiresAt
}
return cur
})
if n == nil {
return
}
if earlier {
// The read buffer may drop the access, and the node would then wait in the timer wheel's
// bucket for its former deadline, so an earlier deadline goes through the write buffer. A
// later one needs nothing: the wheel re-checks the node when its former bucket expires.
// The task goes first, as for a write: afterRead may submit a drain to an executor that
// calls runtime.Goexit.
c.afterWriteTask(newTask(n, nil, reconcileReason))
}
c.afterRead(n, 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.
//
// This call locks a hash table bucket, as a write does. Calling it from a function that runs while the
// cache holds a bucket lock, such as a Compute function, OnAtomicDeletion, a weigher or a calculator,
// may deadlock.
func (c *cache[K, V]) SetRefreshableAfter(key K, refreshableAfter time.Duration) {
if !c.withRefresh || refreshableAfter <= 0 {
return
}
c.setRefreshableAt(key, func(nowNano int64) int64 { return deadlineAfter(nowNano, refreshableAfter) })
}
// setRefreshableAt is SetRefreshableAfter with the time that deadline returns for the current time.
func (c *cache[K, V]) setRefreshableAt(key K, deadline func(nowNano int64) int64) {
// Under the key's bucket lock, as for setExpiresAt.
c.hashmap.Compute(key, func(n node.Node) node.Node {
if n == nil {
return nil
}
if next := deadline(c.clock.NowNano()); next != n.RefreshableAt() {
n.SetRefreshableAt(next)
}
return n
})
}
func (c *cache[K, V]) set(key K, value V, onlyIfAbsent bool) (V, bool) {
m := c.mutate(key, fromCaller, func(prev previous[K, V]) (mutationOp, V) {
if onlyIfAbsent && prev.live {
if c.withReadExpiry {
c.calcExpiresAtAfterRead(prev.node, prev.nowNano)
}
return opKeep, value
}
return opWrite, value
})
c.publish(m)
// An expired entry that is still in the table is absent, as for reads.
if !m.live {
return value, true
}
if onlyIfAbsent {
c.afterRead(m.node, false)
}
return m.value, false
}
// 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, 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, value := c.getNode(key, nowNano); n != nil {
return 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
}, 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) {
// The check only skips locking the bucket of an absent key. It is not a read: as in Compute,
// the hit or miss is the entry the function is given, and a read of it would also restart
// its ExpireAfterRead deadline before the function decides what to do with it. An expired
// entry is removed under the lock, as Compute removes it.
if c.hashmap.Get(key) == nil {
c.stats.RecordMisses(1)
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
}, true)
}
func (c *cache[K, V]) doCompute(
key K,
remappingFunc func(oldValue V, found bool) (newValue V, op ComputeOp),
recordStats bool,
) (V, bool) {
var (
result V
op ComputeOp
notValidOp bool
panicErr error
)
m := c.mutate(key, fromCaller, func(prev previous[K, V]) (mutationOp, V) {
var (
oldValue V
actualValue V
)
if prev.live {
oldValue = prev.value
}
func() {
defer func() {
if r := recover(); r != nil {
panicErr = newPanicError(r)
}
}()
actualValue, op = remappingFunc(oldValue, prev.live)
}()
if panicErr != nil {
return opKeep, actualValue
}
switch op {
case CancelOp:
if prev.node != nil && !prev.live {
// The expired entry is removed, as the timer wheel would remove it.
return opRemoveExpired, actualValue
}
result = prev.value
return opKeep, actualValue
case WriteOp:
result = actualValue
return opWrite, actualValue
case InvalidateOp:
return opInvalidate, actualValue
default:
notValidOp = true
return opKeep, actualValue
}
})
if panicErr != nil {
panic(panicErr)
}
if notValidOp {
panic(fmt.Sprintf("otter: invalid ComputeOp: %d", op))
}
c.publish(m)
// recorded after the mutation is published, so that a recorder that calls runtime.Goexit
// cannot keep the change out of the policies
if recordStats {
if m.live {
c.stats.RecordHits(1)
} else {
c.stats.RecordMisses(1)
}
}
if m.next == nil {
return zeroValue[V](), false
}
// The node may be updated in place by another writer once the bucket lock is released, so
// the result is the value seen under the lock, not c.nodeManager.Value(m.next).
return result, true
}
// startRefresh registers a refresh of key and returns its call, or returns the call already
// registered for key. shouldLoad reports that the caller registered the call and must run it.
//
// The refresh's base, the key's live node (nil if absent or expired), is read and the call
// registered under the key's bucket lock. A write or an invalidation cancels the key's calls under
// the same lock, before it publishes its change. So it either comes before the registration, and
// the refresh starts from what it wrote, or cancels the refresh; and a refresh requested after the
// change is visible never joins a call that the change cancelled.
//
// A refresh that a read starts (!isManual) is not registered if the key's node is fresh by then, having
// been refreshed or replaced since the read, or the key is gone: there is nothing left to refresh,
// and cl is nil. Without this, every read that saw the key stale before the first refresh
// completed would reload it again.
//
// again is the manual refresh's way to run a refresh registered in place of a load it joins,
// if the load fails for its owner's context (see loadAgain); it is nil for a refresh that a read
// starts, which never joins a load.
func (c *cache[K, V]) startRefresh(
key K,
isManual bool,
nowNano int64,
again func(s *call[K, V]),
) (cl *call[K, V], shouldLoad bool) {
// fast path: a read that saw a change does not find the calls the change cancelled. A call is
// joined only if it was started from the key's live node, or from an absent key that is
// still absent, and has not committed (see group.startRefresh); then it is not superseded
// either. A load is joined only under the lock, see call.again.
if cl := c.singleflight.getCall(key); cl != nil && cl.isRefresh && !cl.committed.Load() {
if n := c.getNodeQuietly(key, nowNano); cl.base == n && (n == nil || n.IsAlive()) {
return cl, false
}
}
c.hashmap.Compute(key, func(current node.Node) node.Node {
// The time is read again under the lock, as a mutation does: the entry may have expired
// while the refresh waited for it, and a load of the key registered since must not be
// replaced by a refresh of the expired value.
nowNano = max(nowNano, c.clock.NowNano())
var base node.Node
if current != nil && !current.HasExpired(nowNano) {
base = current
}
if !isManual && (base == nil || base.IsFresh(nowNano)) {
return current
}
cl, shouldLoad = c.singleflight.startRefresh(key, base)
if !shouldLoad && !cl.isRefresh && again != nil && cl.again == nil {
cl.again = &loadAgain[K, V]{submit: again}
}
return current
})
return cl, shouldLoad
}
func (c *cache[K, V]) refreshKey(
ctx context.Context,
key K,
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)
}
// The refresh is registered before it is handed to the executor, so that a write that
// follows the request cancels it. Registered by the task, a refresh that the executor starts
// after the write would replace the written value or bring an invalidated key back.
// The clock is user code, so it is read before: if it panicked after the registration, the
// call would never be finished, and every later refresh of the key would join it.
if !isManual {
// A refresh that a read starts is the cache's own work: a panic of the clock, or of a
// custom executor submitting it, is logged, as one submitting maintenance or OnDeletion,
// and the read returns the value it found. submitRefresh has finished the call by then.
defer recoverCallback(c.logger, "Panicked while starting a refresh")
}
var again func(s *call[K, V])
if isManual {
again = func(s *call[K, V]) {
defer recoverCallback(c.logger, "Panicked while starting a refresh")
c.singleflight.submitRefresh([]*call[K, V]{s}, func() { c.refreshTask(ctx, s, loader, nil) })
}
}
nowNano := c.clock.NowNano()
cl, shouldLoad := c.startRefresh(key, isManual, nowNano, again)
if cl == nil {
return ch
}
if !shouldLoad {
// A load or refresh of the key is in flight, and its result is all there is to report.
// A task that waited for it would take an executor slot for the whole load: with an
// executor that runs a bounded number of tasks, enough stale reads of one key would take
// every slot and block, and so would the task they wait for. A manual refresh waits in a
// goroutine of its own, and the error is logged by the call's owner.
if isManual {
go func() {
ch <- joinedResult(cl)
}()
}
return ch
}
c.singleflight.submitRefresh([]*call[K, V]{cl}, func() { c.refreshTask(ctx, cl, loader, ch) })
return ch
}
// refreshTask runs cl, a refresh that the caller registered, with loader, logs its error, and
// sends its result to ch unless ch is nil.
func (c *cache[K, V]) refreshTask(ctx context.Context, cl *call[K, V], loader Loader[K, V], ch chan<- RefreshResult[K, V]) {
// Deferred, so that a loader that calls runtime.Goexit is reported like one that panics. The
// result is sent from a defer of its own, which runs after the log: a Logger.Error that calls
// runtime.Goexit would skip the rest of a deferred function shared with it, and the caller
// would wait for the channel forever.
if ch != nil {
defer func() {
ch <- cl.refreshResult()
}()
}
defer func() {
if cl.err != nil && !cl.isNotFound {
c.logger.Error(ctx, "Returned an error during the refreshing", cl.err)
}
}()
// the loader is called in a closure, see doCall
refresher := func(ctx context.Context, key K) (V, error) {
if cl.base != nil {
return loader.Reload(ctx, key, c.nodeManager.Value(cl.base))
}
return loader.Load(ctx, key)
}
//nolint:errcheck // there is no need to check error
_ = c.wrapRefresh(func() error {
return c.singleflight.doCall(ctx, cl, refresher)
})
}
// 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, or if Get waits for a BulkGet
// whose BulkLoader leaves the key out of its result.
// 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()
// The value is read before the refresh starts: the node may be updated in place by then
// (with a synchronous executor, by the refresh itself).
n, value := c.getNode(key, nowNano)
if n != nil {
// A node that is being removed is not fresh either, but there is nothing to refresh. It is
// checked after IsFresh: a node retired in between would pass the check before. A node is
// retired after OnAtomicDeletion, so a refresh requested while the listener runs waits for
// the bucket lock, and then finds the key's new node.
if !n.IsFresh(nowNano) && n.IsAlive() {
c.refreshKey(ctx, c.nodeManager.Key(n), loader, false)
}
return value, nil
}
for {
// A Get whose context has ended does not start a load: the load would fail for its
// context, and a waiter with a live context that joined it would retry, so callers that
// give up could keep it from loading the key. A key invalidated faster than it loads
// refuses every load, and the loader may ignore ctx: checked before each retry as well,
// ctx bounds the wait whatever the loader does.
if err := ctx.Err(); err != nil {
return zeroValue[V](), err
}
value, retry, err := c.loadOrJoin(ctx, key, loader, nowNano)
if !retry {
return value, err
}
nowNano = c.clock.NowNano()
}
}
// loadOrJoin loads the value for key, which Get has not found, or waits for the load already
// running for it. retry reports that the joined load failed for its owner's context while ctx
// is live, so the key must be loaded again.
func (c *cache[K, V]) loadOrJoin(
ctx context.Context,
key K,
loader Loader[K, V],
nowNano int64,
) (value V, retry bool, err error) {
cl, shouldLoad := c.singleflight.startLoad(key, nowNano)
if shouldLoad {
// Re-check the map before loading. The getNode above runs before this
// call slot is claimed, so it can miss a value that a concurrently
// completing load publishes in between, leaving this caller to load the
// same value a second time. group.finish frees a call slot only after
// committing the value to the table, so winning the slot means any such
// value is already visible here; adopt it rather than loading it again. Quiet lookup: the
// getNode above already recorded the miss for this request.
if c.getNodeQuietly(key, nowNano) != nil {
if value, expiresAt, n := c.readForAdoption(cl, nowNano); n != nil {
c.singleflight.adopt(cl, value, expiresAt, n)
return value, false, nil
}
}
//nolint:errcheck // there is no need to check error
_ = c.wrapLoad(func() error {
// the loader is called in a closure, see doCall
return c.singleflight.doCall(ctx, cl, func(ctx context.Context, key K) (V, error) {
return loader.Load(ctx, key)
})
})
if cl.refused {
value, ok := c.valueAfterRefusal(key)
return value, !ok, nil
}
return cl.value, false, cl.err
}
if err := cl.waitContext(ctx); err != nil {
return zeroValue[V](), false, err
}
if cl.refused {
value, ok := c.valueAfterRefusal(key)
return value, !ok, nil
}
if c.withExpiration && cl.expiredBefore(nowNano) {
// The Get joined a load after its value had been committed and had expired: a Get that
// started after the expiration loads the key again.
return zeroValue[V](), true, nil
}
if cl.failedForOwner() && ctx.Err() == nil {
return zeroValue[V](), true, nil
}
return cl.value, false, cl.err
}
// commitCall writes the result of a finished load or refresh, if it may still be written, for
// group.finish: not found removes the entry, an error keeps it (a failed refresh moves its
// refresh time), and a value is written over it.
func (c *cache[K, V]) commitCall(cl *call[K, V]) mutation[K, V] {
from := fromLoad
if cl.isRefresh {
from = fromRefresh
}
m := c.mutate(cl.key, from, func(prev previous[K, V]) (mutationOp, V) {
// From here on, an eviction or expiration of the key drops the call (see
// group.deleteOnRemoval): it can no longer bring the removed value back.
cl.committed.Store(true)
if !cl.isRefresh && prev.live {
// A load starts on a miss, so a write has given the key a value during the load. The
// write may not have cancelled the load: a write that inserts or replaces a node
// cancels the calls before the node is stored, so a load registered in between is not