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
|
package cache
import (
"bytes"
"sync"
"time"
"go.sudomsg.com/cache/internal/pausedtimer"
)
const (
initialBucketSize uint64 = 8
loadFactor float64 = 0.9
)
// node represents an entry in the cache with metadata for eviction and expiration.
type node struct {
Hash uint64
Key []byte
Value []byte
Expiration time.Time
Access uint64
HashNext *node
HashPrev *node
EvictNext *node
EvictPrev *node
}
func (n *node) UnlinkHash() {
n.HashNext.HashPrev = n.HashPrev
n.HashPrev.HashNext = n.HashNext
n.HashNext = nil
n.HashPrev = nil
}
func (n *node) UnlinkEvict() {
n.EvictNext.EvictPrev = n.EvictPrev
n.EvictPrev.EvictNext = n.EvictNext
n.EvictNext = nil
n.EvictPrev = nil
}
// IsValid checks if the node is still valid based on its expiration time.
func (n *node) IsValid() bool {
return n.Expiration.IsZero() || n.Expiration.After(time.Now())
}
// TTL returns the time-to-live of the node.
func (n *node) TTL() time.Duration {
if n.Expiration.IsZero() {
return 0
} else {
return time.Until(n.Expiration)
}
}
func (n *node) Cost() uint64 {
return uint64(len(n.Key) + len(n.Value))
}
// store represents the in-memory cache with eviction policies and periodic tasks.
type store struct {
Bucket []node
Length uint64
Cost uint64
EvictList node
MaxCost uint64
SnapshotTicker *pausedtimer.PauseTimer
CleanupTicker *pausedtimer.PauseTimer
Policy evictionPolicy
Lock sync.RWMutex
EvictLock sync.RWMutex
}
// Init initializes the store with default settings.
func (s *store) Init() {
s.Clear()
s.Policy = evictionPolicy{
ListLock: &s.EvictLock,
Sentinel: &s.EvictList,
}
s.SnapshotTicker = pausedtimer.NewStopped(0)
s.CleanupTicker = pausedtimer.NewStopped(10 * time.Second)
if err := s.Policy.SetPolicy(PolicyNone); err != nil {
panic(err)
}
}
// Clear removes all entries from the store.
func (s *store) Clear() {
s.Lock.Lock()
defer s.Lock.Unlock()
s.Bucket = make([]node, initialBucketSize)
s.Length = 0
s.Cost = 0
s.EvictList.EvictNext = &s.EvictList
s.EvictList.EvictPrev = &s.EvictList
}
// lookupIdx calculates the hash and index for a given key.
func lookupIdx(s *store, key []byte) (uint64, uint64) {
hash := hash(key)
return hash % uint64(len(s.Bucket)), hash
}
// lazyInitBucket initializes the hash bucket if it hasn't been initialized yet.
func lazyInitBucket(n *node) {
if n.HashNext == nil {
n.HashNext = n
n.HashPrev = n
}
}
// lookup finds a node in the store by key.
func (s *store) lookup(key []byte) (*node, uint64, uint64) {
idx, hash := lookupIdx(s, key)
bucket := &s.Bucket[idx]
lazyInitBucket(bucket)
for v := bucket.HashNext; v != bucket; v = v.HashNext {
if bytes.Equal(key, v.Key) {
return v, idx, hash
}
}
return nil, idx, hash
}
// Get retrieves a value from the store by key with locking.
func (s *store) Get(key []byte) ([]byte, time.Duration, bool) {
s.Lock.RLock()
defer s.Lock.RUnlock()
v, _, _ := s.lookup(key)
if v != nil {
if !v.IsValid() {
return nil, 0, false
}
s.Policy.OnAccess(v)
return v.Value, v.TTL(), true
}
return nil, 0, false
}
// resize doubles the size of the hash table and rehashes all entries.
func (s *store) Resize() {
bucket := make([]node, 2*len(s.Bucket))
for i := range s.Bucket {
sentinel := &s.Bucket[i]
if sentinel.HashNext == nil {
continue
}
var order []*node
for v := sentinel.HashNext; v != sentinel; v = v.HashNext {
order = append(order, v)
}
for _, v := range order {
idx := v.Hash % uint64(len(bucket))
n := &bucket[idx]
lazyInitBucket(n)
v.HashPrev = n
v.HashNext = v.HashPrev.HashNext
v.HashNext.HashPrev = v
v.HashPrev.HashNext = v
}
}
s.Bucket = bucket
}
// cleanup removes expired entries from the store.
func (s *store) Cleanup() {
s.Lock.Lock()
defer s.Lock.Unlock()
s.EvictLock.Lock()
defer s.EvictLock.Unlock()
for v := s.EvictList.EvictNext; v != &s.EvictList; {
n := v.EvictNext
if !v.IsValid() {
deleteNode(s, v)
}
v = n
}
}
// evict removes entries from the store based on the eviction policy.
func (s *store) Evict() bool {
s.Lock.Lock()
defer s.Lock.Unlock()
s.EvictLock.Lock()
defer s.EvictLock.Unlock()
if s.MaxCost == 0 {
return true
}
for s.MaxCost < s.Cost {
n := s.Policy.Evict()
if n == nil {
break
}
deleteNode(s, n)
}
return true
}
// insert adds a new key-value pair to the store.
func (s *store) insert(key, value []byte, ttl time.Duration) {
idx, hash := lookupIdx(s, key)
bucket := &s.Bucket[idx]
if float64(s.Length) > loadFactor*float64(len(s.Bucket)) {
s.Resize()
// resize may invalidate pointer to bucket
idx, _ = lookupIdx(s, key)
bucket = &s.Bucket[idx]
lazyInitBucket(bucket)
}
v := &node{
Hash: hash,
Key: key,
Value: value,
}
if ttl != 0 {
v.Expiration = time.Now().Add(ttl)
} else {
v.Expiration = zero[time.Time]()
}
v.HashPrev = bucket
v.HashNext = v.HashPrev.HashNext
v.HashNext.HashPrev = v
v.HashPrev.HashNext = v
s.Policy.OnInsert(v)
s.Cost = s.Cost + v.Cost()
s.Length = s.Length + 1
}
// Set adds or updates a key-value pair in the store with locking.
func (s *store) Set(key, value []byte, ttl time.Duration) {
s.Lock.Lock()
defer s.Lock.Unlock()
v, _, _ := s.lookup(key)
if v != nil {
cost := v.Cost()
v.Value = value
if ttl != 0 {
v.Expiration = time.Now().Add(ttl)
} else {
v.Expiration = zero[time.Time]()
}
s.Cost = s.Cost + v.Cost() - cost
s.Policy.OnUpdate(v)
return
}
s.insert(key, value, ttl)
}
// deleteNode removes a node from the store.
func deleteNode(s *store, v *node) {
v.UnlinkEvict()
v.UnlinkHash()
s.Cost = s.Cost - v.Cost()
s.Length = s.Length - 1
}
// Delete removes a key-value pair from the store with locking.
func (s *store) Delete(key []byte) bool {
s.Lock.Lock()
defer s.Lock.Unlock()
v, _, _ := s.lookup(key)
if v != nil {
deleteNode(s, v)
return true
}
return false
}
// UpdateInPlace retrieves a value from the store, processes it using the provided function,
// and then sets the result back into the store with the same key.
func (s *store) UpdateInPlace(key []byte, processFunc func([]byte) ([]byte, error), ttl time.Duration) error {
s.Lock.Lock()
defer s.Lock.Unlock()
v, _, _ := s.lookup(key)
if v == nil {
return ErrKeyNotFound
}
if !v.IsValid() {
deleteNode(s, v)
return ErrKeyNotFound
}
value, err := processFunc(v.Value)
if err != nil {
return err
}
cost := v.Cost()
v.Value = value
if ttl != 0 {
v.Expiration = time.Now().Add(ttl)
} else {
v.Expiration = zero[time.Time]()
}
s.Cost = s.Cost + v.Cost() - cost
s.Policy.OnUpdate(v)
return nil
}
// Memorize attempts to retrieve a value from the store. If the retrieval fails,
// it sets the result of the factory function into the store and returns that result.
func (s *store) Memorize(key []byte, factory func() ([]byte, error), ttl time.Duration) ([]byte, error) {
s.Lock.Lock()
defer s.Lock.Unlock()
v, _, _ := s.lookup(key)
if v != nil && v.IsValid() {
s.Policy.OnAccess(v)
return v.Value, nil
}
value, err := factory()
if err != nil {
return nil, err
}
s.insert(key, value, ttl)
return value, nil
}
|