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
|
package cache
import (
"errors"
"io"
"log"
"os"
"sync"
"time"
"github.com/rogpeppe/go-internal/lockedfile"
"github.com/vmihailenco/msgpack/v5"
)
// db represents a cache database with file-backed storage and in-memory operation.
type db struct {
File io.WriteSeeker
Store store
Stop chan struct{}
wg sync.WaitGroup
}
// Option is a function type for configuring the db.
type Option func(*db) error
// openFile opens a file-backed cache database with the given options.
func openFile(filename string, options ...Option) (*db, error) {
ret, err := openMem(options...)
if err != nil {
return nil, err
}
file, err := lockedfile.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0o666)
if err != nil {
return nil, err
}
fileInfo, err := file.Stat()
if err != nil {
return nil, err
}
if fileInfo.Size() == 0 {
ret.File = file
ret.Flush()
} else {
err := ret.Store.LoadSnapshot(file)
if err != nil {
return nil, err
}
ret.File = file
}
return ret, nil
}
// openMem initializes an in-memory cache database with the given options.
func openMem(options ...Option) (*db, error) {
ret := &db{}
ret.Store.Init()
if err := ret.SetConfig(options...); err != nil {
return nil, err
}
return ret, nil
}
// Start begins the background worker for periodic tasks.
func (d *db) Start() {
d.Stop = make(chan struct{})
d.wg.Add(1)
go d.backgroundWorker()
}
// SetConfig applies configuration options to the db.
func (d *db) SetConfig(options ...Option) error {
d.Store.Lock.Lock()
defer d.Store.Lock.Unlock()
for _, opt := range options {
if err := opt(d); err != nil {
return err
}
}
return nil
}
// WithPolicy sets the eviction policy for the cache.
func WithPolicy(e EvictionPolicyType) Option {
return func(d *db) error {
return d.Store.Policy.SetPolicy(e)
}
}
// WithMaxCost sets the maximum cost for the cache.
func WithMaxCost(maxCost uint64) Option {
return func(d *db) error {
d.Store.MaxCost = maxCost
return nil
}
}
// SetSnapshotTime sets the interval for taking snapshots of the cache.
func SetSnapshotTime(t time.Duration) Option {
return func(d *db) error {
d.Store.SnapshotTicker.Reset(t)
return nil
}
}
// SetCleanupTime sets the interval for cleaning up expired entries.
func SetCleanupTime(t time.Duration) Option {
return func(d *db) error {
d.Store.CleanupTicker.Reset(t)
return nil
}
}
// backgroundWorker performs periodic tasks such as snapshotting and cleanup.
func (d *db) backgroundWorker() {
defer d.wg.Done()
defer func() {
if r := recover(); r != nil {
log.Printf("Recovered from panic in background worker: %v", r)
}
}()
d.Store.SnapshotTicker.Resume()
defer d.Store.SnapshotTicker.Stop()
d.Store.CleanupTicker.Resume()
defer d.Store.CleanupTicker.Stop()
for {
select {
case <-d.Stop:
return
case <-d.Store.SnapshotTicker.C:
d.Flush()
case <-d.Store.CleanupTicker.C:
d.Store.Cleanup()
d.Store.Evict()
}
}
}
// Close stops the background worker and cleans up resources.
func (d *db) Close() error {
close(d.Stop)
d.wg.Wait()
err := d.Flush()
d.Clear()
var err1 error
if d.File != nil {
closer, ok := d.File.(io.Closer)
if ok {
err1 = closer.Close()
}
}
if err != nil {
return err
}
return err1
}
// Flush writes the current state of the store to the file.
func (d *db) Flush() error {
if d.File != nil {
return d.Store.Snapshot(d.File)
}
return nil
}
// Clear removes all entries from the in-memory store.
func (d *db) Clear() {
d.Store.Clear()
}
var ErrKeyNotFound = errors.New("key not found") // ErrKeyNotFound is returned when a key is not found in the cache.
// The Cache database. Can be initialized by either OpenFile or OpenMem. Uses per DB Locks.
// DB represents a generic cache database with key-value pairs.
type DB[K any, V any] struct {
*db
}
// OpenFile opens a file-backed cache database with the specified options.
func OpenFile[K any, V any](filename string, options ...Option) (DB[K, V], error) {
ret, err := openFile(filename, options...)
if err != nil {
return zero[DB[K, V]](), err
}
ret.Start()
return DB[K, V]{db: ret}, nil
}
// OpenMem initializes an in-memory cache database with the specified options.
func OpenMem[K any, V any](options ...Option) (DB[K, V], error) {
ret, err := openMem(options...)
if err != nil {
return zero[DB[K, V]](), err
}
ret.Start()
return DB[K, V]{db: ret}, nil
}
// marshal serializes a value using msgpack.
func marshal[T any](v T) ([]byte, error) {
return msgpack.Marshal(v)
}
// unmarshal deserializes data into a value using msgpack.
func unmarshal[T any](data []byte, v *T) error {
return msgpack.Unmarshal(data, v)
}
// Get retrieves a value from the cache by key and returns its TTL.
func (h *DB[K, V]) Get(key K, value *V) (time.Duration, error) {
keyData, err := marshal(key)
if err != nil {
return 0, err
}
v, ttl, ok := h.Store.Get(keyData)
if !ok {
return 0, ErrKeyNotFound
}
if v != nil {
if err = unmarshal(v, value); err != nil {
return 0, err
}
}
return ttl, err
}
// GetValue retrieves a value from the cache by key and returns the value and its TTL.
func (h *DB[K, V]) GetValue(key K) (V, time.Duration, error) {
value := zero[V]()
ttl, err := h.Get(key, &value)
return value, ttl, err
}
// Set adds a key-value pair to the cache with a specified TTL.
func (h *DB[K, V]) Set(key K, value V, ttl time.Duration) error {
keyData, err := marshal(key)
if err != nil {
return err
}
valueData, err := marshal(value)
if err != nil {
return err
}
h.Store.Set(keyData, valueData, ttl)
return nil
}
// Delete removes a key-value pair from the cache.
func (h *DB[K, V]) Delete(key K) error {
keyData, err := marshal(key)
if err != nil {
return err
}
ok := h.Store.Delete(keyData)
if !ok {
return ErrKeyNotFound
}
return nil
}
// UpdateInPlace retrieves a value from the cache, processes it using the provided function,
// and then sets the result back into the cache with the same key.
func (h *DB[K, V]) UpdateInPlace(key K, processFunc func(V) (V, error), ttl time.Duration) error {
keyData, err := marshal(key)
if err != nil {
return err
}
return h.Store.UpdateInPlace(keyData, func(data []byte) ([]byte, error) {
var value V
if err := unmarshal(data, &value); err != nil {
return nil, err
}
processedValue, err := processFunc(value)
if err != nil {
return nil, err
}
return marshal(processedValue)
}, ttl)
}
// Memorize attempts to retrieve a value from the cache. If the retrieval fails,
// it sets the result of the factory function into the cache and returns that result.
func (h *DB[K, V]) Memorize(key K, factoryFunc func() (V, error), ttl time.Duration) (V, error) {
keyData, err := marshal(key)
if err != nil {
return zero[V](), err
}
data, err := h.Store.Memorize(keyData, func() ([]byte, error) {
value, err := factoryFunc()
if err != nil {
return nil, err
}
return marshal(value)
}, ttl)
if err != nil {
return zero[V](), err
}
var value V
if err := unmarshal(data, &value); err != nil {
return zero[V](), err
}
return value, nil
}
|