-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru.go
108 lines (92 loc) · 2.39 KB
/
lru.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
package xlb
import (
"container/list"
"sync"
"time"
)
type CacheEntry struct {
IP string
ExpiresAt time.Time
Count int
}
// LRUCache simple LRU cache to store, search and easily evict data
type LRUCache struct {
capacity int
cache map[string]*list.Element
list *list.List
mutex sync.RWMutex
}
// NewLRUCache Constructor for LRU cache
func NewLRUCache(capacity int) *LRUCache {
return &LRUCache{
capacity: capacity,
cache: make(map[string]*list.Element),
list: list.New(),
}
}
// Get looks up value in the cache and returns it
func (c *LRUCache) Get(key string) (*CacheEntry, bool) {
c.mutex.RLock()
defer c.mutex.RUnlock()
if entry, ok := c.cache[key]; ok {
return entry.Value.(*CacheEntry), true
}
return nil, false
}
// Put adds value to the cache
func (c *LRUCache) Put(key string, t time.Time, count int) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.put(key, t, count)
}
// method to provide outside locking for more than one transaction in cache
func (c *LRUCache) put(key string, t time.Time, count int) {
if entry, ok := c.cache[key]; ok {
c.list.MoveToFront(entry)
entry.Value = &CacheEntry{key, t, count}
return
}
value := &CacheEntry{key, t, count}
newEntry := c.list.PushFront(value)
c.cache[key] = newEntry
if c.list.Len() > c.capacity {
lastEntry := c.list.Back()
c.list.Remove(lastEntry)
delete(c.cache, lastEntry.Value.(*CacheEntry).IP)
}
}
// IncrementCount increments counts for some record in the cache
func (c *LRUCache) IncrementCount(ip string, blockDuration time.Duration) {
c.mutex.Lock()
defer c.mutex.Unlock()
if entry, ok := c.cache[ip]; ok {
entry.Value.(*CacheEntry).Count++
entry.Value.(*CacheEntry).ExpiresAt = time.Now().Add(blockDuration * time.Duration(entry.Value.(*CacheEntry).Count))
c.list.MoveToFront(entry)
} else {
c.put(ip, time.Now().Add(blockDuration), 1)
}
}
// Invalidate particular element in the cache
func (c *LRUCache) Invalidate(key string) {
c.mutex.Lock()
defer c.mutex.Unlock()
if entry, ok := c.cache[key]; ok {
c.list.Remove(entry)
delete(c.cache, key)
}
}
// RemoveExpired bulk remove of expired records
func (c *LRUCache) RemoveExpired() {
c.mutex.Lock()
defer c.mutex.Unlock()
for c.list.Len() > 0 {
entry := c.list.Back().Value.(*CacheEntry)
if entry.ExpiresAt.Before(time.Now()) {
c.list.Remove(c.list.Back())
delete(c.cache, entry.IP)
} else {
break
}
}
}