-
Notifications
You must be signed in to change notification settings - Fork 70
/
cache.go
201 lines (166 loc) · 4.04 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
package piececache
import (
"container/heap"
"sync"
"time"
"github.com/cenkalti/rain/internal/semaphore"
"github.com/rcrowley/go-metrics"
)
// Cache is a LRU piece cache of certain size.
// Items in the cache are expired after the defined TTL.
type Cache struct {
size, maxSize int64
ttl time.Duration
items map[string]*item
accessList accessList
m sync.RWMutex
sem *semaphore.Semaphore
NumCached metrics.Meter
NumTotal metrics.Meter
NumLoad metrics.Meter
NumLoadedBytes metrics.Meter
closeC chan struct{}
}
// Loader is a function that loads data from a piece.
type Loader func() ([]byte, error)
// New returns new Cache.
func New(maxSize int64, ttl time.Duration, parallelReads uint) *Cache {
return &Cache{
maxSize: maxSize,
ttl: ttl,
items: make(map[string]*item),
sem: semaphore.New(int(parallelReads)),
NumCached: metrics.NewMeter(),
NumTotal: metrics.NewMeter(),
NumLoad: metrics.NewMeter(),
NumLoadedBytes: metrics.NewMeter(),
closeC: make(chan struct{}),
}
}
// Close the cache and release all resources.
func (c *Cache) Close() {
close(c.closeC)
c.NumCached.Stop()
c.NumTotal.Stop()
c.NumLoad.Stop()
c.NumLoadedBytes.Stop()
}
// Clear the cache. Drops all items in cache.
func (c *Cache) Clear() {
c.m.Lock()
c.items = make(map[string]*item)
for _, i := range c.accessList {
i.timer.Stop()
}
c.accessList = nil
c.size = 0
c.m.Unlock()
}
// Len returns the number of items in the cache. Items may be in different sizes.
func (c *Cache) Len() int {
c.m.RLock()
defer c.m.RUnlock()
return len(c.items)
}
// LoadsActive returns the number of active Loader calls.
func (c *Cache) LoadsActive() int {
return (c.sem.Len())
}
// LoadsWaiting returns the number of waiting Loader calls.
func (c *Cache) LoadsWaiting() int {
return (c.sem.Waiting())
}
// Size returns the total size of the items in the cache.
func (c *Cache) Size() int64 {
c.m.RLock()
defer c.m.RUnlock()
return c.size
}
// Utilization is a number between 0 and 100 that returns the hit-ratio of the cache.
func (c *Cache) Utilization() int {
total := c.NumTotal.Rate1()
if total == 0 {
return 0
}
return int((100 * c.NumCached.Rate1()) / total)
}
// Get item with the key from cache. If item is not in cache, load by calling `loader` func and put into the cache.
func (c *Cache) Get(key string, loader Loader) ([]byte, error) {
i := c.getItem(key)
return c.getValue(i, loader)
}
func (c *Cache) getItem(key string) *item {
c.m.Lock()
defer c.m.Unlock()
c.NumTotal.Mark(1)
i, ok := c.items[key]
if ok {
c.NumCached.Mark(1)
} else {
i = &item{key: key}
c.items[key] = i
}
return i
}
func (c *Cache) getValue(i *item, loader Loader) ([]byte, error) {
i.Lock()
defer i.Unlock()
if i.loaded {
if i.err != nil {
return nil, i.err
}
c.updateAccessTime(i)
return i.value, nil
}
c.sem.Wait()
i.value, i.err = loader()
c.sem.Signal()
i.loaded = true
c.NumLoad.Mark(1)
c.NumLoadedBytes.Mark(int64(len(i.value)))
return c.handleNewItem(i)
}
func (c *Cache) handleNewItem(i *item) ([]byte, error) {
c.m.Lock()
defer c.m.Unlock()
if i.err != nil {
delete(c.items, i.key)
return nil, i.err
}
// Do not cache values larger than cache size.
if int64(len(i.value)) > c.maxSize {
delete(c.items, i.key)
return i.value, nil
}
c.makeRoom(i)
c.size += int64(len(i.value))
i.lastAccessed = time.Now()
heap.Push(&c.accessList, i)
i.timer = time.AfterFunc(c.ttl, func() {
c.m.Lock()
if i.index != -1 {
c.removeItem(i)
}
c.m.Unlock()
})
return i.value, nil
}
func (c *Cache) updateAccessTime(i *item) {
c.m.Lock()
defer c.m.Unlock()
i.lastAccessed = time.Now()
heap.Fix(&c.accessList, i.index)
i.timer.Reset(c.ttl)
}
func (c *Cache) makeRoom(i *item) {
for c.maxSize-c.size < int64(len(i.value)) {
i := c.accessList[0]
c.removeItem(i)
}
}
func (c *Cache) removeItem(i *item) {
i.timer.Stop()
delete(c.items, i.key)
heap.Remove(&c.accessList, i.index)
c.size -= int64(len(i.value))
}