garage/src/util/metrics.rs

58 lines
1.2 KiB
Rust
Raw Normal View History

2022-02-22 12:53:59 +00:00
use std::time::SystemTime;
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 = SystemTime::now();
let res = self.await;
2022-02-22 13:52:41 +00:00
r.record(
request_start.elapsed().map_or(0.0, |d| d.as_secs_f64()),
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 = SystemTime::now();
let res = self.await;
r.record(request_start.elapsed().map_or(0.0, |d| d.as_secs_f64()));
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()
}