-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.go
76 lines (66 loc) · 1.36 KB
/
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
package main
import (
"context"
"sync"
"time"
"github.com/benbjohnson/clock"
"github.com/vmware/govmomi/vim25/mo"
"knative.dev/pkg/logging"
)
const (
cacheGCInterval = time.Second * 10 // periodically check for expired cache TTLs
)
type cache struct {
clock clock.Clock
ttl int64
sync.RWMutex
cache map[string]*item
}
type item struct {
alarm mo.Alarm
added int64
}
func newAlarmCache(ttl int64) *cache {
return &cache{
clock: clock.New(),
ttl: ttl,
cache: map[string]*item{},
}
}
func (c *cache) add(key string, alarm mo.Alarm) {
c.Lock()
defer c.Unlock()
c.cache[key] = &item{
alarm: alarm,
added: c.clock.Now().UTC().Unix(),
}
}
func (c *cache) get(key string) (mo.Alarm, bool) {
c.RLock()
defer c.RUnlock()
if k, ok := c.cache[key]; ok {
return k.alarm, true
}
return mo.Alarm{}, false
}
func (c *cache) run(ctx context.Context) error {
for {
select {
case <-ctx.Done():
logging.FromContext(ctx).Debugf("stopping alarm cache: %v", ctx.Err())
return ctx.Err()
case <-c.clock.Tick(cacheGCInterval):
func() {
c.Lock()
defer c.Unlock()
logging.FromContext(ctx).Debugf("purging stale cache items")
for k, v := range c.cache {
if c.clock.Now().UTC().Unix()-v.added > c.ttl {
logging.FromContext(ctx).Debugf("removing stale cache item: %s", k)
delete(c.cache, k)
}
}
}()
}
}
}