Dragonfly2
472 строки · 11.0 Кб
1/*
2* Copyright 2020 The Dragonfly Authors
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16
17//go:generate mockgen -destination cache_mock.go -source cache.go -package cache
18package cache
19
20import (
21"encoding/gob"
22"fmt"
23"io"
24"io/fs"
25"os"
26"path/filepath"
27"regexp"
28"runtime"
29"sync"
30"time"
31)
32
33type Item struct {
34Object any
35Expiration int64
36}
37
38// Returns true if the item has expired.
39func (item Item) Expired() bool {
40if item.Expiration == 0 {
41return false
42}
43return time.Now().UnixNano() > item.Expiration
44}
45
46const (
47// For use with functions that take an expiration time.
48NoExpiration time.Duration = -1
49
50// For use with functions that take an expiration time. Equivalent to
51// passing in the same expiration duration as was given to New() or
52// NewFrom() when the cache was created (e.g. 5 minutes.)
53DefaultExpiration time.Duration = 0
54
55// For use with functions that do not clean up.
56NoCleanup time.Duration = -1
57)
58
59type Cache interface {
60Scan(m string, n int) ([]string, error)
61Set(k string, x any, d time.Duration)
62SetDefault(k string, x any)
63Add(k string, x any, d time.Duration) error
64Get(k string) (any, bool)
65GetWithExpiration(k string) (any, time.Time, bool)
66Delete(k string)
67DeleteExpired()
68Keys() []string
69OnEvicted(f func(string, any))
70Save(w io.Writer) (err error)
71SaveFile(fname string) error
72Load(r io.Reader) error
73LoadFile(fname string) error
74Items() map[string]Item
75ItemCount() int
76Flush()
77}
78
79type cache struct {
80defaultExpiration time.Duration
81items map[string]Item
82mu sync.RWMutex
83onEvicted func(string, any)
84janitor *janitor
85}
86
87// Scan all items to get a specified number of matching regexp key.
88func (c *cache) Scan(m string, n int) ([]string, error) {
89c.mu.RLock()
90defer c.mu.RUnlock()
91
92regex, err := regexp.Compile(m)
93if err != nil {
94return nil, err
95}
96
97keys := make([]string, 0, n)
98for item := range c.items {
99if len(keys) >= n {
100break
101}
102
103if regex.MatchString(item) {
104keys = append(keys, item)
105}
106}
107
108return keys, nil
109}
110
111// Add an item to the cache, replacing any existing item. If the duration is 0
112// (DefaultExpiration), the cache's default expiration time is used. If it is -1
113// (NoExpiration), the item never expires.
114func (c *cache) Set(k string, x any, d time.Duration) {
115// "Inlining" of set
116var e int64
117if d == DefaultExpiration {
118d = c.defaultExpiration
119}
120if d > 0 {
121e = time.Now().Add(d).UnixNano()
122}
123c.mu.Lock()
124c.items[k] = Item{
125Object: x,
126Expiration: e,
127}
128// TODO: Calls to mu.Unlock are currently not deferred because defer
129// adds ~200 ns (as of go1.)
130c.mu.Unlock()
131}
132
133func (c *cache) set(k string, x any, d time.Duration) {
134var e int64
135if d == DefaultExpiration {
136d = c.defaultExpiration
137}
138if d > 0 {
139e = time.Now().Add(d).UnixNano()
140}
141c.items[k] = Item{
142Object: x,
143Expiration: e,
144}
145}
146
147// Add an item to the cache, replacing any existing item, using the default
148// expiration.
149func (c *cache) SetDefault(k string, x any) {
150c.Set(k, x, DefaultExpiration)
151}
152
153// Add an item to the cache only if an item doesn't already exist for the given
154// key, or if the existing item has expired. Returns an error otherwise.
155func (c *cache) Add(k string, x any, d time.Duration) error {
156c.mu.Lock()
157_, found := c.get(k)
158if found {
159c.mu.Unlock()
160return fmt.Errorf("Item %s already exists", k)
161}
162c.set(k, x, d)
163c.mu.Unlock()
164return nil
165}
166
167// Get an item from the cache. Returns the item or nil, and a bool indicating
168// whether the key was found.
169func (c *cache) Get(k string) (any, bool) {
170c.mu.RLock()
171// "Inlining" of get and Expired
172item, found := c.items[k]
173if !found {
174c.mu.RUnlock()
175return nil, false
176}
177
178c.mu.RUnlock()
179return item.Object, true
180}
181
182// GetWithExpiration returns an item and its expiration time from the cache.
183// It returns the item or nil, the expiration time if one is set (if the item
184// never expires a zero value for time.Time is returned), and a bool indicating
185// whether the key was found.
186func (c *cache) GetWithExpiration(k string) (any, time.Time, bool) {
187c.mu.RLock()
188// "Inlining" of get and Expired
189item, found := c.items[k]
190if !found {
191c.mu.RUnlock()
192return nil, time.Time{}, false
193}
194
195if item.Expiration > 0 {
196if time.Now().UnixNano() > item.Expiration {
197c.mu.RUnlock()
198return nil, time.Time{}, false
199}
200
201// Return the item and the expiration time
202c.mu.RUnlock()
203return item.Object, time.Unix(0, item.Expiration), true
204}
205
206// If expiration <= 0 (i.e. no expiration time set) then return the item
207// and a zeroed time.Time
208c.mu.RUnlock()
209return item.Object, time.Time{}, true
210}
211
212func (c *cache) get(k string) (any, bool) {
213item, found := c.items[k]
214if !found {
215return nil, false
216}
217// "Inlining" of Expired
218if item.Expiration > 0 {
219if time.Now().UnixNano() > item.Expiration {
220return nil, false
221}
222}
223return item.Object, true
224}
225
226// Delete an item from the cache. Does nothing if the key is not in the cache.
227func (c *cache) Delete(k string) {
228c.mu.Lock()
229v, evicted := c.delete(k)
230c.mu.Unlock()
231if evicted {
232c.onEvicted(k, v)
233}
234}
235
236func (c *cache) delete(k string) (any, bool) {
237if c.onEvicted != nil {
238if v, found := c.items[k]; found {
239delete(c.items, k)
240return v.Object, true
241}
242}
243delete(c.items, k)
244return nil, false
245}
246
247type keyAndValue struct {
248key string
249value any
250}
251
252// Delete all expired items from the cache.
253func (c *cache) DeleteExpired() {
254var evictedItems []keyAndValue
255now := time.Now().UnixNano()
256c.mu.Lock()
257for k, v := range c.items {
258// "Inlining" of expired
259if v.Expiration > 0 && now > v.Expiration {
260ov, evicted := c.delete(k)
261if evicted {
262evictedItems = append(evictedItems, keyAndValue{k, ov})
263}
264}
265}
266c.mu.Unlock()
267for _, v := range evictedItems {
268c.onEvicted(v.key, v.value)
269}
270}
271
272// Keys returns a sorted slice of all the keys in the cache.
273func (c *cache) Keys() []string {
274c.mu.RLock()
275defer c.mu.RUnlock()
276keys := make([]string, len(c.items))
277var i int
278for k := range c.items {
279keys[i] = k
280i++
281}
282return keys
283}
284
285// Sets an (optional) function that is called with the key and value when an
286// item is evicted from the cache. (Including when it is deleted manually, but
287// not when it is overwritten.) Set to nil to disable.
288func (c *cache) OnEvicted(f func(string, any)) {
289c.mu.Lock()
290c.onEvicted = f
291c.mu.Unlock()
292}
293
294// Write the cache's items (using Gob) to an io.Writer.
295//
296// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
297// documentation for NewFrom().)
298func (c *cache) Save(w io.Writer) (err error) {
299enc := gob.NewEncoder(w)
300defer func() {
301if x := recover(); x != nil {
302err = fmt.Errorf("Error registering item types with Gob library")
303}
304}()
305c.mu.RLock()
306defer c.mu.RUnlock()
307for _, v := range c.items {
308gob.Register(v.Object)
309}
310err = enc.Encode(&c.items)
311return
312}
313
314// Save the cache's items to the given filename, creating the file if it
315// doesn't exist, and overwriting it if it does.
316//
317// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
318// documentation for NewFrom().)
319func (c *cache) SaveFile(fname string) error {
320dir := filepath.Dir(fname)
321if err := os.MkdirAll(dir, fs.FileMode(0700)); err != nil {
322return err
323}
324
325fp, err := os.Create(fname)
326if err != nil {
327return err
328}
329
330defer fp.Close()
331
332return c.Save(fp)
333}
334
335// Add (Gob-serialized) cache items from an io.Reader, excluding any items with
336// keys that already exist (and haven't expired) in the current cache.
337//
338// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
339// documentation for NewFrom().)
340func (c *cache) Load(r io.Reader) error {
341dec := gob.NewDecoder(r)
342items := map[string]Item{}
343err := dec.Decode(&items)
344if err == nil {
345c.mu.Lock()
346defer c.mu.Unlock()
347for k, v := range items {
348ov, found := c.items[k]
349if !found || ov.Expired() {
350c.items[k] = v
351}
352}
353}
354return err
355}
356
357// Load and add cache items from the given filename, excluding any items with
358// keys that already exist in the current cache.
359//
360// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
361// documentation for NewFrom().)
362func (c *cache) LoadFile(fname string) error {
363fp, err := os.Open(fname)
364if err != nil {
365return err
366}
367err = c.Load(fp)
368if err != nil {
369fp.Close()
370return err
371}
372return fp.Close()
373}
374
375// Copies all unexpired items in the cache into a new map and returns it.
376func (c *cache) Items() map[string]Item {
377c.mu.RLock()
378defer c.mu.RUnlock()
379m := make(map[string]Item, len(c.items))
380now := time.Now().UnixNano()
381for k, v := range c.items {
382// "Inlining" of Expired
383if v.Expiration > 0 {
384if now > v.Expiration {
385continue
386}
387}
388m[k] = v
389}
390return m
391}
392
393// Returns the number of items in the cache. This may include items that have
394// expired, but have not yet been cleaned up.
395func (c *cache) ItemCount() int {
396c.mu.RLock()
397n := len(c.items)
398c.mu.RUnlock()
399return n
400}
401
402// Delete all items from the cache.
403func (c *cache) Flush() {
404c.mu.Lock()
405c.items = map[string]Item{}
406c.mu.Unlock()
407}
408
409type janitor struct {
410Interval time.Duration
411stop chan bool
412}
413
414func (j *janitor) Run(c *cache) {
415ticker := time.NewTicker(j.Interval)
416for {
417select {
418case <-ticker.C:
419c.DeleteExpired()
420case <-j.stop:
421ticker.Stop()
422return
423}
424}
425}
426
427func stopJanitor(c *cache) {
428c.janitor.stop <- true
429}
430
431func runJanitor(c *cache, ci time.Duration) {
432j := &janitor{
433Interval: ci,
434stop: make(chan bool),
435}
436c.janitor = j
437go j.Run(c)
438}
439
440func newCache(de time.Duration) *cache {
441if de == 0 {
442de = -1
443}
444c := &cache{
445defaultExpiration: de,
446items: make(map[string]Item),
447}
448return c
449}
450
451func newCacheWithJanitor(de time.Duration, ci time.Duration) Cache {
452c := newCache(de)
453// This trick ensures that the janitor goroutine (which--granted it
454// was enabled--is running DeleteExpired on c forever) does not keep
455// the returned C object from being garbage collected. When it is
456// garbage collected, the finalizer stops the janitor goroutine, after
457// which c can be collected.
458if ci > 0 {
459runJanitor(c, ci)
460runtime.SetFinalizer(c, stopJanitor)
461}
462return c
463}
464
465// Return a new cache with a given default expiration duration and cleanup
466// interval. If the expiration duration is less than one (or NoExpiration),
467// the items in the cache never expire (by default), and must be deleted
468// manually. If the cleanup interval is less than one, expired items are not
469// deleted from the cache before calling c.DeleteExpired().
470func New(defaultExpiration, cleanupInterval time.Duration) Cache {
471return newCacheWithJanitor(defaultExpiration, cleanupInterval)
472}
473