-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
367 lines (320 loc) · 7.99 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
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
package goswift
import (
"errors"
"reflect"
"sync"
"time"
"github.com/leoantony72/goswift/expiry"
)
const (
ErrKeyNotFound = "key does not Exists"
ErrFieldNotFound = "field does not Exists"
ErrNotHashvalue = "not a Hash value/table"
ErrHmsetDataType = "invalid data type, Expected Struct/Map"
)
var close chan string
type Cache struct {
Data map[string]*dataHolder
length int
heap *expiry.Heap
mu sync.RWMutex
}
type dataHolder struct {
Value interface{}
Expiry *expiry.Node
}
// returns all data from the map with both key and value,
// expiry data will not be returned, returned data will be a
// copy of the original data
func (c *Cache) AllData() (map[string]interface{}, int) {
c.mu.RLock()
defer c.mu.RUnlock()
dataMap := make(map[string]interface{}, len(c.Data))
counter := 0
for k, v := range c.Data {
dataMap[k] = v.Value
counter++
}
return dataMap, counter
}
type snaphotData struct {
Value interface{}
Expiry int64
}
func (c *Cache) AllDatawithExpiry() map[string]snaphotData {
c.mu.Lock()
data := make(map[string]snaphotData)
for k, v := range c.Data {
s := &snaphotData{}
s.Value = v.Value
// d := data[k]
// d.Value = v.Value
if v.Expiry == nil {
s.Expiry = 0
} else {
s.Expiry = v.Expiry.Expiry
}
data[k] = *s
}
c.mu.Unlock()
return data
}
type CacheOptions struct {
EnableSnapshots bool
SnapshotInterval time.Duration
}
// Initialize a New CacheFunction type which is an Interfaces
// for all the availabel function
func NewCache(options ...CacheOptions) CacheFunction {
dataMap := make(map[string]*dataHolder)
heapInit := expiry.Init()
cache := &Cache{Data: dataMap, length: 0, heap: heapInit}
defaultOption := CacheOptions{
EnableSnapshots: false,
SnapshotInterval: time.Second * 5,
}
if options != nil {
defaultOption = mergeOptions(defaultOption, options[0])
}
if defaultOption.EnableSnapshots {
decoder(cache)
go snapShotTimer(cache, time.Second)
}
go sweaper(cache, heapInit)
close = make(chan string)
return cache
}
func mergeOptions(defaultOption CacheOptions, customOption CacheOptions) CacheOptions {
if customOption.EnableSnapshots {
defaultOption.EnableSnapshots = true
if customOption.SnapshotInterval != 0 {
defaultOption.SnapshotInterval = customOption.SnapshotInterval
}
}
return defaultOption
}
func testHeaps(c *Cache) []*expiry.Node {
c.mu.Lock()
// var h []*expiry.Heap
// d := c.heap.Data
dst := make([]*expiry.Node, len(c.heap.Data))
copy(dst, c.heap.Data)
c.mu.Unlock()
return dst
}
// Exists func receives the key check if it exists in the
// Hash Table and returns a boolean
func (c *Cache) Exists(key string) bool {
c.mu.RLock()
_, ok := c.Data[key]
c.mu.RUnlock()
return ok
}
// Internal exist func wihtout locking(c.mu.Lock)
func (c *Cache) ExistsNonBlocking(key string) bool {
_, ok := c.Data[key]
return ok
}
// Adds an element to Hash Set, If exp is provided add the
// Node to the Heap with Key and expiration time(int64).
// If exp == 0, Item Never expires, thus it isn't added
// In the Heap
func (c *Cache) Set(key string, val interface{}, exp int) {
c.mu.Lock()
var node *expiry.Node
if exp == 0 {
data := &dataHolder{Value: val}
c.Data[key] = data
c.mu.Unlock()
return
}
exp = exp / 1000
expTime := time.Now().Add(time.Second * time.Duration(exp)).Unix()
node = c.heap.Insert(key, expTime)
data := &dataHolder{Value: val, Expiry: node}
c.Data[key] = data
c.mu.Unlock()
}
// If exp is not nil, check if the element has expired or not
// Removes the element from the cache if expired, It does not remove
// The Node from the Heap, which will handled by the Sweaper.
// @This must be improved, So that deleted keys does'nt stay in the Heap.
func (c *Cache) Get(key string) (interface{}, error) {
c.mu.RLock()
data, ok := c.Data[key]
c.mu.RUnlock()
if !ok {
return nil, errors.New(ErrKeyNotFound)
}
if data.Expiry != nil {
if data.Expiry.Expiry > time.Now().Unix() {
return data.Value, nil
}
c.mu.Lock()
delete(c.Data, key)
c.mu.Unlock()
return nil, errors.New(ErrKeyNotFound)
}
return data.Value, nil
}
// Delete's the Item from the cache
// @This must be improved, So that deleted keys does'nt stay in the Heap.
func (c *Cache) Del(key string) {
c.mu.Lock()
if !c.ExistsNonBlocking(key) {
c.mu.Unlock()
return
}
data := c.Data[key]
// if !ok {
// c.mu.Unlock()
// return
// }
// fmt.Println(data.Expiry)
if data.Expiry == nil {
delete(c.Data, key)
c.mu.Unlock()
return
}
index := data.Expiry.Index
c.heap.Remove(index, len(c.heap.Data)-1)
delete(c.Data, key)
c.mu.Unlock()
}
// Set a new value for the key only if it already exist.
// New data will expire at the same time as the prev Key.
func (c *Cache) Update(key string, val interface{}) error {
if !c.Exists(key) {
return errors.New(ErrKeyNotFound)
}
c.mu.Lock()
e := c.Data[key].Expiry
data := &dataHolder{Value: val, Expiry: e}
c.Data[key] = data
c.mu.Unlock()
return nil
}
// Support for Hash data type, Hset func receives key, field and value
func (c *Cache) Hset(key, field string, value interface{}, exp int) {
c.mu.Lock()
if _, exists := c.Data[key]; !exists {
c.Data[key] = &dataHolder{}
c.Data[key].Value = make(map[string]interface{})
} else {
if c.Data[key].Expiry != nil {
c.heap.Remove(c.Data[key].Expiry.Index, len(c.heap.Data)-1)
}
}
var node *expiry.Node
if exp != 0 {
exp = exp / 1000
expTime := time.Now().Add(time.Second * time.Duration(exp)).Unix()
node = c.heap.Insert(key, expTime)
c.Data[key].Expiry = node
}
hash := c.Data[key].Value.(map[string]interface{})
hash[field] = value
c.mu.Unlock()
}
// Retrieves the field value of hash by key and field name
func (c *Cache) HGet(key, field string) (interface{}, error) {
if !c.Exists(key) {
return nil, errors.New(ErrKeyNotFound)
}
c.mu.RLock()
data := c.Data[key]
c.mu.RUnlock()
if mpval, ok := data.Value.(map[string]interface{}); ok {
if dataf, ok := mpval[field]; ok {
if data.Expiry != nil {
if data.Expiry.Expiry > time.Now().Unix() {
return dataf, nil
}
c.mu.Lock()
delete(c.Data, key)
c.mu.Unlock()
return nil, errors.New(ErrKeyNotFound)
}
return dataf, nil
}
return nil, errors.New(ErrFieldNotFound)
}
return nil, errors.New(ErrNotHashvalue)
}
/* @struct
type t struct{
name string
age int
place string
}
type tm map[string]int
tm{}
*/
// HMset takes a Struct/Map as the value , if any other datatype is
// Provided it will return an error.
func (c *Cache) HMset(key string, d interface{}, exp int) error {
valType := reflect.TypeOf(d)
fieldValues := reflect.ValueOf(d)
if valType.Kind() == reflect.Ptr {
valType = valType.Elem()
fieldValues = fieldValues.Elem()
}
// fmt.Println("type", valType.Kind())
switch valType.Kind() {
case reflect.Struct:
{
c.mu.Lock()
c.Data[key] = &dataHolder{Value: make(map[string]interface{})}
c.mu.Unlock()
for i := 0; i < valType.NumField(); i++ {
field := valType.Field(i)
value := fieldValues.Field(i).Interface()
c.Hset(key, field.Name, value, exp)
}
}
case reflect.Map:
{
for field, value := range d.(map[string]interface{}) {
// c.mu.Lock()
c.Hset(key, field, value, exp)
// c.mu.Unlock()
}
}
default:
return errors.New(ErrHmsetDataType)
}
return nil
}
// HgetAll retrives all the fields in a Hash by providing the key
func (c *Cache) HGetAll(key string) (map[string]interface{}, error) {
c.mu.RLock()
data, ok := c.Data[key]
c.mu.RUnlock()
if ok {
if mpData, oks := data.Value.(map[string]interface{}); oks {
if data.Expiry != nil {
if data.Expiry.Expiry > time.Now().Unix() {
return mpData, nil
}
c.mu.Lock()
delete(c.Data, key)
c.mu.Unlock()
return nil, errors.New(ErrKeyNotFound)
}
return mpData, nil
}
return nil, errors.New(ErrNotHashvalue)
}
return nil, errors.New(ErrKeyNotFound)
}
/*
func (c *Cache) AllDataHeap() []*expiry.Node {
c.mu.Lock()
// var h []*expiry.Heap
// d := c.heap.Data
dst := make([]*expiry.Node, len(c.heap.Data))
copy(dst, c.heap.Data)
c.mu.Unlock()
return dst
}
*/