This repository has been archived by the owner on Oct 3, 2022. It is now read-only.
/
cache.go
296 lines (258 loc) · 7.3 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package recache
import (
"compress/gzip"
"sync"
"time"
)
var (
// Registry of all created caches. Require cacheMu to be held for access.
cacheMu sync.RWMutex
cacheIDCounter uint
caches = make(map[uint]*Cache)
)
// Get cache from registry by ID
func getCache(id uint) *Cache {
cacheMu.RLock()
defer cacheMu.RUnlock()
return caches[id]
}
// Unified storage for cached records with specific eviction parameters
type Cache struct {
// Locks for all cache access, excluding the contained records
mu sync.Mutex
// Global ID of cache
id uint
// Total used memory and limit
memoryLimit, memoryUsed int
// Linked list and limit for quick LRU data order modifications and lookup
lruLimit time.Duration
lruList linkedList
// Storage for each individual frontend
frontendIDCounter uint
buckets map[uint]map[Key]recordWithMeta
}
// Options for new cache creation
type CacheOptions struct {
// Maximum amount of memory the cache can consume without forcing eviction
MemoryLimit uint
// Maximum last use time of record without forcing eviction
LRULimit time.Duration
}
// Create new cache with specified memory and LRU eviction limits. After either
// of these are exceeded, the least recently used cache records will be evicted,
// until the requirements are satisfied again. Note that this eviction is
// eventual and not immediate for optimisation purposes.
//
// Pass in zero values to ignore either or both eviction limits.
func NewCache(opts CacheOptions) (c *Cache) {
cacheMu.Lock()
defer cacheMu.Unlock()
c = &Cache{
id: cacheIDCounter,
memoryLimit: int(opts.MemoryLimit),
lruLimit: opts.LRULimit,
buckets: make(map[uint]map[Key]recordWithMeta),
}
caches[cacheIDCounter] = c
cacheIDCounter++
return c
}
// Options for creating a new cache frontend
type FrontendOptions struct {
// Will be used for generating fresh cache records for the given key by
// the cache engine. These records will be stored by the cache engine and
// must not be modified after Get() returns. Get() must be thread-safe.
Get Getter
// Level level to use for storing records.
// Defaults to gzip.DefaultCompression.
Level *int
}
// Create new Frontend for accessing the cache.
// A Frontend must only be created using this method.
func (c *Cache) NewFrontend(opts FrontendOptions) *Frontend {
c.mu.Lock()
defer c.mu.Unlock()
f := &Frontend{
id: c.frontendIDCounter,
cache: c,
getter: opts.Get,
}
if opts.Level != nil {
f.level = *opts.Level
} else {
f.level = gzip.DefaultCompression
}
c.buckets[c.frontendIDCounter] = make(map[Key]recordWithMeta)
c.frontendIDCounter++
return f
}
// Get or create a new record in the cache.
// fresh=true, if record is freshly created and requires population.
func (c *Cache) getRecord(loc recordLocation) (rec *record, fresh bool) {
c.mu.Lock()
defer c.mu.Unlock()
recWithMeta, ok := c.record(loc)
if !ok {
recWithMeta = recordWithMeta{
node: c.lruList.Prepend(loc),
rec: new(record),
}
recWithMeta.rec.semaphore.Init() // Block all reads until population
} else {
c.lruList.MoveToFront(recWithMeta.node)
}
now := time.Now()
recWithMeta.lastUsed = now
c.buckets[loc.frontend][loc.key] = recWithMeta
// Attempt to evict up to the last 2 records due to LRU or memory
// constraints. Doing this here simplifies locking patterns while retaining
// good enough eviction eventuality.
for i := 0; i < 2; i++ {
last, ok := c.lruList.Last()
if !ok {
break
}
if c.memoryLimit != 0 && c.memoryUsed > c.memoryLimit {
c.evictWithLock(last)
continue
}
if c.lruLimit != 0 {
lruRec, ok := c.record(last)
if !ok {
panic("linked list points to evicted record")
}
if lruRec.lastUsed.Add(c.lruLimit).Before(now) {
c.evictWithLock(last)
continue
}
}
break
}
return recWithMeta.rec, !ok
}
// Shorthand for retrieving record by its location.
//
// Requires lock on c.mu.
func (c *Cache) record(loc recordLocation) (recordWithMeta, bool) {
rec, ok := c.buckets[loc.frontend][loc.key]
return rec, ok
}
// Set record used memory
func (c *Cache) setUsedMemory(src *record, loc recordLocation, memoryUsed int) {
c.mu.Lock()
defer c.mu.Unlock()
// It is possible for the record to be evicted and possibly then a new
// record to be inserted into the same spot while the current record is
// populated. Need to assert the former is still in the cache.
//
// This is needed here, because the used memory value of the record directly
// effects the total used memory of the cache w/o recording what parts of
// the cache contribute what amount to the total.
//
// All other cases of such possible concurrent evictions and overriden
// inclusions will simply NOP on their respective operations.
rec, ok := c.record(loc)
if !ok || rec.rec != src {
return
}
rec.memoryUsed = memoryUsed
c.buckets[loc.frontend][loc.key] = rec
c.memoryUsed += memoryUsed
}
// Register a record as being used in another record
func registerInclusion(parent, child intercacheRecordLocation) {
c := getCache(child.cache)
c.mu.Lock()
defer c.mu.Unlock()
rec, ok := c.record(child.recordLocation)
if !ok {
return // Already evicted
}
rec.includedIn = append(rec.includedIn, parent)
c.buckets[child.frontend][child.key] = rec
}
// Evict record from cache
func evict(loc intercacheRecordLocation) {
getCache(loc.cache).evict(loc.recordLocation)
}
// Evict record from cache
func (c *Cache) evict(loc recordLocation) {
c.mu.Lock()
defer c.mu.Unlock()
c.evictWithLock(loc)
}
// Evict record from cache. Requires lock on c.mu.
func (c *Cache) evictWithLock(loc recordLocation) {
rec, ok := c.record(loc)
if !ok {
return
}
delete(c.buckets[loc.frontend], loc.key)
c.lruList.Remove(rec.node)
c.memoryUsed -= rec.memoryUsed
for _, ch := range rec.includedIn {
if ch.cache == c.id {
// Hot path to reduce lock contention
c.evictWithLock(ch.recordLocation)
} else {
// Separate goroutine to prevent lock intersection
go evict(ch)
}
}
}
// The all keys of specific frontend.
func (c *Cache) evictFrontend(frontend uint) {
c.mu.Lock()
defer c.mu.Unlock()
c.evictFrontendWithLock(frontend)
}
// The all keys of specific frontend. Requires lock on c.mu.
func (c *Cache) evictFrontendWithLock(frontend uint) {
for _, k := range c.keys(frontend) {
c.evictWithLock(recordLocation{frontend, k})
}
}
// Make copy of frontend keys to prevent itterator invalidation.
// Requires lock on c.mu.
func (c *Cache) keys(frontend uint) []Key {
m := c.buckets[frontend]
keys := make([]Key, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return keys
}
// Evict all records from cache
func (c *Cache) EvictAll() {
c.mu.Lock()
defer c.mu.Unlock()
for i := uint(0); i < c.frontendIDCounter; i++ {
c.evictFrontendWithLock(i)
}
}
// Evict keys from frontend using matcher function fn.
// fn returns true, if a key must be evicted.
func (c *Cache) evictByFunc(frontend uint, fn func(Key) (bool, error),
) (err error) {
c.mu.Lock()
defer c.mu.Unlock()
var (
b = c.buckets[frontend]
evict bool
)
for _, k := range c.keys(frontend) {
// Check, if key not already evicted by recursive eviction, to reduce
// potentially expensive matcher function calls
if _, ok := b[k]; !ok {
continue
}
evict, err = fn(k)
if err != nil {
return
}
if evict {
c.evictWithLock(recordLocation{frontend, k})
}
}
return
}