github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/pkg/cache/metrics.go (about) 1 package cache 2 3 import ( 4 "sync" 5 6 "github.com/jzelinskie/stringz" 7 "github.com/prometheus/client_golang/prometheus" 8 ) 9 10 func init() { 11 prometheus.MustRegister(defaultCollector) 12 } 13 14 const ( 15 promNamespace = "spicedb" 16 promSubsystem = "cache" 17 ) 18 19 var ( 20 descCacheHitsTotal = prometheus.NewDesc( 21 stringz.Join("_", promNamespace, promSubsystem, "hits_total"), 22 "Number of cache hits", 23 []string{"cache"}, 24 nil, 25 ) 26 27 descCacheMissesTotal = prometheus.NewDesc( 28 stringz.Join("_", promNamespace, promSubsystem, "misses_total"), 29 "Number of cache misses", 30 []string{"cache"}, 31 nil, 32 ) 33 34 descCostAddedBytes = prometheus.NewDesc( 35 stringz.Join("_", promNamespace, promSubsystem, "cost_added_bytes"), 36 "Cost of entries added to the cache", 37 []string{"cache"}, 38 nil, 39 ) 40 41 descCostEvictedBytes = prometheus.NewDesc( 42 stringz.Join("_", promNamespace, promSubsystem, "cost_evicted_bytes"), 43 "Cost of entries evicted from the cache", 44 []string{"cache"}, 45 nil, 46 ) 47 ) 48 49 var caches sync.Map 50 51 func mustRegisterCache(name string, c Cache) { 52 if _, loaded := caches.LoadOrStore(name, c); loaded { 53 panic("two caches with the same name") 54 } 55 } 56 57 func unregisterCache(name string) { 58 caches.Delete(name) 59 } 60 61 var ( 62 defaultCollector collector 63 64 _ prometheus.Collector = (*collector)(nil) 65 ) 66 67 type collector struct{} 68 69 func (c collector) Describe(ch chan<- *prometheus.Desc) { 70 prometheus.DescribeByCollect(c, ch) 71 } 72 73 func (c collector) Collect(ch chan<- prometheus.Metric) { 74 caches.Range(func(name, cache any) bool { 75 cacheName := name.(string) 76 metrics := cache.(Cache).GetMetrics() 77 ch <- prometheus.MustNewConstMetric(descCacheHitsTotal, prometheus.CounterValue, float64(metrics.Hits()), cacheName) 78 ch <- prometheus.MustNewConstMetric(descCacheMissesTotal, prometheus.CounterValue, float64(metrics.Misses()), cacheName) 79 ch <- prometheus.MustNewConstMetric(descCostAddedBytes, prometheus.CounterValue, float64(metrics.CostAdded()), cacheName) 80 ch <- prometheus.MustNewConstMetric(descCostEvictedBytes, prometheus.CounterValue, float64(metrics.CostEvicted()), cacheName) 81 return true 82 }) 83 }