forked from vladaionescu/leveros
/
cache.go
248 lines (224 loc) · 5.9 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package leverutil
import (
"fmt"
"sync"
"time"
"github.com/leveros/gods/maps/treemap"
)
var (
cacheLogger = GetLogger(PackageName, "cache")
)
var (
// ErrNotYetConstructed is returned when the cache element has not yet been
// initialized.
ErrNotYetConstructed = fmt.Errorf("Not yet constructed")
// ErrWasDestructed is returned if the element has just been destructed.
ErrWasDestructed = fmt.Errorf("Was destructed")
)
// Cache is a data structure that keeps in-memory instances of objects for
// a specified amount of time after their last use.
type Cache struct {
expiry time.Duration
constructor func(string) (interface{}, error)
destructor func(interface{})
lock sync.Mutex
data map[string]*cacheEntry
lastUsedMap *treemap.Map // lastUsed (unix nano) -> list of keys
}
type cacheEntry struct {
element interface{}
err error
lastUsed int64
lock sync.RWMutex
}
// NewCache creates a new Cache object.
func NewCache(
expiry time.Duration,
constructor func(string) (interface{}, error),
destructor func(interface{})) *Cache {
return &Cache{
lastUsedMap: treemap.NewWith(int64Comparator),
expiry: expiry,
constructor: constructor,
destructor: destructor,
data: make(map[string]*cacheEntry),
}
}
// Get returns either a cached instance with provided key or a newly
// constructed one, if an instance is not found.
func (cache *Cache) Get(key string) (interface{}, error) {
cache.lock.Lock()
entry, ok := cache.data[key]
if ok {
cache.keepAliveInternal(key)
cache.lock.Unlock()
entry.lock.RLock() // Will block if currently constructing.
defer entry.lock.RUnlock()
return entry.element, entry.err
}
// Add entry to cache (before constructing).
entry = &cacheEntry{
err: ErrNotYetConstructed,
lastUsed: time.Now().UnixNano(),
}
treemapInsert(cache.lastUsedMap, entry.lastUsed, key)
cache.data[key] = entry
cache.maybeScheduleExpire(entry.lastUsed)
// Construct outside cache's lock.
entry.lock.Lock()
cache.lock.Unlock()
element, err := cache.constructor(key)
entry.element = element
entry.err = err
entry.lock.Unlock()
// Remove from cache if construction failed.
if err != nil {
cache.lock.Lock()
delete(cache.data, key)
treemapRemove(cache.lastUsedMap, entry.lastUsed, key)
cache.lock.Unlock()
}
return element, err
}
// GetExisting returns a cached instance with provided key, if it exists.
func (cache *Cache) GetExisting(key string) (interface{}, bool) {
cache.lock.Lock()
defer cache.lock.Unlock()
entry, ok := cache.data[key]
if ok {
cache.keepAliveInternal(key)
entry.lock.RLock() // Will block if currently constructing.
defer entry.lock.RUnlock()
if entry.err != nil {
return nil, false
}
return entry.element, true
}
return nil, false
}
// KeepAlive can be used to prevent expiry of instance with provided key.
// Returns false if instance does not exist.
func (cache *Cache) KeepAlive(key string) bool {
cache.lock.Lock()
defer cache.lock.Unlock()
return cache.keepAliveInternal(key)
}
// Destroy removes an instance from the Cache and calls the destructor for it.
func (cache *Cache) Destroy(key string) bool {
cache.lock.Lock()
entry, ok := cache.data[key]
if !ok {
cache.lock.Unlock()
return false
}
delete(cache.data, key)
treemapRemove(cache.lastUsedMap, entry.lastUsed, key)
cache.lock.Unlock()
cache.destroyEntry(entry)
return true
}
func (cache *Cache) destroyEntry(entry *cacheEntry) {
entry.lock.Lock() // Will block if currently constructing.
defer entry.lock.Unlock()
if entry.element != nil {
cache.destructor(entry.element)
entry.element = nil
entry.err = ErrWasDestructed
}
}
func (cache *Cache) keepAliveInternal(key string) bool {
entry, ok := cache.data[key]
if !ok {
return false
}
treemapRemove(cache.lastUsedMap, entry.lastUsed, key)
entry.lastUsed = time.Now().UnixNano()
treemapInsert(cache.lastUsedMap, entry.lastUsed, key)
cache.maybeScheduleExpire(entry.lastUsed)
return true
}
func (cache *Cache) maybeScheduleExpire(lastUsed int64) {
if cache.lastUsedMap.Left().(int64) != lastUsed {
// Already scheduled.
return
}
value, _ := cache.lastUsedMap.Get(lastUsed)
if value != nil && len(value.([]string)) > 1 {
// Already scheduled.
return
}
cache.doExpire()
}
func (cache *Cache) doExpire() {
for !cache.lastUsedMap.Empty() {
lastUsed := cache.lastUsedMap.Left().(int64)
expiryTime := time.Unix(0, lastUsed).Add(cache.expiry)
if expiryTime.Before(time.Now()) {
// Entry expired.
value, _ := cache.lastUsedMap.Get(lastUsed)
if value != nil {
for _, key := range value.([]string) {
entry := cache.data[key]
delete(cache.data, key)
// Run in parallel so as not to hold cache lock.
go cache.destroyEntry(entry)
}
}
cache.lastUsedMap.Remove(lastUsed)
} else {
// Not yet time. Schedule next.
untilExpiry := expiryTime.Sub(time.Now())
go func() {
time.Sleep(untilExpiry)
cache.lock.Lock()
cache.doExpire()
cache.lock.Unlock()
}()
break
}
}
}
func int64Comparator(a, b interface{}) int {
aInt64 := a.(int64)
bInt64 := b.(int64)
switch {
case aInt64 > bInt64:
return 1
case aInt64 < bInt64:
return -1
default:
return 0
}
}
func treemapInsert(theMap *treemap.Map, key int64, target string) {
value, _ := theMap.Get(key)
var entry []string
if value == nil {
entry = []string{target}
} else {
entry = value.([]string)
entry = append(entry, target)
}
theMap.Put(key, entry)
}
func treemapRemove(theMap *treemap.Map, key int64, target string) {
value, _ := theMap.Get(key)
if value == nil {
cacheLogger.Error("Could not find element in treemap")
return
}
entry := value.([]string)
foundIndex := -1
for index, targetJ := range entry {
if target == targetJ {
foundIndex = index
break
}
}
if foundIndex == -1 {
cacheLogger.Error("Could not find element in treemap")
return
}
entry = append(entry[:foundIndex], entry[foundIndex+1:]...)
theMap.Put(key, entry)
}