-
Notifications
You must be signed in to change notification settings - Fork 1
/
ttl_cache.go
450 lines (353 loc) · 7.96 KB
/
ttl_cache.go
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
package ttlcache
import (
"bytes"
"encoding/gob"
"fmt"
"math"
"os"
"sort"
"sync"
"time"
"github.com/boltdb/bolt"
)
const (
groupsBucketName string = "__groups"
defaultGroupName string = "default"
)
func init() {
gob.Register(map[string]interface{}{})
gob.Register(map[string]string{})
gob.Register([]interface{}{})
}
type TTLCache struct {
Groups map[string]*Group
db *bolt.DB
storagePath string
ticker *time.Ticker
stop chan bool
}
func OpenCache(storagePath string, reapInterval time.Duration) (*TTLCache, error) {
// TODO: jdouglas For now, deleting existing database on restart Mon Nov 7 09:31:03 2016
os.RemoveAll(storagePath)
// Open the database
db, err := bolt.Open(storagePath, 0755, nil)
if err != nil {
return nil, err
}
if reapInterval < time.Millisecond {
reapInterval = time.Millisecond
}
ttlc := TTLCache{
db: db,
storagePath: storagePath,
}
ttlc.Groups = make(map[string]*Group)
// Load up existing groups
err = db.Update(func(tx *bolt.Tx) error {
// Ensure the groups bucket exists
gps, err := tx.CreateBucketIfNotExists([]byte(groupsBucketName))
if err != nil {
return err
}
// Get any existing groups
err = gps.ForEach(func(k, v []byte) error {
g := Group{
Key: k,
ttlIndex: []IndexEntry{},
ttlCache: &ttlc,
}
gbkt, err := tx.CreateBucketIfNotExists(k)
if err != nil {
return err
}
g.Lock()
defer g.Unlock()
g.ttlIndex = []IndexEntry{}
err = gbkt.ForEach(func(k, v []byte) error {
e := CacheEntry{}
r := bytes.NewBuffer(v)
decoder := gob.NewDecoder(r)
err := decoder.Decode(&e)
if err != nil {
return err
}
g.ttlIndex = append(g.ttlIndex, IndexEntry{Key: k, ExpiresAt: e.ExpiresAt})
return nil
})
if err != nil {
return err
}
sort.Sort(ByIndexEntryExpiry(g.ttlIndex))
ttlc.Groups[string(k)] = &g
return nil
})
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
ttlc.ticker = time.NewTicker(reapInterval)
ttlc.stop = make(chan bool, 1)
go func() {
for {
select {
case <-ttlc.ticker.C:
ttlc.reapExpired()
case <-ttlc.stop:
return
}
}
}()
return &ttlc, nil
}
func (t *TTLCache) reapExpired() {
// Loop over each group
for _, g := range t.Groups {
go func(g *Group) {
g.ttlCache.db.Update(func(tx *bolt.Tx) error {
now := time.Now()
newIndex := []IndexEntry{}
g.Lock()
defer g.Unlock()
for _, e := range g.ttlIndex {
if e.ExpiresAt.Before(now) {
gbkt := tx.Bucket(g.Key)
if gbkt == nil {
return fmt.Errorf("Bucket does not exist")
}
err := gbkt.Delete(e.Key)
if err != nil {
return err
}
} else {
newIndex = append(newIndex, e)
}
}
// Ensure the groups bucket exists
g.ttlIndex = newIndex
return nil
})
}(g)
}
}
type Group struct {
sync.Mutex
Key []byte
ttlIndex []IndexEntry
ttlCache *TTLCache
}
func (g *Group) Count() int {
return len(g.ttlIndex)
}
func (g *Group) Put(key []byte, value interface{}, ttl time.Duration) error {
err := g.ttlCache.db.Update(func(tx *bolt.Tx) error {
// Ensure the groups bucket exists
gbkt, err := tx.CreateBucketIfNotExists(g.Key)
if err != nil {
return err
}
existing := gbkt.Get(key)
if existing != nil {
// We are doing this primarily to ensure that the index stays in sync with the entries
gbkt.Delete(key)
}
b := new(bytes.Buffer)
now := time.Now()
e := CacheEntry{
Key: key,
Value: value,
CreatedAt: now,
ExpiresAt: now.Add(ttl),
}
encoder := gob.NewEncoder(b)
err = encoder.Encode(&e)
if err != nil {
return err
}
// Add the item to the group bucket
err = gbkt.Put(key, b.Bytes())
if err != nil {
return err
}
g.Lock()
defer g.Unlock()
g.ttlIndex = appendIndex(g.ttlIndex, IndexEntry{Key: e.Key, ExpiresAt: e.ExpiresAt})
return nil
})
if err != nil {
return err
}
return nil
}
func (g *Group) Get(key []byte) (*CacheEntry, error) {
var val []byte
e := CacheEntry{}
err := g.ttlCache.db.View(func(tx *bolt.Tx) error {
// Ensure the groups bucket exists
gbkt := tx.Bucket(g.Key)
if gbkt == nil {
return nil
}
val = gbkt.Get(key)
if val == nil {
return nil
}
r := bytes.NewBuffer(val)
decoder := gob.NewDecoder(r)
err := decoder.Decode(&e)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
if e.Value == nil {
return nil, nil
}
return &e, nil
}
func (g *Group) Delete(key []byte) error {
g.Lock()
defer g.Unlock()
err := g.ttlCache.db.Update(func(tx *bolt.Tx) error {
// Ensure the groups bucket exists
gbkt := tx.Bucket(g.Key)
if gbkt == nil {
return fmt.Errorf("Bucket does not exist")
}
return gbkt.Delete(key)
})
if err != nil {
return err
}
ttlIndex := []IndexEntry{}
for _, e := range g.ttlIndex {
if !bytes.Equal(e.Key, key) {
ttlIndex = append(ttlIndex, e)
}
}
g.ttlIndex = ttlIndex
return nil
}
type IndexEntry struct {
Key []byte
ExpiresAt time.Time
}
type ByIndexEntryExpiry []IndexEntry
func (s ByIndexEntryExpiry) Len() int {
return len(s)
}
func (s ByIndexEntryExpiry) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s ByIndexEntryExpiry) Less(i, j int) bool {
return s[i].ExpiresAt.Before(s[j].ExpiresAt)
}
type CacheEntry struct {
Key []byte
Value interface{}
CreatedAt time.Time
ExpiresAt time.Time
}
// CreateGroupIfNotExists gets a group by key. If the grouiop does not exist, it will be created.
func (t *TTLCache) CreateGroupIfNotExists(key string) (*Group, error) {
// Check for an existing group.
g := t.Groups[key]
if g != nil {
return g, nil
}
// New Group
g = &Group{
Key: []byte(key),
ttlIndex: []IndexEntry{},
}
g.Lock()
defer g.Unlock()
// If the group does not already exist, create it and add it to the database
err := t.db.Update(func(tx *bolt.Tx) error {
// get the bucket for the groups
gps, err := tx.CreateBucketIfNotExists([]byte(groupsBucketName))
if err != nil {
return err
}
// Add the group to the bucket
err = gps.Put(g.Key, g.Key)
if err != nil {
return err
}
// Now add the group bucket
_, err = tx.CreateBucketIfNotExists([]byte(key))
if err != nil {
return err
}
g.ttlCache = t
t.Groups[key] = g
return nil
})
if err != nil {
return nil, err
}
return g, nil
}
func (t *TTLCache) DeleteGroup(key string) error {
// Check for an existing group.
g := t.Groups[key]
if len(g.Key) == 0 {
return fmt.Errorf("Group does not exist")
}
g.Lock()
defer g.Unlock()
// If the group does not already exist, create it and add it to the database
err := t.db.Update(func(tx *bolt.Tx) error {
// get the bucket for the groups
gbkt := tx.Bucket([]byte(groupsBucketName))
err := gbkt.Delete(g.Key)
return err
})
if err != nil {
return err
}
return nil
}
func (t *TTLCache) Close() {
t.stop <- true
t.db.Close()
}
func appendIndex(index []IndexEntry, entry IndexEntry) []IndexEntry {
newIdx := insertSortedIndexEntry(index, entry, 0, 0)
return newIdx
}
func insertSortedIndexEntry(index []IndexEntry, entry IndexEntry, start int, end int) []IndexEntry {
if index == nil {
return nil
}
length := len(index)
if end == 0 {
end = length - 1
}
mid := start + int(math.Floor(float64(end-start)/2))
if length == 0 {
return append(index, entry)
}
firstEntry := index[end]
lastEntry := index[end]
middleEntry := index[mid]
if entry.ExpiresAt.Before(firstEntry.ExpiresAt) {
return append([]IndexEntry{entry}, index...)
}
if entry.ExpiresAt.After(lastEntry.ExpiresAt) || entry.ExpiresAt.Equal(lastEntry.ExpiresAt) {
return append(index, entry)
}
if entry.ExpiresAt.Before(middleEntry.ExpiresAt) {
return insertSortedIndexEntry(index, entry, start, mid-1)
}
if entry.ExpiresAt.After(middleEntry.ExpiresAt) || entry.ExpiresAt.Equal(middleEntry.ExpiresAt) {
return insertSortedIndexEntry(index, entry, mid+1, end)
}
return index
}