github.com/prysmaticlabs/prysm@v1.4.4/slasher/cache/flat_span_cache.go (about) 1 package cache 2 3 import ( 4 lru "github.com/hashicorp/golang-lru" 5 types "github.com/prysmaticlabs/eth2-types" 6 slashertypes "github.com/prysmaticlabs/prysm/slasher/detection/attestations/types" 7 ) 8 9 // EpochFlatSpansCache is used to store the spans needed on a per-epoch basis for slashing detection. 10 type EpochFlatSpansCache struct { 11 cache *lru.Cache 12 } 13 14 // NewEpochFlatSpansCache initializes the underlying cache with the given size and on evict function. 15 func NewEpochFlatSpansCache(size int, onEvicted func(key interface{}, value interface{})) (*EpochFlatSpansCache, error) { 16 if size != 0 { 17 epochSpansCacheSize = size 18 } 19 cache, err := lru.NewWithEvict(epochSpansCacheSize, onEvicted) 20 if err != nil { 21 return nil, err 22 } 23 return &EpochFlatSpansCache{cache: cache}, nil 24 } 25 26 // Get returns an ok bool and the cached value for the requested epoch key, if any. 27 func (c *EpochFlatSpansCache) Get(epoch types.Epoch) (*slashertypes.EpochStore, bool) { 28 item, exists := c.cache.Get(epoch) 29 if exists && item != nil { 30 epochSpansCacheHit.Inc() 31 return item.(*slashertypes.EpochStore), true 32 } 33 34 epochSpansCacheMiss.Inc() 35 return &slashertypes.EpochStore{}, false 36 } 37 38 // Set the response in the cache. 39 func (c *EpochFlatSpansCache) Set(epoch types.Epoch, epochSpans *slashertypes.EpochStore) { 40 _ = c.cache.Add(epoch, epochSpans) 41 } 42 43 // Delete removes an epoch from the cache and returns if it existed or not. 44 // Performs the onEviction function before removal. 45 func (c *EpochFlatSpansCache) Delete(epoch types.Epoch) bool { 46 return c.cache.Remove(epoch) 47 } 48 49 // PruneOldest removes the oldest key from the span cache, calling its OnEvict function. 50 func (c *EpochFlatSpansCache) PruneOldest() uint64 { 51 if c.cache.Len() == epochSpansCacheSize { 52 epoch, _, _ := c.cache.RemoveOldest() 53 return epoch.(uint64) 54 } 55 return 0 56 } 57 58 // Has returns true if the key exists in the cache. 59 func (c *EpochFlatSpansCache) Has(epoch types.Epoch) bool { 60 return c.cache.Contains(epoch) 61 } 62 63 // Purge removes all keys from the SpanCache and evicts all current data. 64 func (c *EpochFlatSpansCache) Purge() { 65 log.Info("Saving all cached data to DB, please wait for completion.") 66 c.cache.Purge() 67 } 68 69 // Length returns the number of cached items. 70 func (c *EpochFlatSpansCache) Length() int { 71 return c.cache.Len() 72 }