Debian Codegraph @

sieve/sieve.go

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