garage/src/util/metrics.rs

64 lines
1.3 KiB
Rust
Raw Normal View History

use std::time::Instant;
2022-02-22 12:53:59 +00:00
use futures::{future::BoxFuture, Future, FutureExt};
2022-02-22 14:21:06 +00:00
use rand::Rng;
2022-02-22 12:53:59 +00:00
2022-02-22 14:21:06 +00:00
use opentelemetry::{metrics::*, trace::TraceId, KeyValue};
2022-02-22 12:53:59 +00:00
pub trait RecordDuration<'a>: 'a {
type Output;
2022-02-22 13:52:41 +00:00
fn record_duration(
self,
r: &'a ValueRecorder<f64>,
attributes: &'a [KeyValue],
) -> BoxFuture<'a, Self::Output>;
2022-02-22 12:53:59 +00:00
fn bound_record_duration(self, r: &'a BoundValueRecorder<f64>) -> BoxFuture<'a, Self::Output>;
}
impl<'a, T, O> RecordDuration<'a> for T
2022-02-22 13:52:41 +00:00
where
T: Future<Output = O> + Send + 'a,
{
2022-02-22 12:53:59 +00:00
type Output = O;
2022-02-22 13:52:41 +00:00
fn record_duration(
self,
r: &'a ValueRecorder<f64>,
attributes: &'a [KeyValue],
) -> BoxFuture<'a, Self::Output> {
2022-02-22 12:53:59 +00:00
async move {
let request_start = Instant::now();
2022-02-22 12:53:59 +00:00
let res = self.await;
2022-02-22 13:52:41 +00:00
r.record(
Instant::now()
.saturating_duration_since(request_start)
.as_secs_f64(),
2022-02-22 13:52:41 +00:00
attributes,
);
2022-02-22 12:53:59 +00:00
res
2022-02-22 13:52:41 +00:00
}
.boxed()
2022-02-22 12:53:59 +00:00
}
fn bound_record_duration(self, r: &'a BoundValueRecorder<f64>) -> BoxFuture<'a, Self::Output> {
async move {
let request_start = Instant::now();
2022-02-22 12:53:59 +00:00
let res = self.await;
r.record(
Instant::now()
.saturating_duration_since(request_start)
.as_secs_f64(),
);
2022-02-22 12:53:59 +00:00
res
2022-02-22 13:52:41 +00:00
}
.boxed()
2022-02-22 12:53:59 +00:00
}
}
2022-02-22 14:21:06 +00:00
// ----
pub fn gen_trace_id() -> TraceId {
rand::thread_rng().gen::<[u8; 16]>().into()
}