Debian Codegraph @

lfu.go

raw symbols SCIP
1 package gcache
2
3 import (
4 "container/list"
5 "time"
6 )
7
8 // Discards the least frequently used items first.
9 type LFUCache struct {
10 baseCache
11 items map[interface{}]*lfuItem
12 freqList *list.List // list for freqEntry
13 }
14
15 var _ Cache = (*LFUCache)(nil)
16
17 type lfuItem struct {
18 clock Clock
19 key interface{}
20 value interface{}
21 freqElement *list.Element
22 expiration *time.Time
23 }
24
25 type freqEntry struct {
26 freq uint
27 items map[*lfuItem]struct{}
28 }
29
30 func newLFUCache(cb *CacheBuilder) *LFUCache {
31 c := &LFUCache{}
32 buildCache(&c.baseCache, cb)
33
34 c.init()
35 c.loadGroup.cache = c
36 return c
37 }
38
39 func (c *LFUCache) init() {
40 c.freqList = list.New()
41 c.items = make(map[interface{}]*lfuItem, c.size)
42 c.freqList.PushFront(&freqEntry{
43 freq: 0,
44 items: make(map[*lfuItem]struct{}),
45 })
46 }
47
48 // Set a new key-value pair
49 func (c *LFUCache) Set(key, value interface{}) error {
50 c.mu.Lock()
51 defer c.mu.Unlock()
52 _, err := c.set(key, value)
53 return err
54 }
55
56 // Set a new key-value pair with an expiration time
57 func (c *LFUCache) SetWithExpire(key, value interface{}, expiration time.Duration) error {
58 c.mu.Lock()
59 defer c.mu.Unlock()
60 item, err := c.set(key, value)
61 if err != nil {
62 return err
63 }
64
65 t := c.clock.Now().Add(expiration)
66 item.(*lfuItem).expiration = &t
67 return nil
68 }
69
70 func (c *LFUCache) set(key, value interface{}) (interface{}, error) {
71 var err error
72 if c.serializeFunc != nil {
73 value, err = c.serializeFunc(key, value)
74 if err != nil {
75 return nil, err
76 }
77 }
78
79 // Check for existing item
80 item, ok := c.items[key]
81 if ok {
82 item.value = value
83 } else {
84 // Verify size not exceeded
85 if len(c.items) >= c.size {
86 c.evict(1)
87 }
88 item = &lfuItem{
89 clock: c.clock,
90 key: key,
91 value: value,
92 freqElement: nil,
93 }
94 el := c.freqList.Front()
95 fe := el.Value.(*freqEntry)
96 fe.items[item] = struct{}{}
97
98 item.freqElement = el
99 c.items[key] = item
100 }
101
102 if c.expiration != nil {
103 t := c.clock.Now().Add(*c.expiration)
104 item.expiration = &t
105 }
106
107 if c.addedFunc != nil {
108 c.addedFunc(key, value)
109 }
110
111 return item, nil
112 }
113
114 // Get a value from cache pool using key if it exists.
115 // If it dose not exists key and has LoaderFunc,
116 // generate a value using `LoaderFunc` method returns value.
117 func (c *LFUCache) Get(key interface{}) (interface{}, error) {
118 v, err := c.get(key, false)
119 if err == KeyNotFoundError {
120 return c.getWithLoader(key, true)
121 }
122 return v, err
123 }
124
125 // GetIFPresent gets a value from cache pool using key if it exists.
126 // If it dose not exists key, returns KeyNotFoundError.
127 // And send a request which refresh value for specified key if cache object has LoaderFunc.
128 func (c *LFUCache) GetIFPresent(key interface{}) (interface{}, error) {
129 v, err := c.get(key, false)
130 if err == KeyNotFoundError {
131 return c.getWithLoader(key, false)
132 }
133 return v, err
134 }
135
136 func (c *LFUCache) get(key interface{}, onLoad bool) (interface{}, error) {
137 v, err := c.getValue(key, onLoad)
138 if err != nil {
139 return nil, err
140 }
141 if c.deserializeFunc != nil {
142 return c.deserializeFunc(key, v)
143 }
144 return v, nil
145 }
146
147 func (c *LFUCache) getValue(key interface{}, onLoad bool) (interface{}, error) {
148 c.mu.Lock()
149 item, ok := c.items[key]
150 if ok {
151 if !item.IsExpired(nil) {
152 c.increment(item)
153 v := item.value
154 c.mu.Unlock()
155 if !onLoad {
156 c.stats.IncrHitCount()
157 }
158 return v, nil
159 }
160 c.removeItem(item)
161 }
162 c.mu.Unlock()
163 if !onLoad {
164 c.stats.IncrMissCount()
165 }
166 return nil, KeyNotFoundError
167 }
168
169 func (c *LFUCache) getWithLoader(key interface{}, isWait bool) (interface{}, error) {
170 if c.loaderExpireFunc == nil {
171 return nil, KeyNotFoundError
172 }
173 value, _, err := c.load(key, func(v interface{}, expiration *time.Duration, e error) (interface{}, error) {
174 if e != nil {
175 return nil, e
176 }
177 c.mu.Lock()
178 defer c.mu.Unlock()
179 item, err := c.set(key, v)
180 if err != nil {
181 return nil, err
182 }
183 if expiration != nil {
184 t := c.clock.Now().Add(*expiration)
185 item.(*lfuItem).expiration = &t
186 }
187 return v, nil
188 }, isWait)
189 if err != nil {
190 return nil, err
191 }
192 return value, nil
193 }
194
195 func (c *LFUCache) increment(item *lfuItem) {
196 currentFreqElement := item.freqElement
197 currentFreqEntry := currentFreqElement.Value.(*freqEntry)
198 nextFreq := currentFreqEntry.freq + 1
199 delete(currentFreqEntry.items, item)
200
201 // a boolean whether reuse the empty current entry
202 removable := isRemovableFreqEntry(currentFreqEntry)
203
204 // insert item into a valid entry
205 nextFreqElement := currentFreqElement.Next()
206 switch {
207 case nextFreqElement == nil || nextFreqElement.Value.(*freqEntry).freq > nextFreq:
208 if removable {
209 currentFreqEntry.freq = nextFreq
210 nextFreqElement = currentFreqElement
211 } else {
212 nextFreqElement = c.freqList.InsertAfter(&freqEntry{
213 freq: nextFreq,
214 items: make(map[*lfuItem]struct{}),
215 }, currentFreqElement)
216 }
217 case nextFreqElement.Value.(*freqEntry).freq == nextFreq:
218 if removable {
219 c.freqList.Remove(currentFreqElement)
220 }
221 default:
222 panic("unreachable")
223 }
224 nextFreqElement.Value.(*freqEntry).items[item] = struct{}{}
225 item.freqElement = nextFreqElement
226 }
227
228 // evict removes the least frequence item from the cache.
229 func (c *LFUCache) evict(count int) {
230 entry := c.freqList.Front()
231 for i := 0; i < count; {
232 if entry == nil {
233 return
234 } else {
235 for item := range entry.Value.(*freqEntry).items {
236 if i >= count {
237 return
238 }
239 c.removeItem(item)
240 i++
241 }
242 entry = entry.Next()
243 }
244 }
245 }
246
247 // Has checks if key exists in cache
248 func (c *LFUCache) Has(key interface{}) bool {
249 c.mu.RLock()
250 defer c.mu.RUnlock()
251 now := time.Now()
252 return c.has(key, &now)
253 }
254
255 func (c *LFUCache) has(key interface{}, now *time.Time) bool {
256 item, ok := c.items[key]
257 if !ok {
258 return false
259 }
260 return !item.IsExpired(now)
261 }
262
263 // Remove removes the provided key from the cache.
264 func (c *LFUCache) Remove(key interface{}) bool {
265 c.mu.Lock()
266 defer c.mu.Unlock()
267
268 return c.remove(key)
269 }
270
271 func (c *LFUCache) remove(key interface{}) bool {
272 if item, ok := c.items[key]; ok {
273 c.removeItem(item)
274 return true
275 }
276 return false
277 }
278
279 // removeElement is used to remove a given list element from the cache
280 func (c *LFUCache) removeItem(item *lfuItem) {
281 entry := item.freqElement.Value.(*freqEntry)
282 delete(c.items, item.key)
283 delete(entry.items, item)
284 if isRemovableFreqEntry(entry) {
285 c.freqList.Remove(item.freqElement)
286 }
287 if c.evictedFunc != nil {
288 c.evictedFunc(item.key, item.value)
289 }
290 }
291
292 func (c *LFUCache) keys() []interface{} {
293 c.mu.RLock()
294 defer c.mu.RUnlock()
295 keys := make([]interface{}, len(c.items))
296 var i = 0
297 for k := range c.items {
298 keys[i] = k
299 i++
300 }
301 return keys
302 }
303
304 // GetALL returns all key-value pairs in the cache.
305 func (c *LFUCache) GetALL(checkExpired bool) map[interface{}]interface{} {
306 c.mu.RLock()
307 defer c.mu.RUnlock()
308 items := make(map[interface{}]interface{}, len(c.items))
309 now := time.Now()
310 for k, item := range c.items {
311 if !checkExpired || c.has(k, &now) {
312 items[k] = item.value
313 }
314 }
315 return items
316 }
317
318 // Keys returns a slice of the keys in the cache.
319 func (c *LFUCache) Keys(checkExpired bool) []interface{} {
320 c.mu.RLock()
321 defer c.mu.RUnlock()
322 keys := make([]interface{}, 0, len(c.items))
323 now := time.Now()
324 for k := range c.items {
325 if !checkExpired || c.has(k, &now) {
326 keys = append(keys, k)
327 }
328 }
329 return keys
330 }
331
332 // Len returns the number of items in the cache.
333 func (c *LFUCache) Len(checkExpired bool) int {
334 c.mu.RLock()
335 defer c.mu.RUnlock()
336 if !checkExpired {
337 return len(c.items)
338 }
339 var length int
340 now := time.Now()
341 for k := range c.items {
342 if c.has(k, &now) {
343 length++
344 }
345 }
346 return length
347 }
348
349 // Completely clear the cache
350 func (c *LFUCache) Purge() {
351 c.mu.Lock()
352 defer c.mu.Unlock()
353
354 if c.purgeVisitorFunc != nil {
355 for key, item := range c.items {
356 c.purgeVisitorFunc(key, item.value)
357 }
358 }
359
360 c.init()
361 }
362
363 // IsExpired returns boolean value whether this item is expired or not.
364 func (it *lfuItem) IsExpired(now *time.Time) bool {
365 if it.expiration == nil {
366 return false
367 }
368 if now == nil {
369 t := it.clock.Now()
370 now = &t
371 }
372 return it.expiration.Before(*now)
373 }
374
375 func isRemovableFreqEntry(entry *freqEntry) bool {
376 return entry.freq != 0 && len(entry.items) == 0
377 }