-
Notifications
You must be signed in to change notification settings - Fork 5
/
cache.go
226 lines (198 loc) · 4.7 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
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
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
// Item represents an item in the cache.
type Item struct {
Object interface{}
Expiration int64
}
// Expired returns true if the item has expired.
func (item Item) Expired() bool {
if item.Expiration == 0 {
return false
}
return time.Now().UnixNano() > item.Expiration
}
// Cache is the cache object
type Cache struct {
*cache
// If this is confusing, see the comment at the bottom of New()
}
type cache struct {
expiration time.Duration
items map[string]Item
mu sync.RWMutex
onExpired func()
janitor *janitor
}
// Set add an item to the cache, replacing any existing item.
func (c *cache) Set(k string, x interface{}) {
// "Inlining" of set
var e = time.Now().Add(c.expiration).UnixNano()
c.mu.Lock()
c.items[k] = Item{
Object: x,
Expiration: e,
}
// TODO: Calls to mu.Unlock are currently not deferred because defer
// adds ~200 ns (as of go1.)
c.mu.Unlock()
}
func (c *cache) set(k string, x interface{}) {
var e = time.Now().Add(c.expiration).UnixNano()
c.items[k] = Item{
Object: x,
Expiration: e,
}
}
// Replace set a new value for the cache key only if it already exists. Returns an error otherwise.
func (c *cache) Replace(k string, x interface{}) error {
c.mu.Lock()
_, found := c.get(k)
if !found {
c.mu.Unlock()
return fmt.Errorf("item %s doesn't exist", k)
}
c.set(k, x)
c.mu.Unlock()
return nil
}
// Get an item from the cache. Returns the item or nil, and a bool indicating
// whether the key was found.
func (c *cache) Get(k string) (interface{}, bool) {
c.mu.RLock()
item, found := c.items[k]
if !found {
c.mu.RUnlock()
return nil, false
}
c.mu.RUnlock()
return item.Object, true
}
func (c *cache) get(k string) (interface{}, bool) {
item, found := c.items[k]
if !found {
return nil, false
}
return item.Object, true
}
// GetAll returns all keys in the cache or empty map.
func (c *cache) GetAll() map[string]interface{} {
c.mu.RLock()
defer c.mu.RUnlock()
var items map[string]interface{}
if c.ItemCount() > 0 {
items = make(map[string]interface{}, len(c.items))
for k, v := range c.items {
items[k] = v.Object
}
}
return items
}
// Delete an item from the cache. Does nothing if the key is not in the cache.
func (c *cache) Delete(k string) {
c.mu.Lock()
delete(c.items, k)
c.mu.Unlock()
}
// DeleteExpired Delete all expired items from the cache.
func (c *cache) DeleteExpired() {
now := time.Now().UnixNano()
c.mu.Lock()
for k, v := range c.items {
if v.Expiration > 0 && now > v.Expiration {
delete(c.items, k)
}
}
c.mu.Unlock()
}
type keyAndValue struct {
key string
value interface{}
}
// OnExpired sets an (optional) function that is called when the cache expires
func (c *cache) OnExpired(f func()) {
c.onExpired = f
}
// ItemCount Returns the number of items in the cache, including expired items.
func (c *cache) ItemCount() int {
c.mu.RLock()
n := len(c.items)
c.mu.RUnlock()
return n
}
// Flush Delete all items from the cache.
func (c *cache) Flush() {
c.mu.Lock()
c.items = map[string]Item{}
c.mu.Unlock()
}
type janitor struct {
Interval time.Duration
stop chan bool
}
// handleExpired is fired by the ticker and executes the onExpired function.
func (c *cache) handleExpired() {
if c.onExpired != nil {
c.onExpired()
}
}
func (j *janitor) Run(c *cache) {
ticker := time.NewTicker(j.Interval)
for {
select {
case <-ticker.C:
c.handleExpired()
case <-j.stop:
ticker.Stop()
return
}
}
}
func stopJanitor(c *Cache) {
c.janitor.stop <- true
}
func runJanitor(c *cache, ex time.Duration) {
j := &janitor{
Interval: ex,
stop: make(chan bool, 1),
}
c.janitor = j
go j.Run(c)
}
func newCache(ex time.Duration, m map[string]Item) *cache {
if ex <= 0 {
ex = -1
}
c := &cache{
expiration: ex,
items: m,
}
return c
}
func newCacheWithJanitor(ex time.Duration, m map[string]Item) *Cache {
c := newCache(ex, m)
// This trick ensures that the janitor goroutine (which--granted it
// was enabled--is running DeleteExpired on c forever) does not keep
// the returned C object from being garbage collected. When it is
// garbage collected, the finalizer stops the janitor goroutine, after
// which c can be collected.
C := &Cache{c}
if ex > 0 {
runJanitor(c, ex)
runtime.SetFinalizer(C, stopJanitor)
}
return C
}
// NewCache return a new cache with a given expiration duration. If the
// expiration duration is less than 1 (i.e. No Expiration),
// the items in the cache never expire (by default), and must be deleted
// manually. The OnExpired callback method is ignored, too.
func NewCache(expiration time.Duration) *Cache {
items := make(map[string]Item)
return newCacheWithJanitor(expiration, items)
}