This repository has been archived by the owner on May 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinmemory.go
260 lines (234 loc) · 6.18 KB
/
inmemory.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
package cache
import (
"fmt"
"runtime"
"time"
"github.com/Bose/go-cache/galapagos_gin/cache"
"github.com/Bose/cache/persistence"
lru "github.com/hashicorp/golang-lru"
)
// InMemoryStore - an in memory LRU store with expiry
type InMemoryStore struct {
*inMemoryStore
}
type inMemoryStore struct {
lru *lru.ARCCache
DefaultExp time.Duration
janitor *janitor
}
// NewGenericCacheEntry - create a new in memory cache entry
func (c *InMemoryStore) NewGenericCacheEntry(data interface{}, exp time.Duration) (newEntry GenericCacheEntry, err error) {
var t time.Duration
if exp != 0 {
t = exp
} else {
t = c.DefaultExp
}
now := time.Now().Unix()
expiresAt := now + int64(t/time.Second) // convert from nanoseconds
entry := GenericCacheEntry{Data: data, TimeAdded: now, ExpiresAt: expiresAt}
return entry, nil
}
// NewInMemoryStore - create a new in memory cache
func NewInMemoryStore(maxEntries int, defaultExpiration, cleanupInterval time.Duration, createMetric bool, metricLabel string) (*InMemoryStore, error) {
lru, err := lru.NewARC(maxEntries)
if err != nil {
return nil, err
}
c := &inMemoryStore{
lru: lru,
DefaultExp: defaultExpiration,
}
if createMetric {
label := "inmemory_cache_total_items_cnt"
if len(metricLabel) != 0 {
label = metricLabel
}
// setup metrics
initGaugeWithFunc(
func() float64 {
return float64(lru.Len())
},
label,
fmt.Sprintf("Total count the number of items in the in-memory cache for %s", label))
}
// This trick ensures that the janitor goroutine (which--granted it
// was enabled--is running DeleteExpired on c forever) does not keep
// the returned C object from being garbage collected. When it is
// garbage collected, the finalizer stops the janitor goroutine, after
// which c can be collected.
C := &InMemoryStore{c}
if cleanupInterval > 0 {
runJanitor(c, cleanupInterval)
runtime.SetFinalizer(C, stopJanitor)
}
return C, nil
}
// Get - Get an entry
func (c *InMemoryStore) Get(key string, value interface{}) error {
if val, ok := c.lru.Get(key); ok {
entry := val.(GenericCacheEntry)
if entry.Expired() {
c.lru.Remove(key)
return persistence.ErrCacheMiss
}
valueType := fmt.Sprintf("%T", value)
switch valueType {
case "*string":
*value.(*string) = entry.Data.(string)
return nil
case "*int":
*value.(*int) = entry.Data.(int)
return nil
case "*cache.GenericCacheEntry":
*value.(*GenericCacheEntry) = entry
return nil
case "*cache.ResponseCache":
*value.(*cache.ResponseCache) = entry.Data.(cache.ResponseCache)
return nil
}
return persistence.ErrNotSupport
}
return persistence.ErrCacheMiss
}
func (c *InMemoryStore) doAddSet(key string, value interface{}, exp time.Duration) error {
valueType := fmt.Sprintf("%T", value)
now := time.Now().Unix()
var expiresAt int64
if exp == persistence.FOREVER {
expiresAt = 0
} else if exp != 0 {
expiresAt = now + int64(exp/time.Second)
} else {
expiresAt = now + int64(c.DefaultExp/time.Second)
}
if valueType != "cache.GenericCacheEntry" {
e := GenericCacheEntry{Data: value, ExpiresAt: expiresAt, TimeAdded: now}
c.lru.Add(key, e)
return nil
}
e := GenericCacheEntry{Data: value.(GenericCacheEntry).Data, ExpiresAt: expiresAt, TimeAdded: now}
c.lru.Add(key, e)
return nil
}
// Keys - get all the keys
func (c *InMemoryStore) Keys() []interface{} {
return c.lru.Keys()
}
// Len - get the current count of entries in the cache
func (c *InMemoryStore) Len() int {
return c.lru.Len()
}
// Set - set an entry
func (c *InMemoryStore) Set(key string, value interface{}, exp time.Duration) error {
return c.doAddSet(key, value, exp)
}
// Add - add an entry
func (c *InMemoryStore) Add(key string, value interface{}, exp time.Duration) error {
if _, ok := c.lru.Get(key); ok {
return persistence.ErrNotStored
}
return c.doAddSet(key, value, exp)
}
// Replace - replace an entry
func (c *InMemoryStore) Replace(key string, value interface{}, exp time.Duration) error {
if _, ok := c.lru.Get(key); ok {
return c.doAddSet(key, value, exp)
}
return persistence.ErrNotStored
}
// Update - update an entry
func (c *InMemoryStore) Update(key string, entry GenericCacheEntry) error {
if _, ok := c.lru.Get(key); ok {
c.lru.Add(key, entry)
return nil
}
return persistence.ErrNotStored
}
// Delete - delete an entry
func (c *InMemoryStore) Delete(key string) error {
if _, ok := c.lru.Get(key); ok {
c.lru.Remove(key)
return nil
}
return persistence.ErrCacheMiss
}
// Increment (see CacheStore interface)
func (c *InMemoryStore) Increment(key string, n uint64) (uint64, error) {
v, ok := c.lru.Get(key)
if !ok {
return 0, persistence.ErrCacheMiss
}
entry := v.(GenericCacheEntry)
valueType := fmt.Sprintf("%T", entry.Data)
switch valueType {
case "int":
entry.Data = entry.Data.(int) + int(n)
c.lru.Add(key, entry)
return uint64(entry.Data.(int)), nil
}
return 0, persistence.ErrNotSupport
}
// Decrement (see CacheStore interface)
func (c *InMemoryStore) Decrement(key string, n uint64) (uint64, error) {
v, ok := c.lru.Get(key)
if !ok {
return 0, persistence.ErrCacheMiss
}
entry := v.(GenericCacheEntry)
valueType := fmt.Sprintf("%T", entry.Data)
switch valueType {
case "int":
if int(n) > entry.Data.(int) {
entry.Data = 0
} else {
entry.Data = entry.Data.(int) - int(n)
}
c.lru.Add(key, entry)
return uint64(entry.Data.(int)), nil
}
return 0, persistence.ErrNotSupport
}
// Flush (see CacheStore interface)
func (c *InMemoryStore) Flush() error {
c.lru.Purge()
return nil
}
// DeleteExpired - Delete all expired items from the cache.
func (c *inMemoryStore) DeleteExpired() {
keys := c.lru.Keys()
for _, key := range keys {
if entry, ok := c.lru.Get(key); ok {
e := entry.(GenericCacheEntry)
if e.Expired() {
c.lru.Remove(key)
}
}
}
}
type janitor struct {
Interval time.Duration
stop chan bool
}
func (j *janitor) Run(c *inMemoryStore) {
j.stop = make(chan bool)
tick := time.Tick(j.Interval)
for {
select {
case <-tick:
c.DeleteExpired()
case <-j.stop:
return
}
}
}
func stopJanitor(c *InMemoryStore) {
c.janitor.stop <- true
}
func runJanitor(c *inMemoryStore, ci time.Duration) {
j := &janitor{
Interval: ci,
}
c.janitor = j
go j.Run(c)
}