forked from nemosupremo/vault-gatekeeper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathttlset.go
62 lines (54 loc) · 859 Bytes
/
ttlset.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
package main
import (
"sync"
"time"
)
type TtlSet struct {
sync.RWMutex
s map[string]time.Time
quit chan struct{}
}
func NewTtlSet() *TtlSet {
t := &TtlSet{}
t.s = make(map[string]time.Time)
t.quit = make(chan struct{})
go t.garbageCollector()
return t
}
func (t *TtlSet) Has(key string) bool {
t.RLock()
defer t.RUnlock()
_, ok := t.s[key]
return ok
}
func (t *TtlSet) Put(key string, ttl time.Duration) {
t.Lock()
t.s[key] = time.Now().Add(ttl)
t.Unlock()
}
func (t *TtlSet) Destroy() {
t.Lock()
close(t.quit)
t.s = nil
t.Unlock()
}
func (t *TtlSet) cleanup() {
t.Lock()
for k, v := range t.s {
if time.Now().After(v) {
delete(t.s, k)
}
}
t.Unlock()
}
func (t *TtlSet) garbageCollector() {
ticker := time.Tick(5 * time.Second)
for {
select {
case <-ticker:
t.cleanup()
case <-t.quit:
return
}
}
}