util/metrics.rs: Ported to opentelemetry 0.18.

This commit is contained in:
Jonathan Davies 2023-01-22 23:45:51 +00:00
parent 904d563ec3
commit 5ec3bde885

View file

@ -3,17 +3,17 @@ use std::time::Instant;
use futures::{future::BoxFuture, Future, FutureExt}; use futures::{future::BoxFuture, Future, FutureExt};
use rand::Rng; use rand::Rng;
use opentelemetry::{metrics::*, trace::TraceId, KeyValue}; use opentelemetry::{metrics::*, trace::TraceId, Context, KeyValue};
pub trait RecordDuration<'a>: 'a { pub trait RecordDuration<'a>: 'a {
type Output; type Output;
fn record_duration( fn record_duration(
self, self,
r: &'a ValueRecorder<f64>, r: &'a Histogram<f64>,
attributes: &'a [KeyValue], attributes: &'a [KeyValue],
) -> BoxFuture<'a, Self::Output>; ) -> BoxFuture<'a, Self::Output>;
fn bound_record_duration(self, r: &'a BoundValueRecorder<f64>) -> BoxFuture<'a, Self::Output>; fn bound_record_duration(self, r: &'a Histogram<f64>) -> BoxFuture<'a, Self::Output>;
} }
impl<'a, T, O> RecordDuration<'a> for T impl<'a, T, O> RecordDuration<'a> for T
@ -24,13 +24,14 @@ where
fn record_duration( fn record_duration(
self, self,
r: &'a ValueRecorder<f64>, r: &'a Histogram<f64>,
attributes: &'a [KeyValue], attributes: &'a [KeyValue],
) -> BoxFuture<'a, Self::Output> { ) -> BoxFuture<'a, Self::Output> {
async move { async move {
let request_start = Instant::now(); let request_start = Instant::now();
let res = self.await; let res = self.await;
r.record( r.record(
&Context::current(),
Instant::now() Instant::now()
.saturating_duration_since(request_start) .saturating_duration_since(request_start)
.as_secs_f64(), .as_secs_f64(),
@ -41,14 +42,16 @@ where
.boxed() .boxed()
} }
fn bound_record_duration(self, r: &'a BoundValueRecorder<f64>) -> BoxFuture<'a, Self::Output> { fn bound_record_duration(self, r: &'a Histogram<f64>) -> BoxFuture<'a, Self::Output> {
async move { async move {
let request_start = Instant::now(); let request_start = Instant::now();
let res = self.await; let res = self.await;
r.record( r.record(
&Context::current(),
Instant::now() Instant::now()
.saturating_duration_since(request_start) .saturating_duration_since(request_start)
.as_secs_f64(), .as_secs_f64(),
&[],
); );
res res
} }