aboutsummaryrefslogtreecommitdiff
path: root/src/util/metrics.rs
blob: cd5aa182a83f4fee0328ef605fc3b5f6d418d4c8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use std::time::SystemTime;

use futures::{future::BoxFuture, Future, FutureExt};

use opentelemetry::{metrics::*, KeyValue};

pub trait RecordDuration<'a>: 'a {
	type Output;

	fn record_duration(
		self,
		r: &'a ValueRecorder<f64>,
		attributes: &'a [KeyValue],
	) -> BoxFuture<'a, Self::Output>;
	fn bound_record_duration(self, r: &'a BoundValueRecorder<f64>) -> BoxFuture<'a, Self::Output>;
}

impl<'a, T, O> RecordDuration<'a> for T
where
	T: Future<Output = O> + Send + 'a,
{
	type Output = O;

	fn record_duration(
		self,
		r: &'a ValueRecorder<f64>,
		attributes: &'a [KeyValue],
	) -> 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()),
				attributes,
			);
			res
		}
		.boxed()
	}

	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
		}
		.boxed()
	}
}