-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
239 lines (191 loc) · 4.54 KB
/
Copy pathmain.go
File metadata and controls
239 lines (191 loc) · 4.54 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
package main
import (
"container/list"
"errors"
"log"
"sync"
"time"
)
const MaxEntries = 256
type Options struct {
TTL time.Duration
EvictionPolicy string
}
type Option func(*Options) error
// Cache structure
type Cache struct {
cache map[string]*list.Element
list *list.List
lock sync.Mutex
options Options
}
// entry is the data structure stored in the linked list
type entry struct {
bucket string
key string
value []byte
time time.Time
}
// NewCache creates a new Cache with default options
func NewCache(opts ...Option) *Cache {
cacheOptions := Options{
EvictionPolicy: "Oldest", // Default policy
}
for _, opt := range opts {
opt(&cacheOptions)
}
cache := &Cache{
cache: make(map[string]*list.Element),
list: list.New(),
options: cacheOptions,
}
//automatic delete if the cache has expired
go func() {
for e := cache.list.Front(); e != nil; e = e.Next() {
go automaticDelete(cache, e)
}
}()
return cache
}
// Set inserts a value into the cache.
func (c *Cache) Set(bucket, key string, value []byte, opts ...Option) error {
c.lock.Lock()
defer c.lock.Unlock()
// Apply options
for _, opt := range opts {
if err := opt(&c.options); err != nil {
return err
}
}
// check if the cache is full
if c.list.Len() == MaxEntries {
//evict the oldest item from the cache
c.evict(c.options.EvictionPolicy)
}
fullKey := bucket + ":" + key
el, ok := c.cache[fullKey]
if ok {
c.list.MoveToFront(el)
//update the value
el.Value.(*entry).value = value
//update the time
el.Value.(*entry).time = time.Now()
return nil
}
ent := &entry{bucket: bucket, key: fullKey, value: value, time: time.Now()}
element := c.list.PushFront(ent)
c.cache[fullKey] = element
return nil
}
// Get retrieves a value from the cache.
func (c *Cache) Get(bucket, key string, opts ...Option) ([]byte, error) {
c.lock.Lock()
defer c.lock.Unlock()
// Apply options
for _, opt := range opts {
if err := opt(&c.options); err != nil {
return nil, err
}
}
fullKey := bucket + ":" + key
if ele, hit := c.cache[fullKey]; hit {
c.list.MoveToFront(ele)
if c.options.TTL > 0 && time.Since(ele.Value.(*entry).time) > c.options.TTL {
c.list.Remove(ele)
delete(c.cache, fullKey)
return nil, errors.New("cache expired")
}
return ele.Value.(*entry).value, nil
}
return nil, errors.New("not found")
}
// Delete removes an entry from the cache.
func (c *Cache) Delete(bucket, key string, opts ...Option) error {
c.lock.Lock()
defer c.lock.Unlock()
// Apply options
for _, opt := range opts {
if err := opt(&c.options); err != nil {
return err
}
}
fullKey := bucket + ":" + key
if ele, hit := c.cache[fullKey]; hit {
c.removeElement(ele)
return nil
}
return errors.New("not found")
}
// evict removes the oldest item from the cache based on the eviction policy.
func (c *Cache) evict(policy string) {
switch policy {
case "Oldest":
c.removeElement(c.list.Back())
}
}
// removeElement handles the removal of an element from the cache.
func (c *Cache) removeElement(e *list.Element) {
c.list.Remove(e)
kv := e.Value.(*entry)
delete(c.cache, kv.key)
}
// automaticDelete is a helper function that automatically deletes an entry if it has expired.
func automaticDelete(c *Cache, e *list.Element) {
//run every minute
ticker := time.NewTicker(1 * time.Minute)
for {
select {
case <-ticker.C:
if time.Since(e.Value.(*entry).time) > c.options.TTL {
c.removeElement(e)
}
}
}
}
// ApplyOptions applies given option functions to the cache options.
func (c *Cache) ApplyOptions(opts ...Option) error {
for _, opt := range opts {
if err := opt(&c.options); err != nil {
return err
}
}
return nil
}
// WithTTL sets the time-to-live for cache entries.
func WithTTL(ttl time.Duration) Option {
return func(o *Options) error {
o.TTL = ttl
return nil
}
}
// WithEvictionPolicy sets the eviction policy for the cache.
func WithEvictionPolicy(policy string) Option {
return func(o *Options) error {
o.EvictionPolicy = policy
return nil
}
}
func main() {
cache := NewCache(WithTTL(10*time.Second), WithEvictionPolicy("Oldest"))
err := cache.Set("bucket", "key", []byte("value"))
if err != nil {
log.Println(err)
panic(err)
}
value, err := cache.Get("bucket", "key")
if err != nil {
log.Println(err)
panic(err)
}
log.Println(string(value))
//sleep for 11 seconds
time.Sleep(11 * time.Second)
_, err = cache.Get("bucket", "key")
if err != nil {
log.Println(err)
}
err = cache.Delete("bucket", "key")
if err != nil {
log.Println(err)
}
}