...
1 package reaper
2
3 import (
4 "sync"
5 "time"
6
7 "github.com/cybertec-postgresql/pgwatch/v3/internal/metrics"
8 )
9
10 var lastSQLFetchError sync.Map
11
12 type InstanceMetricCache struct {
13 cache map[string](metrics.Measurements)
14 sync.RWMutex
15 }
16
17 func NewInstanceMetricCache() *InstanceMetricCache {
18 return &InstanceMetricCache{
19 cache: make(map[string](metrics.Measurements)),
20 }
21 }
22
23 func (imc *InstanceMetricCache) Get(key string, age time.Duration) metrics.Measurements {
24 if key == "" {
25 return nil
26 }
27 imc.RLock()
28 defer imc.RUnlock()
29 instanceMetricEpochNs := (imc.cache[key]).GetEpoch()
30
31 if time.Now().UnixNano()-instanceMetricEpochNs > age.Nanoseconds() {
32 return nil
33 }
34 instanceMetricData, ok := imc.cache[key]
35 if !ok {
36 return nil
37 }
38 return instanceMetricData.DeepCopy()
39 }
40
41 func (imc *InstanceMetricCache) Put(key string, data metrics.Measurements) {
42 if len(data) == 0 || key == "" {
43 return
44 }
45 imc.Lock()
46 defer imc.Unlock()
47 m := data.DeepCopy()
48 if !m.IsEpochSet() {
49 m.Touch()
50 }
51 imc.cache[key] = m
52 }
53