-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
131 lines (116 loc) · 3.03 KB
/
cache.go
File metadata and controls
131 lines (116 loc) · 3.03 KB
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
package main
import (
"container/heap"
"log"
"sync"
"time"
)
// Value stored in our map and priority queue
type Item struct {
Key string
Value []byte
Expiry time.Time
// The index is needed by update and is maintained by the heap.Interface methods.
index int // The index of the item in the heap.
}
type Cache struct {
m sync.Map
expiryQueue *PriorityQueue
// ensure we don't have 2 goroutine removing from our cache at the same time
expireLock sync.Mutex
// configuration
maxSize int
timeToLive time.Duration
// the cache's own input
Input chan *Request
// the redis backend input for when keys aren't cached
redisChan chan *Request
}
func NewCache(redisChan chan *Request, maxSize int, timeToLive time.Duration) *Cache {
c := new(Cache)
c.expiryQueue = NewPriorityQueue()
c.maxSize = maxSize
c.timeToLive = timeToLive
c.redisChan = redisChan
c.Input = make(chan *Request, 64) // FIXME hardcoded value
return c
}
func (c *Cache) expiryTime() time.Time {
return time.Now().Add(c.timeToLive)
}
func (c *Cache) addKey(key string, value []byte) {
item := &Item{Key: key, Value: value, Expiry: c.expiryTime()}
c.m.Store(key, item)
// update the priority queue in the background
go func() {
c.expireLock.Lock()
heap.Push(c.expiryQueue, item)
c.expireKeys()
c.expireLock.Unlock()
}()
}
func (c *Cache) expireKeys() {
log.Println("cache: remove expired keys")
// Remove the extra entries in the expiry queue if needed
if x := c.expiryQueue.Len() - c.maxSize; x > 0 {
for x > 0 {
item := heap.Pop(c.expiryQueue).(*Item)
c.m.Delete(item.Key)
x -= 1
}
}
// Remove expired entries if needed
now := time.Now()
if c.expiryQueue.Len() > 0 {
for c.expiryQueue.Oldest().After(now) {
item := heap.Pop(c.expiryQueue).(*Item)
c.m.Delete(item.Key)
if c.expiryQueue.Len() == 0 {
break
}
}
}
}
// garbage collect expired keys every expiry period
func (c *Cache) backgroundExpiry(period time.Duration) {
ticker := time.NewTicker(period)
for {
select {
case <-ticker.C:
c.expireLock.Lock()
c.expireKeys()
c.expireLock.Unlock()
}
}
}
func (c *Cache) Process() {
period := time.Second // FIXME hardcoded value, should be config
go c.backgroundExpiry(period)
for r := range c.Input {
i, ok := c.m.Load(r.Key)
if !ok {
log.Println("cache:", r.Key, "not found, forwarding to Redis")
// key not found, we forward the request to the Redis backend and
// wait for the result in a separate goroutine
go func() {
ch := make(chan *Response)
// send request to redis
c.redisChan <- &Request{Key: r.Key, Output: ch}
// wait for the Redis backend's response
resp := <-ch
log.Println("cache: redis replied")
// Add the response to our cache
if resp.Err == nil {
c.addKey(r.Key, resp.Result)
}
log.Println("cache: forward redis response to http")
// Forward response to HTTP front-end
r.Output <- resp
}()
} else {
log.Println("cache:", r.Key, "found")
item := i.(*Item)
r.Output <- &Response{Result: item.Value}
}
}
}