-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcache.go
More file actions
313 lines (286 loc) · 7.25 KB
/
Copy pathcache.go
File metadata and controls
313 lines (286 loc) · 7.25 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
package memoize
import (
"context"
"fmt"
"sync"
"time"
)
type flight[V any] struct {
wg sync.WaitGroup
value V
err error
}
// peekingStore lets GetOrCompute inspect stored entry state without applying
// Store.Get side effects such as recency updates before it chooses a policy.
type peekingStore[K comparable, V any] interface {
Peek(ctx context.Context, key K) (Stored[V], bool, error)
}
// freshValueStore is the first cache policy check: stores that can prove a
// value is fresh return it directly before entry loading or flight handling.
type freshValueStore[K comparable, V any] interface {
PeekFreshValue(ctx context.Context, key K, now time.Time) (V, bool, error)
}
func metricKey[K comparable](key K) string {
if s, ok := any(key).(string); ok {
return s
}
return fmt.Sprint(key)
}
func (c *Cache[K, V]) emitHit(key K) {
if !c.metricsEnabled {
return
}
c.metrics.RecordMetric(MetricEvent{Kind: MetricHit, Key: metricKey(key)})
}
func (c *Cache[K, V]) emitMiss(key K) {
if !c.metricsEnabled {
return
}
c.metrics.RecordMetric(MetricEvent{Kind: MetricMiss, Key: metricKey(key)})
}
func (c *Cache[K, V]) emitStaleHit(key K) {
if !c.metricsEnabled {
return
}
c.metrics.RecordMetric(MetricEvent{Kind: MetricStaleHit, Key: metricKey(key)})
}
func (c *Cache[K, V]) emitRefreshStart(key K) {
if !c.metricsEnabled {
return
}
c.metrics.RecordMetric(MetricEvent{Kind: MetricRefreshStart, Key: metricKey(key)})
}
func (c *Cache[K, V]) emitRefreshSuccess(key K, duration time.Duration) {
if !c.metricsEnabled {
return
}
c.metrics.RecordMetric(MetricEvent{Kind: MetricRefreshSuccess, Key: metricKey(key), Duration: duration})
}
func (c *Cache[K, V]) emitRefreshError(key K, err error) {
if !c.metricsEnabled {
return
}
c.metrics.RecordMetric(MetricEvent{Kind: MetricRefreshError, Key: metricKey(key), Err: err})
}
func (c *Cache[K, V]) emitSet(key K) {
if !c.metricsEnabled {
return
}
c.metrics.RecordMetric(MetricEvent{Kind: MetricSet, Key: metricKey(key)})
}
func (c *Cache[K, V]) emitDelete(key K) {
if !c.metricsEnabled {
return
}
c.metrics.RecordMetric(MetricEvent{Kind: MetricDelete, Key: metricKey(key)})
}
func (c *Cache[K, V]) getEntry(ctx context.Context, key K) (Stored[V], bool, error) {
if c.peeker != nil {
return c.peeker.Peek(ctx, key)
}
return c.store.Get(ctx, key)
}
func (c *Cache[K, V]) getFreshValue(ctx context.Context, key K, now time.Time) (V, bool, bool, error) {
if store, ok := c.store.(freshValueStore[K, V]); ok {
value, fresh, err := store.PeekFreshValue(ctx, key, now)
return value, fresh, true, err
}
var zero V
return zero, false, false, nil
}
func (c *Cache[K, V]) waitForFlight(key K) (V, bool, error) {
c.flightMu.Lock()
existing := c.flights[key]
c.flightMu.Unlock()
if existing == nil {
var zero V
return zero, false, nil
}
existing.wg.Wait()
return existing.value, true, existing.err
}
func (c *Cache[K, V]) startFlight(key K) (*flight[V], bool) {
c.flightMu.Lock()
if existing := c.flights[key]; existing != nil {
c.flightMu.Unlock()
return existing, false
}
f := &flight[V]{}
f.wg.Add(1)
c.flights[key] = f
c.flightMu.Unlock()
return f, true
}
func (c *Cache[K, V]) finishFlight(key K, f *flight[V], value V, err error) {
f.value = value
f.err = err
f.wg.Done()
c.flightMu.Lock()
delete(c.flights, key)
c.flightMu.Unlock()
}
func (c *Cache[K, V]) do(key K, fn func() (V, error)) (V, error) {
f, leader := c.startFlight(key)
if !leader {
f.wg.Wait()
return f.value, f.err
}
value, err := fn()
c.finishFlight(key, f, value, err)
return value, err
}
func (c *Cache[K, V]) refresh(key K, compute func(context.Context) (V, error)) {
f, leader := c.startFlight(key)
if !leader {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), c.refreshTimeout)
defer cancel()
started := c.clock.Now()
c.emitRefreshStart(key)
value, err := compute(ctx)
if err != nil {
c.emitRefreshError(key, err)
c.finishFlight(key, f, value, err)
return
}
if err := c.Set(ctx, key, value); err != nil {
c.emitRefreshError(key, err)
c.finishFlight(key, f, value, err)
return
}
c.emitRefreshSuccess(key, c.clock.Now().Sub(started))
c.finishFlight(key, f, value, nil)
}()
}
func (c *Cache[K, V]) Get(ctx context.Context, key K) (V, bool, error) {
var zero V
if c.bypass {
return zero, false, nil
}
if c.store == nil {
return zero, false, ErrMissingStore
}
now := c.clock.Now()
if value, ok, _, err := c.getFreshValue(ctx, key, now); err != nil || ok {
if ok {
c.emitHit(key)
}
return value, ok, err
}
entry, ok, err := c.getEntry(ctx, key)
if err != nil || !ok {
return zero, false, err
}
if entry.state(now) != entryFresh {
return zero, false, nil
}
c.emitHit(key)
return entry.Value, true, nil
}
func (c *Cache[K, V]) Set(ctx context.Context, key K, value V) error {
if c.bypass {
return nil
}
if c.store == nil {
return ErrMissingStore
}
now := c.clock.Now()
entry := Stored[V]{Value: value, CreatedAt: now, NoExpire: c.noExpiration}
if !c.noExpiration {
entry.FreshUntil = now.Add(c.ttl)
if c.staleTTL > 0 {
entry.StaleUntil = entry.FreshUntil.Add(c.staleTTL)
}
}
if err := c.store.Set(ctx, key, entry); err != nil {
return err
}
c.emitSet(key)
return nil
}
func (c *Cache[K, V]) Delete(ctx context.Context, key K) error {
if c.store == nil {
return ErrMissingStore
}
if err := c.store.Delete(ctx, key); err != nil {
return err
}
c.emitDelete(key)
return nil
}
func (c *Cache[K, V]) Clear(ctx context.Context) error {
if c.store == nil {
return ErrMissingStore
}
return c.store.Clear(ctx)
}
// GetOrCompute follows the cache policy order: fresh-value fast path,
// active-flight wait for non-stale caches, stored entry state handling,
// stale-while-revalidate, miss computation, then configured stale fallback on
// compute error.
func (c *Cache[K, V]) GetOrCompute(ctx context.Context, key K, compute func(context.Context) (V, error)) (V, error) {
if c.bypass {
c.emitMiss(key)
return compute(ctx)
}
if c.store == nil {
var zero V
return zero, ErrMissingStore
}
now := c.clock.Now()
value, ok, supportsFreshValue, err := c.getFreshValue(ctx, key, now)
if err != nil || ok {
if ok {
c.emitHit(key)
}
return value, err
}
if supportsFreshValue && c.staleTTL == 0 && !c.keepStaleOnError {
if value, ok, err := c.waitForFlight(key); ok || err != nil {
return value, err
}
}
entry, ok, err := c.getEntry(ctx, key)
if err != nil {
var zero V
return zero, err
}
if ok {
switch entry.state(now) {
case entryFresh:
c.emitHit(key)
return entry.Value, nil
case entryStale:
c.emitStaleHit(key)
c.refresh(key, compute)
return entry.Value, nil
}
}
c.emitMiss(key)
value, err = c.do(key, func() (V, error) {
now := c.clock.Now()
if value, ok, _, err := c.getFreshValue(ctx, key, now); err != nil || ok {
return value, err
}
entry, ok, err := c.getEntry(ctx, key)
if err != nil {
var zero V
return zero, err
}
if ok && entry.state(now) == entryFresh {
return entry.Value, nil
}
computed, computeErr := compute(ctx)
if computeErr != nil {
return computed, computeErr
}
return computed, c.Set(ctx, key, computed)
})
if err != nil && ok && c.keepStaleOnError {
c.emitRefreshError(key, err)
return entry.Value, nil
}
return value, err
}