-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpersistent.go
More file actions
268 lines (222 loc) · 7.04 KB
/
persistent.go
File metadata and controls
268 lines (222 loc) · 7.04 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
package fido
import (
"context"
"errors"
"fmt"
"iter"
"log/slog"
"time"
"github.com/puzpuzpuz/xsync/v4"
)
const asyncTimeout = 5 * time.Second
// TieredCache combines an in-memory cache with persistent storage.
type TieredCache[K comparable, V any] struct {
Store Store[K, V] // direct access to persistence layer
flights *xsync.Map[K, *flightCall[V]]
memory *s3fifo[K, V]
defaultTTL time.Duration
}
// NewTiered creates a cache backed by the given store.
func NewTiered[K comparable, V any](store Store[K, V], opts ...Option) (*TieredCache[K, V], error) {
cfg := &config{size: 16384}
for _, opt := range opts {
opt(cfg)
}
if store == nil {
return nil, errors.New("store cannot be nil")
}
cache := &TieredCache[K, V]{
Store: store,
flights: xsync.NewMap[K, *flightCall[V]](),
memory: newS3FIFO[K, V](cfg),
defaultTTL: cfg.defaultTTL,
}
return cache, nil
}
// Get checks memory, then persistence. Found values are cached in memory.
//
//nolint:gocritic // unnamedResult: public API signature is intentionally clear
func (c *TieredCache[K, V]) Get(ctx context.Context, key K) (V, bool, error) {
if val, ok := c.memory.get(key); ok {
return val, true, nil
}
var zero V
if err := c.Store.ValidateKey(key); err != nil {
return zero, false, fmt.Errorf("invalid key: %w", err)
}
val, expiry, found, err := c.Store.Get(ctx, key)
if err != nil {
return zero, false, fmt.Errorf("persistence load: %w", err)
}
if !found {
return zero, false, nil
}
c.memory.set(key, val, timeToSec(expiry))
return val, true, nil
}
// Set stores to memory first (always), then persistence.
// Uses the default TTL specified at cache creation.
func (c *TieredCache[K, V]) Set(ctx context.Context, key K, value V) error {
return c.SetTTL(ctx, key, value, 0)
}
// SetTTL stores to memory first (always), then persistence with explicit TTL.
// A zero or negative TTL means the entry never expires.
func (c *TieredCache[K, V]) SetTTL(ctx context.Context, key K, value V, ttl time.Duration) error {
expiry := calculateExpiry(ttl, c.defaultTTL)
if err := c.Store.ValidateKey(key); err != nil {
return err
}
c.memory.set(key, value, timeToSec(expiry))
if err := c.Store.Set(ctx, key, value, expiry); err != nil {
return fmt.Errorf("persistence store failed: %w", err)
}
return nil
}
// SetAsync stores to memory synchronously, persistence asynchronously.
// Uses the default TTL. Persistence errors are logged, not returned.
func (c *TieredCache[K, V]) SetAsync(ctx context.Context, key K, value V) error {
return c.SetAsyncTTL(ctx, key, value, 0)
}
// SetAsyncTTL stores to memory synchronously, persistence asynchronously with explicit TTL.
// Persistence errors are logged, not returned.
func (c *TieredCache[K, V]) SetAsyncTTL(ctx context.Context, key K, value V, ttl time.Duration) error {
expiry := calculateExpiry(ttl, c.defaultTTL)
if err := c.Store.ValidateKey(key); err != nil {
return err
}
c.memory.set(key, value, timeToSec(expiry))
go func() {
storeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), asyncTimeout)
defer cancel()
if err := c.Store.Set(storeCtx, key, value, expiry); err != nil {
slog.Error("async persistence failed", "key", key, "error", err)
}
}()
return nil
}
// Fetch returns cached value or calls loader. Concurrent calls share one loader.
// Computed values are stored with the default TTL.
func (c *TieredCache[K, V]) Fetch(ctx context.Context, key K, loader func(context.Context) (V, error)) (V, error) {
return c.getSet(ctx, key, loader, 0)
}
// FetchTTL is like Fetch but stores computed values with an explicit TTL.
func (c *TieredCache[K, V]) FetchTTL(ctx context.Context, key K, ttl time.Duration, loader func(context.Context) (V, error)) (V, error) {
return c.getSet(ctx, key, loader, ttl)
}
func (c *TieredCache[K, V]) getSet(ctx context.Context, key K, loader func(context.Context) (V, error), ttl time.Duration) (V, error) {
var zero V
if val, ok := c.memory.get(key); ok {
return val, nil
}
if err := c.Store.ValidateKey(key); err != nil {
return zero, fmt.Errorf("invalid key: %w", err)
}
val, expiry, found, err := c.Store.Get(ctx, key)
if err != nil {
return zero, fmt.Errorf("persistence load: %w", err)
}
if found {
c.memory.set(key, val, timeToSec(expiry))
return val, nil
}
call, loaded := c.flights.LoadOrCompute(key, func() (*flightCall[V], bool) {
fc := &flightCall[V]{}
fc.wg.Add(1)
return fc, false
})
if loaded {
call.wg.Wait()
return call.val, call.err
}
if v, ok := c.memory.get(key); ok {
call.val = v
c.flights.Delete(key)
call.wg.Done()
return v, nil
}
val, expiry, found, err = c.Store.Get(ctx, key)
if err != nil {
call.err = fmt.Errorf("persistence load: %w", err)
c.flights.Delete(key)
call.wg.Done()
return zero, call.err
}
if found {
c.memory.set(key, val, timeToSec(expiry))
call.val = val
c.flights.Delete(key)
call.wg.Done()
return val, nil
}
val, err = loader(ctx)
if err != nil {
call.err = err
c.flights.Delete(key)
call.wg.Done()
return zero, err
}
exp := calculateExpiry(ttl, c.defaultTTL)
c.memory.set(key, val, timeToSec(exp))
if err := c.Store.Set(ctx, key, val, exp); err != nil {
slog.Warn("Fetch persistence failed", "key", key, "error", err)
}
call.val = val
c.flights.Delete(key)
call.wg.Done()
return val, nil
}
// Delete removes from memory and persistence.
func (c *TieredCache[K, V]) Delete(ctx context.Context, key K) error {
c.memory.del(key)
if err := c.Store.ValidateKey(key); err != nil {
return fmt.Errorf("invalid key: %w", err)
}
if err := c.Store.Delete(ctx, key); err != nil {
return fmt.Errorf("persistence delete: %w", err)
}
return nil
}
// Flush clears memory and persistence. Returns total entries removed.
func (c *TieredCache[K, V]) Flush(ctx context.Context) (int, error) {
memoryRemoved := c.memory.flush()
persistRemoved, err := c.Store.Flush(ctx)
if err != nil {
return memoryRemoved, fmt.Errorf("persistence flush: %w", err)
}
return memoryRemoved + persistRemoved, nil
}
// Len returns the memory cache size. Use Store.Len for persistence count.
func (c *TieredCache[K, V]) Len() int {
return c.memory.len()
}
// Range returns an iterator over all non-expired key-value pairs in memory.
// Does not iterate the persistence layer.
// Iteration order is undefined. Safe for concurrent use.
// Changes during iteration may or may not be reflected.
func (c *TieredCache[K, V]) Range() iter.Seq2[K, V] {
return func(yield func(K, V) bool) {
//nolint:gosec // G115: Unix seconds fit in uint32 until year 2106
now := uint32(time.Now().Unix())
c.memory.entries.Range(func(key K, e *entry[K, V]) bool {
// Skip expired entries.
expiry := e.expirySec.Load()
if expiry != 0 && expiry < now {
return true
}
// Load value with seqlock.
v, ok := e.loadValue()
if !ok {
return true
}
// Yield to caller.
return yield(key, v)
})
}
}
// Close releases store resources.
func (c *TieredCache[K, V]) Close() error {
if err := c.Store.Close(); err != nil {
return fmt.Errorf("close persistence: %w", err)
}
return nil
}