github.com/MetalBlockchain/metalgo@v1.11.9/cache/metercacher/cache.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package metercacher
     5  
     6  import (
     7  	"time"
     8  
     9  	"github.com/prometheus/client_golang/prometheus"
    10  
    11  	"github.com/MetalBlockchain/metalgo/cache"
    12  )
    13  
    14  var _ cache.Cacher[struct{}, struct{}] = (*Cache[struct{}, struct{}])(nil)
    15  
    16  type Cache[K comparable, V any] struct {
    17  	cache.Cacher[K, V]
    18  
    19  	metrics *metrics
    20  }
    21  
    22  func New[K comparable, V any](
    23  	namespace string,
    24  	registerer prometheus.Registerer,
    25  	cache cache.Cacher[K, V],
    26  ) (*Cache[K, V], error) {
    27  	metrics, err := newMetrics(namespace, registerer)
    28  	return &Cache[K, V]{
    29  		Cacher:  cache,
    30  		metrics: metrics,
    31  	}, err
    32  }
    33  
    34  func (c *Cache[K, V]) Put(key K, value V) {
    35  	start := time.Now()
    36  	c.Cacher.Put(key, value)
    37  	putDuration := time.Since(start)
    38  
    39  	c.metrics.putCount.Inc()
    40  	c.metrics.putTime.Add(float64(putDuration))
    41  	c.metrics.len.Set(float64(c.Cacher.Len()))
    42  	c.metrics.portionFilled.Set(c.Cacher.PortionFilled())
    43  }
    44  
    45  func (c *Cache[K, V]) Get(key K) (V, bool) {
    46  	start := time.Now()
    47  	value, has := c.Cacher.Get(key)
    48  	getDuration := time.Since(start)
    49  
    50  	if has {
    51  		c.metrics.getCount.With(hitLabels).Inc()
    52  		c.metrics.getTime.With(hitLabels).Add(float64(getDuration))
    53  	} else {
    54  		c.metrics.getCount.With(missLabels).Inc()
    55  		c.metrics.getTime.With(missLabels).Add(float64(getDuration))
    56  	}
    57  
    58  	return value, has
    59  }
    60  
    61  func (c *Cache[K, _]) Evict(key K) {
    62  	c.Cacher.Evict(key)
    63  
    64  	c.metrics.len.Set(float64(c.Cacher.Len()))
    65  	c.metrics.portionFilled.Set(c.Cacher.PortionFilled())
    66  }
    67  
    68  func (c *Cache[_, _]) Flush() {
    69  	c.Cacher.Flush()
    70  
    71  	c.metrics.len.Set(float64(c.Cacher.Len()))
    72  	c.metrics.portionFilled.Set(c.Cacher.PortionFilled())
    73  }