-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcacheMachine.go
More file actions
419 lines (339 loc) · 10.1 KB
/
cacheMachine.go
File metadata and controls
419 lines (339 loc) · 10.1 KB
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package cacheMachine
import (
"sync"
"time"
)
//===========[CACHE/STATIC]=============================================================================================
var defaultRequirements = Requirements{}
//===========[INTERFACES]===============================================================================================
//Key defines types that can be used as keys in the cache
type Key interface {
string | int | int64 | int32 | int16 | int8 | float32 | float64 | bool
}
type AllGetter[TKey Key, TValue any] interface {
GetAll() map[TKey]TValue
}
type AllGetterAndRemover[TKey Key, TValue any] interface {
GetAllAndRemove() map[TKey]TValue
}
type BulkAdder[TKey Key, TValue any] interface {
AddBulk(d map[TKey]TValue)
}
type Entry[TValue any] interface {
Value() TValue
ResetTimer(time.Duration)
StopTimer()
TimerExist() bool
}
//===========[STRUCTS]==================================================================================================
type Requirements struct {
//If this is set, by default, every cache entry will have a timeout of this duration after which
//the element will be removed from the cache. This timeout can be changed for individual entry
DefaultTimeout time.Duration
//Defines whether the DefaultTimeout is in use
timeoutInUse bool
}
//Individual entry in the cache
type entry[TValue any] struct {
//The value stored in the cache
Val TValue `json:"value" bson:"value"`
//This is the timer that monitors auto-removal of the element
timer *time.Timer
//Locks
mx sync.RWMutex
}
//------PRIVATE------
//Resets timeout duration to the duration specified. If 0 is supplied, it stops the timer
func (e *entry[TValue]) resetTimer(t time.Duration) {
if e.timer == nil {
return
}
if t.String() == "0s" {
e.timer.Stop()
return
}
e.timer.Reset(t)
}
//------PUBLIC------
//Value returns the value of this entry
func (e *entry[TValue]) Value() TValue {
return e.Val
}
//ResetTimer resets the countdown timer until the removal of this entry
func (e *entry[TValue]) ResetTimer(t time.Duration) {
e.mx.Lock()
e.resetTimer(t)
e.mx.Unlock()
}
//TimerExist checks whether the timer exist and returns boolean accordingly
func (e *entry[TValue]) TimerExist() bool {
if e.timer != nil {
return true
}
return false
}
//StopTimer stops the countdown timer until the element is removed
func (e *entry[TValue]) StopTimer() {
if e.timer == nil {
return
}
e.mx.Lock()
e.resetTimer(0)
e.mx.Unlock()
}
//Cache is the main definition of the cache
type cache[TKey Key, TValue any] struct {
Requirements Requirements
data map[TKey]*entry[TValue]
mx sync.RWMutex
}
type Cache[TKey Key, TValue any] struct {
cache[TKey, TValue]
}
//------PRIVATE------
//add method adds an item. This method has no mutex protection
func (c *Cache[TKey, TValue]) add(key TKey, val TValue, t time.Duration) Entry[TValue] {
e := entry[TValue]{
Val: val,
mx: sync.RWMutex{},
}
//Timer implementation
if t.String() != "0s" || c.cache.Requirements.timeoutInUse {
if t.String() == "0s" {
t = c.cache.Requirements.DefaultTimeout
}
e.timer = time.AfterFunc(t, func() {
c.Remove(key)
})
}
c.data[key] = &e
return &e
}
//addTImer adds new timer with specified duration if it doesn't yet exist. If timer is already present,
//this method resets it with the specified duration
func (c *Cache[TKey, TValue]) addTimer(key TKey, t time.Duration) {
e, exist := c.data[key]
if !exist {
return
}
if e.timer != nil {
e.timer.Reset(t)
return
}
e.timer = time.AfterFunc(t, func() { c.Remove(key) })
}
//remove method removes an item, but is not protected by a mutex
func (c *Cache[TKey, TValue]) remove(key TKey) {
delete(c.data, key)
}
//Creates a copy of the data. This function is not protected by locks
func (c *Cache[TKey, TValue]) copyValues() map[TKey]TValue {
cpy := make(map[TKey]TValue)
for key, entry := range c.data {
cpy[key] = entry.Val
}
return cpy
}
//reset clears the cache, but it's not using locks
func (c *Cache[TKey, TValue]) reset() {
c.data = make(map[TKey]*entry[TValue])
}
//getEntry is a private method tha returns Entry or nil and is not using mutexes
func (c *Cache[TKey, TValue]) getEntry(key TKey) Entry[TValue] {
if entry, exist := c.data[key]; !exist {
return nil
} else {
return entry
}
}
//------PUBLIC------
//AddTimer adds timer to the key specified. If the key already has a timer, it gets reset with the new duration specified
func (c *Cache[TKey, TValue]) AddTimer(key TKey, t time.Duration) {
c.mx.Lock()
c.addTimer(key, t)
c.mx.Unlock()
}
//Add inserts new key:value pair into the cache
func (c *Cache[TKey, TValue]) Add(key TKey, val TValue) Entry[TValue] {
c.mx.Lock()
defer c.mx.Unlock()
return c.add(key, val, 0)
}
//AddWithTimeout does the same as method "Add" but also sets timer for automatic removal of the entry
func (c *Cache[TKey, TValue]) AddWithTimeout(key TKey, val TValue, timeout time.Duration) Entry[TValue] {
c.mx.Lock()
defer c.mx.Unlock()
return c.add(key, val, timeout)
}
//AddBulk adds items to cache in bulk
func (c *Cache[TKey, TValue]) AddBulk(d map[TKey]TValue) {
if d == nil {
return
}
c.mx.Lock()
for k, v := range d {
c.add(k, v, 0)
}
c.mx.Unlock()
}
//Remove removes Val from the cache based on the key provided
func (c *Cache[TKey, TValue]) Remove(key TKey) {
c.mx.Lock()
c.remove(key)
c.mx.Unlock()
}
//RemoveBulk removes cached data based on keys provided
func (c *Cache[TKey, TValue]) RemoveBulk(keys []TKey) {
if keys == nil || len(keys) < 1 {
return
}
c.mx.Lock()
for _, key := range keys {
c.remove(key)
}
c.mx.Unlock()
}
//Get returns Value and boolean depending on whether the value exist in the cache
func (c *Cache[TKey, TValue]) Get(key TKey) (TValue, bool) {
c.mx.RLock()
defer c.mx.RUnlock()
if e := c.getEntry(key); e == nil {
var nilVal TValue
return nilVal, false
} else {
return e.Value(), true
}
}
//GetValue returns only Value based on the key provided
func (c *Cache[TKey, TValue]) GetValue(key TKey) TValue {
c.mx.RLock()
defer c.mx.RUnlock()
if e := c.getEntry(key); e == nil {
var nilVal TValue
return nilVal
} else {
return e.Value()
}
}
//GetEntry returns Entry interface for the value saved in the cache
func (c *Cache[TKey, TValue]) GetEntry(key TKey) Entry[TValue] {
c.mx.RLock()
defer c.mx.RUnlock()
return c.getEntry(key)
}
//GetBulk returns a map of key -> Val pairs where key is one provided in the slice
func (c *Cache[TKey, TValue]) GetBulk(d []TKey) map[TKey]TValue {
results := make(map[TKey]TValue)
c.mx.RLock()
for _, k := range d {
results[k] = c.data[k].Val
}
c.mx.RUnlock()
return results
}
//GetAndRemove returns requested Val and removes it from the cache
func (c *Cache[TKey, TValue]) GetAndRemove(key TKey) (TValue, bool) {
c.mx.Lock()
defer c.mx.Unlock()
defer c.remove(key)
e, exist := c.data[key]
return e.Val, exist
}
//GetAndRemoveEntry returns Entry interface and removes the entity from the cache immediately
func (c *Cache[TKey, TValue]) GetAndRemoveEntry(key TKey) Entry[TValue] {
c.mx.Lock()
defer c.mx.Unlock()
defer c.remove(key)
return c.data[key]
}
//GetAll returns all the values stored in the cache
func (c *Cache[TKey, TValue]) GetAll() map[TKey]TValue {
c.mx.RLock()
defer c.mx.RUnlock()
return c.copyValues()
}
//GetAllAndRemove returns and removes all the elements from the cache
func (c *Cache[TKey, TValue]) GetAllAndRemove() map[TKey]TValue {
c.mx.Lock()
defer c.mx.Unlock()
defer c.reset()
return c.copyValues()
}
//GetRandomSamples returns mixed set of items. Number of items is defined in the argument, if it exceeds the
//number of items that are present in the cache, it will return all the cached items
func (c *Cache[TKey, TValue]) GetRandomSamples(n int) map[TKey]TValue {
results := make(map[TKey]TValue)
for key, entry := range c.data {
if n < 1 {
break
}
results[key] = entry.Val
n--
}
return results
}
//Exist checks whether there the key exists in the cache
func (c *Cache[TKey, TValue]) Exist(key TKey) bool {
c.mx.RLock()
defer c.mx.RUnlock()
_, exist := c.data[key]
return exist
}
//Count returns number of elements currently present in the cache
func (c *Cache[TKey, TValue]) Count() int {
c.mx.Lock()
defer c.mx.Unlock()
return len(c.data)
}
//ForEach runs a loop for each element in the cache. Take care using this method as it locks reading/writing the
//cache until ForEach completes.
func (c *Cache[TKey, TValue]) ForEach(f func(TKey, TValue)) {
d := c.GetAll()
for k, v := range d {
f(k, v)
}
}
//Reset empties the cache and resets all the counters
func (c *Cache[TKey, TValue]) Reset() {
c.mx.Lock()
c.reset()
c.mx.Unlock()
}
//Requirements returns requirements used from this cache
func (c *Cache[TKey, TValue]) Requirements() Requirements {
return c.cache.Requirements
}
//===========[FUNCTIONALITY]====================================================================================================
//Adjusts and parses the Requirements
func makeRequirementsSensible(r *Requirements) {
//Checking whether the DefaultTimeout is in use. If yes, it sets timeoutInUse to true
r.timeoutInUse = r.DefaultTimeout.String() != "0s"
}
//New initiates new cache. It can also take in values that will be added to the cache immediately after initiation
func New[TKey Key, TValue any](r *Requirements) Cache[TKey, TValue] {
if r == nil {
r = &defaultRequirements
}
makeRequirementsSensible(r)
c := cache[TKey, TValue]{
Requirements: *r,
data: make(map[TKey]*entry[TValue]),
mx: sync.RWMutex{},
}
return Cache[TKey, TValue]{c}
}
//Copy creates identical copy of the cache supplied as an argument
func Copy[TKey Key, TValue any](c *Cache[TKey, TValue]) Cache[TKey, TValue] {
req := c.Requirements()
nc := New[TKey, TValue](&req)
nc.AddBulk(c.GetAll())
return nc
}
//Merge copies all data from cache2 into cache1
func Merge[TKey Key, TValue any](cache1 BulkAdder[TKey, TValue], cache2 AllGetter[TKey, TValue]) {
cache1.AddBulk(cache2.GetAll())
}
//MergeAndReset copies all data from cache2 into cache1 and wipes cache2 clean right after
func MergeAndReset[TKey Key, TValue any](cache1 BulkAdder[TKey, TValue], cache2 AllGetterAndRemover[TKey, TValue]) {
cache1.AddBulk(cache2.GetAllAndRemove())
}