Debian Codegraph @

s3fifo/s3fifo.go

raw symbols SCIP
1 package s3fifo
2
3 import (
4 "container/list"
5 "context"
6 "sync"
7 "time"
8
9 "github.com/scalalang2/golang-fifo/types"
10 )
11
12 const numberOfBuckets = 100
13
14 // entry holds the key and value of a cache entry.
15 type entry[K comparable, V any] struct {
16 key K
17 value V
18 freq byte
19 element *list.Element
20 expiredAt time.Time
21 bucketID int8 // bucketID is an index which the entry is stored in the bucket
22 }
23
24 // bucket is a container holding entries to be expired
25 // ref. hashicorp/golang-lru
26 type bucket[K comparable, V any] struct {
27 entries map[K]*entry[K, V]
28 newestEntry time.Time
29 }
30
31 type S3FIFO[K comparable, V any] struct {
32 ctx context.Context
33 cancel context.CancelFunc
34 mu sync.Mutex
35
36 // size is the maximum number of entries in the cache.
37 size int
38
39 // followings are the fundamental data structures of S3FIFO algorithm.
40 items map[K]*entry[K, V]
41 small *list.List
42 main *list.List
43 ghost *ghost[K]
44
45 buckets []bucket[K, V]
46
47 // ttl is the time to live of the cache entry
48 ttl time.Duration
49
50 // nextCleanupBucket is an index of the next bucket to be cleaned up
51 nextCleanupBucket int8
52
53 // callback is the function that will be called when an entry is evicted from the cache
54 callback types.OnEvictCallback[K, V]
55 }
56
57 var _ types.Cache[int, int] = (*S3FIFO[int, int])(nil)
58
59 func New[K comparable, V any](size int, ttl time.Duration) *S3FIFO[K, V] {
60 ctx, cancel := context.WithCancel(context.Background())
61
62 if ttl <= 0 {
63 ttl = 0
64 }
65
66 cache := &S3FIFO[K, V]{
67 ctx: ctx,
68 cancel: cancel,
69 size: size,
70 items: make(map[K]*entry[K, V]),
71 small: list.New(),
72 main: list.New(),
73 ghost: newGhost[K](size),
74 buckets: make([]bucket[K, V], numberOfBuckets),
75 ttl: ttl,
76 nextCleanupBucket: 0,
77 }
78
79 for i := 0; i < numberOfBuckets; i++ {
80 cache.buckets[i].entries = make(map[K]*entry[K, V])
81 }
82
83 if ttl != 0 {
84 go func(ctx context.Context) {
85 ticker := time.NewTicker(ttl / numberOfBuckets)
86 defer ticker.Stop()
87 for {
88 select {
89 case <-ctx.Done():
90 return
91 case <-ticker.C:
92 cache.deleteExpired()
93 }
94 }
95 }(cache.ctx)
96 }
97
98 return cache
99 }
100
101 func (s *S3FIFO[K, V]) Set(key K, value V) {
102 s.mu.Lock()
103 defer s.mu.Unlock()
104
105 if el, ok := s.items[key]; ok {
106 s.removeFromBucket(el) // remove from the bucket as the entry is updated
107 el.value = value
108 el.freq = min(el.freq+1, 3)
109 el.expiredAt = time.Now().Add(s.ttl)
110 s.addToBucket(el)
111 return
112 }
113
114 for s.small.Len()+s.main.Len() >= s.size {
115 s.evict()
116 }
117
118 // create a new entry to append it to the cache.
119 ent := &entry[K, V]{
120 key: key,
121 value: value,
122 freq: 0,
123 expiredAt: time.Now().Add(s.ttl),
124 }
125
126 if s.ghost.contains(key) {
127 s.ghost.remove(key)
128 ent.element = s.main.PushFront(key)
129 } else {
130 ent.element = s.small.PushFront(key)
131 }
132
133 s.items[key] = ent
134 s.addToBucket(ent)
135 }
136
137 func (s *S3FIFO[K, V]) Get(key K) (value V, ok bool) {
138 s.mu.Lock()
139 defer s.mu.Unlock()
140
141 if _, ok := s.items[key]; !ok {
142 return value, false
143 }
144
145 s.items[key].freq = min(s.items[key].freq+1, 3)
146 s.ghost.remove(key)
147 return s.items[key].value, true
148 }
149
150 func (s *S3FIFO[K, V]) Remove(key K) (ok bool) {
151 s.mu.Lock()
152 defer s.mu.Unlock()
153 if e, ok := s.items[key]; ok {
154 s.removeEntry(e, types.EvictReasonRemoved)
155 return true
156 }
157
158 return false
159 }
160
161 func (s *S3FIFO[K, V]) Contains(key K) (ok bool) {
162 s.mu.Lock()
163 defer s.mu.Unlock()
164
165 if _, ok := s.items[key]; ok {
166 return true
167 }
168 return false
169 }
170
171 func (s *S3FIFO[K, V]) Peek(key K) (value V, ok bool) {
172 s.mu.Lock()
173 defer s.mu.Unlock()
174
175 el, ok := s.items[key]
176 if !ok {
177 return value, false
178 }
179 return el.value, ok
180 }
181
182 func (s *S3FIFO[K, V]) SetOnEvicted(callback types.OnEvictCallback[K, V]) {
183 s.mu.Lock()
184 defer s.mu.Unlock()
185
186 s.callback = callback
187 }
188
189 func (s *S3FIFO[K, V]) Len() int {
190 return s.small.Len() + s.main.Len()
191 }
192
193 func (s *S3FIFO[K, V]) Purge() {
194 s.mu.Lock()
195 defer s.mu.Unlock()
196
197 for k := range s.items {
198 delete(s.items, k)
199 }
200
201 s.small.Init()
202 s.main.Init()
203 s.ghost.clear()
204 }
205
206 func (s *S3FIFO[K, V]) Close() {
207 s.Purge()
208 s.mu.Lock()
209 s.cancel()
210 s.mu.Unlock()
211 }
212
213 func (s *S3FIFO[K, V]) removeEntry(e *entry[K, V], reason types.EvictReason) {
214 if s.callback != nil {
215 s.callback(e.key, e.value, reason)
216 }
217
218 if s.ghost.contains(e.key) {
219 s.ghost.remove(e.key)
220 }
221
222 s.main.Remove(e.element)
223 s.small.Remove(e.element)
224 delete(s.items, e.key)
225 }
226
227 func (s *S3FIFO[K, V]) addToBucket(e *entry[K, V]) {
228 if s.ttl == 0 {
229 return
230 }
231 bucketId := (numberOfBuckets + s.nextCleanupBucket - 1) % numberOfBuckets
232 e.bucketID = bucketId
233 s.buckets[bucketId].entries[e.key] = e
234 if s.buckets[bucketId].newestEntry.Before(e.expiredAt) {
235 s.buckets[bucketId].newestEntry = e.expiredAt
236 }
237 }
238
239 func (s *S3FIFO[K, V]) removeFromBucket(e *entry[K, V]) {
240 if s.ttl == 0 {
241 return
242 }
243 delete(s.buckets[e.bucketID].entries, e.key)
244 }
245
246 func (s *S3FIFO[K, V]) deleteExpired() {
247 s.mu.Lock()
248
249 bucketId := s.nextCleanupBucket
250 s.nextCleanupBucket = (s.nextCleanupBucket + 1) % numberOfBuckets
251 bucket := &s.buckets[bucketId]
252 timeToExpire := time.Until(bucket.newestEntry)
253 if timeToExpire > 0 {
254 s.mu.Unlock()
255 time.Sleep(timeToExpire)
256 s.mu.Lock()
257 }
258
259 for _, e := range bucket.entries {
260 s.removeEntry(e, types.EvictReasonExpired)
261 }
262
263 s.mu.Unlock()
264 }
265
266 func (s *S3FIFO[K, V]) evict() {
267 // if size of the small queue is greater than 10% of the total cache size.
268 // then, evict from the small queue
269 if s.small.Len() > s.size/10 {
270 s.evictFromSmall()
271 return
272 }
273 s.evictFromMain()
274 }
275
276 func (s *S3FIFO[K, V]) evictFromSmall() {
277 mainCacheSize := s.size / 10 * 9
278
279 evicted := false
280 for !evicted && s.small.Len() > 0 {
281 key := s.small.Back().Value.(K)
282 el, ok := s.items[key]
283 if !ok {
284 panic("s3fifo: entry not found in the cache")
285 }
286
287 if el.freq > 1 {
288 // move the entry from the small queue to the main queue
289 s.small.Remove(el.element)
290 s.items[key].element = s.main.PushFront(el.key)
291
292 if s.main.Len() > mainCacheSize {
293 s.evictFromMain()
294 }
295 } else {
296 s.removeEntry(el, types.EvictReasonEvicted)
297 s.ghost.add(key)
298 evicted = true
299 delete(s.items, key)
300 }
301 }
302 }
303
304 func (s *S3FIFO[K, V]) evictFromMain() {
305 evicted := false
306 for !evicted && s.main.Len() > 0 {
307 key := s.main.Back().Value.(K)
308 el, ok := s.items[key]
309 if !ok {
310 panic("s3fifo: entry not found in the cache")
311 }
312
313 if el.freq > 0 {
314 s.main.Remove(el.element)
315 s.items[key].freq -= 1
316 s.items[key].element = s.main.PushFront(el.key)
317 } else {
318 s.removeEntry(el, types.EvictReasonEvicted)
319 evicted = true
320 delete(s.items, key)
321 }
322 }
323 }