@@ -2,23 +2,26 @@ package metrics
22
33import (
44 "context"
5- "sync"
65 "time"
76
7+ "github.com/jellydator/ttlcache/v3"
88 "github.com/libp2p/go-libp2p/core/peer"
99 "github.com/rs/zerolog/log"
1010 "go.opentelemetry.io/otel/metric"
1111)
1212
13+ const (
14+ SESSION_TTL = time .Minute * 10
15+ )
16+
1317type MpcMetrics struct {
1418 totalRelayersGauge metric.Int64ObservableGauge
1519 availableRelayersGauge metric.Int64ObservableGauge
1620 totalRelayerCount * int64
1721 availableRelayerCount * int64
1822
19- sessionTimeHistogram metric.Float64Histogram
20- sessionStartTime map [string ]time.Time
21- histogramMutex sync.Mutex
23+ sessionTimeHistogram metric.Float64Histogram
24+ sessionStartTimeCache * ttlcache.Cache [string , time.Time ]
2225}
2326
2427// NewMpcMetrics initializes metrics related to the MPC set
@@ -56,8 +59,9 @@ func NewMpcMetrics(ctx context.Context, meter metric.Meter, opts metric.Measurem
5659 totalRelayerCount : totalRelayerCount ,
5760 availableRelayerCount : availableRelayerCount ,
5861 sessionTimeHistogram : sessionTimeHistogram ,
59- sessionStartTime : make (map [string ]time.Time ),
60- histogramMutex : sync.Mutex {},
62+ sessionStartTimeCache : ttlcache .New (
63+ ttlcache.WithTTL [string , time.Time ](SESSION_TTL ),
64+ ),
6165 }, nil
6266}
6367
@@ -67,21 +71,15 @@ func (m *MpcMetrics) TrackRelayerStatus(unavailable peer.IDSlice, all peer.IDSli
6771}
6872
6973func (m * MpcMetrics ) StartProcess (sessionID string ) {
70- m .histogramMutex .Lock ()
71- defer m .histogramMutex .Unlock ()
72-
73- m .sessionStartTime [sessionID ] = time .Now ()
74+ m .sessionStartTimeCache .Set (sessionID , time .Now (), ttlcache .DefaultTTL )
7475}
7576
7677func (m * MpcMetrics ) EndProcess (sessionID string ) {
77- m .histogramMutex .Lock ()
78- defer m .histogramMutex .Unlock ()
79-
80- startTime , ok := m .sessionStartTime [sessionID ]
81- if ! ok {
78+ startTime := m .sessionStartTimeCache .Get (sessionID )
79+ if startTime == nil {
8280 log .Warn ().Msgf ("Session start time with ID %s not found" , sessionID )
8381 return
8482 }
8583
86- m .sessionTimeHistogram .Record (context .Background (), time .Since (startTime ).Seconds ())
84+ m .sessionTimeHistogram .Record (context .Background (), time .Since (startTime . Value () ).Seconds ())
8785}
0 commit comments