github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/data/cache/metric.go (about)

     1  package cache
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/angenalZZZ/gofunc/data/cache/metrics"
     7  	"github.com/angenalZZZ/gofunc/data/cache/store"
     8  )
     9  
    10  const (
    11  	// MetricType represents the metric cache type as a string value
    12  	MetricType = "metric"
    13  )
    14  
    15  // MetricCache is the struct that specifies metrics available for different caches
    16  type MetricCache struct {
    17  	metrics metrics.MetricsInterface
    18  	cache   Interface
    19  }
    20  
    21  // NewMetric creates a new cache with metrics and a given cache storage
    22  func NewMetric(metrics metrics.MetricsInterface, cache Interface) *MetricCache {
    23  	return &MetricCache{
    24  		metrics: metrics,
    25  		cache:   cache,
    26  	}
    27  }
    28  
    29  // Get obtains a value from cache and also records metrics
    30  func (c *MetricCache) Get(key string) (interface{}, error) {
    31  	result, err := c.cache.Get(key)
    32  
    33  	c.updateMetrics(c.cache)
    34  
    35  	return result, err
    36  }
    37  
    38  // Set sets a value from the cache
    39  func (c *MetricCache) Set(key string, object interface{}, options *store.Options) error {
    40  	return c.cache.Set(key, object, options)
    41  }
    42  
    43  // TTL returns an expiration time
    44  func (c *MetricCache) TTL(key string) (time.Duration, error) {
    45  	return c.cache.TTL(key)
    46  }
    47  
    48  // Delete removes a value from the cache
    49  func (c *MetricCache) Delete(key string) error {
    50  	return c.cache.Delete(key)
    51  }
    52  
    53  // Invalidate invalidates cache item from given options
    54  func (c *MetricCache) Invalidate(options store.InvalidateOptions) error {
    55  	return c.cache.Invalidate(options)
    56  }
    57  
    58  // Clear resets all cache data
    59  func (c *MetricCache) Clear() error {
    60  	return c.cache.Clear()
    61  }
    62  
    63  // Get obtains a value from cache and also records metrics
    64  func (c *MetricCache) updateMetrics(cache Interface) {
    65  	switch current := cache.(type) {
    66  	case *ChainCache:
    67  		for _, cache := range current.GetCaches() {
    68  			c.updateMetrics(cache)
    69  		}
    70  
    71  	case StorageInterface:
    72  		c.metrics.RecordFromCodec(current.GetCodec())
    73  	}
    74  }
    75  
    76  // GetType returns the cache type
    77  func (c *MetricCache) GetType() string {
    78  	return MetricType
    79  }