11use {
22 super :: ApiState ,
3- crate :: state:: State as AppState ,
3+ crate :: state:: metrics :: Metrics ,
44 axum:: {
55 extract:: {
66 MatchedPath ,
@@ -22,13 +22,19 @@ use {
2222 tokio:: time:: Instant ,
2323} ;
2424
25- pub struct Metrics {
25+ pub struct ApiMetrics {
2626 pub requests : Family < Labels , Counter > ,
2727 pub latencies : Family < Labels , Histogram > ,
2828}
2929
30- impl Metrics {
31- pub fn new ( state : Arc < AppState > ) -> Self {
30+ impl ApiMetrics {
31+ pub fn new < S > ( state : Arc < S > ) -> Self
32+ where
33+ S : Metrics ,
34+ S : Send ,
35+ S : Sync ,
36+ S : ' static ,
37+ {
3238 let new = Self {
3339 requests : Family :: default ( ) ,
3440 latencies : Family :: new_with_constructor ( || {
@@ -46,15 +52,21 @@ impl Metrics {
4652 let latencies = new. latencies . clone ( ) ;
4753
4854 tokio:: spawn ( async move {
49- let mut metrics_registry = state. metrics_registry . write ( ) . await ;
50-
51- metrics_registry. register ( "api_requests" , "Total number of API requests" , requests) ;
55+ Metrics :: register (
56+ & * state,
57+ ( "api_requests" , "Total number of API requests" , requests) ,
58+ )
59+ . await ;
5260
53- metrics_registry. register (
54- "api_request_latency_seconds" ,
55- "API request latency in seconds" ,
56- latencies,
57- ) ;
61+ Metrics :: register (
62+ & * state,
63+ (
64+ "api_request_latency_seconds" ,
65+ "API request latency in seconds" ,
66+ latencies,
67+ ) ,
68+ )
69+ . await ;
5870 } ) ;
5971 }
6072
@@ -80,21 +92,18 @@ pub async fn track_metrics<B>(
8092 } else {
8193 req. uri ( ) . path ( ) . to_owned ( )
8294 } ;
83- let method = req. method ( ) . clone ( ) ;
8495
96+ let method = req. method ( ) . clone ( ) ;
8597 let response = next. run ( req) . await ;
86-
8798 let latency = start. elapsed ( ) . as_secs_f64 ( ) ;
8899 let status = response. status ( ) . as_u16 ( ) ;
89-
90100 let labels = Labels {
91101 method : method. to_string ( ) ,
92102 path,
93103 status,
94104 } ;
95105
96106 api_state. metrics . requests . get_or_create ( & labels) . inc ( ) ;
97-
98107 api_state
99108 . metrics
100109 . latencies
0 commit comments