Debian Codegraph @

cache.go

raw symbols SCIP
1 package cache
2
3 import (
4 "context"
5 "sync"
6 "time"
7
8 "github.com/Code-Hex/go-generics-cache/policy/clock"
9 "github.com/Code-Hex/go-generics-cache/policy/fifo"
10 "github.com/Code-Hex/go-generics-cache/policy/lfu"
11 "github.com/Code-Hex/go-generics-cache/policy/lru"
12 "github.com/Code-Hex/go-generics-cache/policy/mru"
13 "github.com/Code-Hex/go-generics-cache/policy/simple"
14 )
15
16 // Interface is a common-cache interface.
17 type Interface[K comparable, V any] interface {
18 // Get looks up a key's value from the cache.
19 Get(key K) (value V, ok bool)
20 // Set sets a value to the cache with key. replacing any existing value.
21 Set(key K, val V)
22 // Keys returns the keys of the cache. The order is relied on algorithms.
23 Keys() []K
24 // Delete deletes the item with provided key from the cache.
25 Delete(key K)
26 // Len returns the number of items in the cache.
27 Len() int
28 }
29
30 var (
31 _ = []Interface[struct{}, any]{
32 (*simple.Cache[struct{}, any])(nil),
33 (*lru.Cache[struct{}, any])(nil),
34 (*lfu.Cache[struct{}, any])(nil),
35 (*fifo.Cache[struct{}, any])(nil),
36 (*mru.Cache[struct{}, any])(nil),
37 (*clock.Cache[struct{}, any])(nil),
38 }
39 )
40
41 // Item is an item
42 type Item[K comparable, V any] struct {
43 Key K
44 Value V
45 Expiration time.Time
46 InitialReferenceCount int
47 }
48
49 func (item *Item[K, V]) hasExpiration() bool {
50 return !item.Expiration.IsZero()
51 }
52
53 // Expired returns true if the item has expired.
54 func (item *Item[K, V]) Expired() bool {
55 if !item.hasExpiration() {
56 return false
57 }
58 return nowFunc().After(item.Expiration)
59 }
60
61 // GetReferenceCount returns reference count to be used when setting
62 // the cache item for the first time.
63 func (item *Item[K, V]) GetReferenceCount() int {
64 return item.InitialReferenceCount
65 }
66
67 var nowFunc = time.Now
68
69 // ItemOption is an option for cache item.
70 type ItemOption func(*itemOptions)
71
72 type itemOptions struct {
73 expiration time.Time // default none
74 referenceCount int
75 }
76
77 // WithExpiration is an option to set expiration time for any items.
78 // If the expiration is zero or negative value, it treats as w/o expiration.
79 func WithExpiration(exp time.Duration) ItemOption {
80 return func(o *itemOptions) {
81 o.expiration = nowFunc().Add(exp)
82 }
83 }
84
85 // WithReferenceCount is an option to set reference count for any items.
86 // This option is only applicable to cache policies that have a reference count (e.g., Clock, LFU).
87 // referenceCount specifies the reference count value to set for the cache item.
88 //
89 // the default is 1.
90 func WithReferenceCount(referenceCount int) ItemOption {
91 return func(o *itemOptions) {
92 o.referenceCount = referenceCount
93 }
94 }
95
96 // newItem creates a new item with specified any options.
97 func newItem[K comparable, V any](key K, val V, opts ...ItemOption) *Item[K, V] {
98 o := new(itemOptions)
99 for _, optFunc := range opts {
100 optFunc(o)
101 }
102 return &Item[K, V]{
103 Key: key,
104 Value: val,
105 Expiration: o.expiration,
106 InitialReferenceCount: o.referenceCount,
107 }
108 }
109
110 // Cache is a thread safe cache.
111 type Cache[K comparable, V any] struct {
112 cache Interface[K, *Item[K, V]]
113 // mu is used to do lock in some method process.
114 mu sync.Mutex
115 janitor *janitor
116 expManager *expirationManager[K]
117 }
118
119 // Option is an option for cache.
120 type Option[K comparable, V any] func(*options[K, V])
121
122 type options[K comparable, V any] struct {
123 cache Interface[K, *Item[K, V]]
124 janitorInterval time.Duration
125 }
126
127 func newOptions[K comparable, V any]() *options[K, V] {
128 return &options[K, V]{
129 cache: simple.NewCache[K, *Item[K, V]](),
130 janitorInterval: time.Minute,
131 }
132 }
133
134 // AsLRU is an option to make a new Cache as LRU algorithm.
135 func AsLRU[K comparable, V any](opts ...lru.Option) Option[K, V] {
136 return func(o *options[K, V]) {
137 o.cache = lru.NewCache[K, *Item[K, V]](opts...)
138 }
139 }
140
141 // AsLFU is an option to make a new Cache as LFU algorithm.
142 func AsLFU[K comparable, V any](opts ...lfu.Option) Option[K, V] {
143 return func(o *options[K, V]) {
144 o.cache = lfu.NewCache[K, *Item[K, V]](opts...)
145 }
146 }
147
148 // AsFIFO is an option to make a new Cache as FIFO algorithm.
149 func AsFIFO[K comparable, V any](opts ...fifo.Option) Option[K, V] {
150 return func(o *options[K, V]) {
151 o.cache = fifo.NewCache[K, *Item[K, V]](opts...)
152 }
153 }
154
155 // AsMRU is an option to make a new Cache as MRU algorithm.
156 func AsMRU[K comparable, V any](opts ...mru.Option) Option[K, V] {
157 return func(o *options[K, V]) {
158 o.cache = mru.NewCache[K, *Item[K, V]](opts...)
159 }
160 }
161
162 // AsClock is an option to make a new Cache as clock algorithm.
163 func AsClock[K comparable, V any](opts ...clock.Option) Option[K, V] {
164 return func(o *options[K, V]) {
165 o.cache = clock.NewCache[K, *Item[K, V]](opts...)
166 }
167 }
168
169 // WithJanitorInterval is an option to specify how often cache should delete expired items.
170 //
171 // Default is 1 minute.
172 func WithJanitorInterval[K comparable, V any](d time.Duration) Option[K, V] {
173 return func(o *options[K, V]) {
174 o.janitorInterval = d
175 }
176 }
177
178 // New creates a new thread safe Cache.
179 // The janitor will not be stopped which is created by this function. If you
180 // want to stop the janitor gracefully, You should use the `NewContext` function
181 // instead of this.
182 //
183 // There are several Cache replacement policies available with you specified any options.
184 func New[K comparable, V any](opts ...Option[K, V]) *Cache[K, V] {
185 return NewContext(context.Background(), opts...)
186 }
187
188 // NewContext creates a new thread safe Cache with context.
189 // This function will be stopped an internal janitor when the context is cancelled.
190 //
191 // There are several Cache replacement policies available with you specified any options.
192 func NewContext[K comparable, V any](ctx context.Context, opts ...Option[K, V]) *Cache[K, V] {
193 o := newOptions[K, V]()
194 for _, optFunc := range opts {
195 optFunc(o)
196 }
197 cache := &Cache[K, V]{
198 cache: o.cache,
199 janitor: newJanitor(ctx, o.janitorInterval),
200 expManager: newExpirationManager[K](),
201 }
202 cache.janitor.run(cache.DeleteExpired)
203 return cache
204 }
205
206 // Get looks up a key's value from the cache.
207 func (c *Cache[K, V]) Get(key K) (zero V, ok bool) {
208 c.mu.Lock()
209 defer c.mu.Unlock()
210 item, ok := c.cache.Get(key)
211
212 if !ok {
213 return
214 }
215
216 // Returns nil if the item has been expired.
217 // Do not delete here and leave it to an external process such as Janitor.
218 if item.Expired() {
219 return zero, false
220 }
221
222 return item.Value, true
223 }
224
225 // GetOrSet atomically gets a key's value from the cache, or if the
226 // key is not present, sets the given value.
227 // The loaded result is true if the value was loaded, false if stored.
228 func (c *Cache[K, V]) GetOrSet(key K, val V, opts ...ItemOption) (actual V, loaded bool) {
229 c.mu.Lock()
230 defer c.mu.Unlock()
231 item, ok := c.cache.Get(key)
232
233 if !ok || item.Expired() {
234 item := newItem(key, val, opts...)
235 c.cache.Set(key, item)
236 return val, false
237 }
238
239 return item.Value, true
240 }
241
242 // DeleteExpired all expired items from the cache.
243 func (c *Cache[K, V]) DeleteExpired() {
244 c.mu.Lock()
245 l := c.expManager.len()
246 c.mu.Unlock()
247
248 evict := func() bool {
249 key := c.expManager.pop()
250 // if is expired, delete it and return nil instead
251 item, ok := c.cache.Get(key)
252 if ok {
253 if item.Expired() {
254 c.cache.Delete(key)
255 return false
256 }
257 c.expManager.update(key, item.Expiration)
258 }
259 return true
260 }
261
262 for i := 0; i < l; i++ {
263 c.mu.Lock()
264 shouldBreak := evict()
265 c.mu.Unlock()
266 if shouldBreak {
267 break
268 }
269 }
270 }
271
272 // Set sets a value to the cache with key. replacing any existing value.
273 func (c *Cache[K, V]) Set(key K, val V, opts ...ItemOption) {
274 c.mu.Lock()
275 defer c.mu.Unlock()
276 item := newItem(key, val, opts...)
277 if item.hasExpiration() {
278 c.expManager.update(key, item.Expiration)
279 }
280 c.cache.Set(key, item)
281 }
282
283 // Keys returns the keys of the cache. the order is relied on algorithms.
284 func (c *Cache[K, V]) Keys() []K {
285 c.mu.Lock()
286 defer c.mu.Unlock()
287 return c.cache.Keys()
288 }
289
290 // Delete deletes the item with provided key from the cache.
291 func (c *Cache[K, V]) Delete(key K) {
292 c.mu.Lock()
293 defer c.mu.Unlock()
294 c.cache.Delete(key)
295 c.expManager.remove(key)
296 }
297
298 // Len returns the number of items in the cache.
299 func (c *Cache[K, V]) Len() int {
300 c.mu.Lock()
301 defer c.mu.Unlock()
302 return c.cache.Len()
303 }
304
305 // Contains reports whether key is within cache.
306 func (c *Cache[K, V]) Contains(key K) bool {
307 c.mu.Lock()
308 defer c.mu.Unlock()
309 _, ok := c.cache.Get(key)
310 return ok
311 }
312
313 // NumberCache is a in-memory cache which is able to store only Number constraint.
314 type NumberCache[K comparable, V Number] struct {
315 *Cache[K, V]
316 // nmu is used to do lock in Increment/Decrement process.
317 // Note that this must be here as a separate mutex because mu in Cache struct is Locked in Get,
318 // and if we call mu.Lock in Increment/Decrement, it will cause deadlock.
319 nmu sync.Mutex
320 }
321
322 // NewNumber creates a new cache for Number constraint.
323 func NewNumber[K comparable, V Number](opts ...Option[K, V]) *NumberCache[K, V] {
324 return &NumberCache[K, V]{
325 Cache: New(opts...),
326 }
327 }
328
329 // Increment an item of type Number constraint by n.
330 // Returns the incremented value.
331 func (nc *NumberCache[K, V]) Increment(key K, n V) V {
332 // In order to avoid lost update, we must lock whole Increment/Decrement process.
333 nc.nmu.Lock()
334 defer nc.nmu.Unlock()
335 got, _ := nc.Cache.Get(key)
336 nv := got + n
337 nc.Cache.Set(key, nv)
338 return nv
339 }
340
341 // Decrement an item of type Number constraint by n.
342 // Returns the decremented value.
343 func (nc *NumberCache[K, V]) Decrement(key K, n V) V {
344 nc.nmu.Lock()
345 defer nc.nmu.Unlock()
346 got, _ := nc.Cache.Get(key)
347 nv := got - n
348 nc.Cache.Set(key, nv)
349 return nv
350 }