-
Notifications
You must be signed in to change notification settings - Fork 1
/
ttl.go
93 lines (73 loc) · 1.42 KB
/
ttl.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
package iqdb
import (
"github.com/google/btree"
"sync"
"time"
)
type TTLTreeItem interface {
Less(btree.Item) bool
}
type ttlTreeItem struct {
ttl time.Duration
key string
expire time.Time
}
func (i *ttlTreeItem) Less(than btree.Item) bool {
if than == nil {
return false
}
return i.expire.Before(than.(*ttlTreeItem).expire)
}
func NewttlTreeItem(key string, ttl time.Duration) ttlTreeItem {
return ttlTreeItem{
key: key,
ttl: ttl,
expire: timeFunc().Add(ttl),
}
}
type ttlTree struct {
delCb func(key string) error
tree *btree.BTree
ticker *time.Ticker
mu *sync.Mutex
}
func (t *ttlTree) ReplaceOrInsert(item ttlTreeItem) {
t.mu.Lock()
t.tree.ReplaceOrInsert(&item)
t.mu.Unlock()
}
func (t *ttlTree) Delete(item btree.Item) {
t.mu.Lock()
if t.tree.Has(item) {
t.tree.Delete(item)
}
t.mu.Unlock()
}
func (t *ttlTree) loop() {
for range t.ticker.C {
t.checkTTL()
}
}
func (t *ttlTree) checkTTL() {
items := []btree.Item{}
t.mu.Lock()
t.tree.AscendLessThan(&ttlTreeItem{expire: timeFunc()}, func(item btree.Item) bool {
items = append(items, item)
return true
})
t.mu.Unlock()
for _, item := range items {
t.Delete(item)
_ = t.delCb(item.(*ttlTreeItem).key)
}
}
func newTTLTree(delCb func(key string) error) *ttlTree {
tree := &ttlTree{
delCb: delCb,
tree: btree.New(32),
ticker: time.NewTicker(time.Second),
mu: &sync.Mutex{},
}
go tree.loop()
return tree
}