11use std:: collections:: { HashMap , HashSet } ;
2+ use std:: sync:: RwLock ;
23
34use serde:: ser:: { SerializeSeq , Serializer } ;
45use serde:: { Deserialize , Deserializer , Serialize } ;
@@ -11,6 +12,57 @@ use super::metric::{Metric, MetricName};
1112use super :: prometheus:: PrometheusSerializable ;
1213use crate :: sample_collection:: SampleCollection ;
1314
15+ #[ derive( Debug , Default ) ]
16+ pub struct Metrics {
17+ inner : RwLock < MetricCollection > ,
18+ }
19+
20+ impl Metrics {
21+ #[ must_use]
22+ pub fn new ( counters : MetricKindCollection < Counter > , gauges : MetricKindCollection < Gauge > ) -> Self {
23+ Self {
24+ inner : RwLock :: new ( MetricCollection :: new ( counters, gauges) ) ,
25+ }
26+ }
27+
28+ // Counter-specific methods
29+
30+ /// # Panics
31+ ///
32+ /// Panics if it can't get read access to the inner collection.
33+ #[ must_use]
34+ pub fn get_counter_value ( & self , name : & MetricName , labels : & LabelSet ) -> Counter {
35+ self . inner . read ( ) . unwrap ( ) . counters . get_value ( name, labels)
36+ }
37+
38+ /// # Panics
39+ ///
40+ /// Panics if it can't get write access to the inner collection.
41+ pub fn increase_counter ( & mut self , name : & MetricName , labels : & LabelSet , time : DurationSinceUnixEpoch ) {
42+ self . inner . write ( ) . unwrap ( ) . increase_counter ( name, labels, time) ;
43+ }
44+
45+ // Gauge-specific methods
46+
47+ /// # Panics
48+ ///
49+ /// Panics if it can't get read access to the inner collection.
50+ #[ must_use]
51+ pub fn get_gauge_value ( & self , name : & MetricName , labels : & LabelSet ) -> Gauge {
52+ self . inner . read ( ) . unwrap ( ) . gauges . get_value ( name, labels)
53+ }
54+
55+ /// # Panics
56+ ///
57+ /// Panics if it can't get write access to the inner collection.
58+ pub fn set_gauge ( & mut self , name : & MetricName , labels : & LabelSet , value : f64 , time : DurationSinceUnixEpoch ) {
59+ self . inner . write ( ) . unwrap ( ) . set_gauge ( name, labels, value, time) ;
60+ }
61+ }
62+
63+ /// Use this type only when behind a lock that guarantees thread-safety.
64+ /// Otherwise, there could be race conditions that lead to duplicate metric
65+ /// names in different metric types.
1466#[ derive( Debug , Clone , Default , PartialEq ) ]
1567pub struct MetricCollection {
1668 counters : MetricKindCollection < Counter > ,
0 commit comments