use std::time::{Duration, Instant};
use super::telemetry::byte_sample;
pub fn record_outbound(
target: &'static str,
route: &'static str,
status: Option<u16>,
elapsed: Duration,
request_bytes: Option<u64>,
response_bytes: Option<u64>,
) {
let status: String = status_label(status);
metrics::histogram!(
"http_client_request_duration_seconds",
"target" => target, "route" => route, "status" => status.clone()
)
.record(elapsed.as_secs_f64());
if let Some(bytes) = request_bytes {
metrics::histogram!(
"http_client_request_body_size_bytes",
"target" => target, "route" => route, "status" => status.clone()
)
.record(byte_sample(bytes));
}
if let Some(bytes) = response_bytes {
metrics::histogram!(
"http_client_response_body_size_bytes",
"target" => target, "route" => route, "status" => status
)
.record(byte_sample(bytes));
}
}
#[derive(Debug)]
#[must_use = "call finish() when the response (or the failure) arrives"]
pub struct OutboundCall {
target: &'static str,
route: &'static str,
started: Instant,
request_bytes: Option<u64>,
finished: bool,
}
impl OutboundCall {
pub fn start(target: &'static str, route: &'static str) -> Self {
Self {
target,
route,
started: Instant::now(),
request_bytes: None,
finished: false,
}
}
pub const fn request_bytes(mut self, bytes: u64) -> Self {
self.request_bytes = Some(bytes);
self
}
pub fn finish(mut self, status: Option<u16>, response_bytes: Option<u64>) {
self.finished = true;
record_outbound(
self.target,
self.route,
status,
self.started.elapsed(),
self.request_bytes,
response_bytes,
);
}
}
impl Drop for OutboundCall {
fn drop(&mut self) {
if !self.finished {
record_outbound(
self.target,
self.route,
None,
self.started.elapsed(),
None,
None,
);
}
}
}
fn status_label(status: Option<u16>) -> String {
match status {
Some(code @ 100..=599) => code.to_string(),
Some(_) => String::from("other"),
None => String::from("error"),
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::{OutboundCall, record_outbound, status_label};
use crate::webserver::telemetry::handle;
#[test]
fn a_status_outside_the_http_range_cannot_grow_the_series_count() {
assert_eq!("204", status_label(Some(204)));
assert_eq!("other", status_label(Some(999)));
assert_eq!("other", status_label(Some(0)));
assert_eq!("error", status_label(None));
}
#[test]
fn an_outbound_call_records_duration_and_both_sizes_under_its_labels() {
let _ = handle();
record_outbound(
"unit_target",
"/v1/things/{id}",
Some(200),
Duration::from_millis(30),
Some(300),
Some(5000),
);
let rendered: String = handle().render();
let labels: &str = r#"target="unit_target",route="/v1/things/{id}",status="200""#;
for series in [
"http_client_request_duration_seconds_count",
"http_client_request_body_size_bytes_count",
"http_client_response_body_size_bytes_count",
] {
let line: String = format!("{series}{{{labels}}} 1");
assert!(rendered.contains(&line), "{line} missing: {rendered}");
}
let sum: String = format!("http_client_request_body_size_bytes_sum{{{labels}}} 300");
assert!(rendered.contains(&sum), "{rendered}");
let bucket: String =
format!("http_client_response_body_size_bytes_bucket{{{labels},le=\"16384\"}} 1");
assert!(rendered.contains(&bucket), "{rendered}");
}
#[test]
fn a_failed_call_without_sizes_records_only_the_duration_as_error() {
let _ = handle();
OutboundCall::start("unit_down", "/ping").finish(None, None);
let rendered: String = handle().render();
assert!(
rendered.contains(
r#"http_client_request_duration_seconds_count{target="unit_down",route="/ping",status="error"} 1"#
),
"{rendered}"
);
assert!(
!rendered.contains(r#"body_size_bytes_count{target="unit_down""#),
"unknown sizes record nothing"
);
}
#[test]
fn a_call_dropped_without_finish_records_one_error() {
let _ = handle();
{
let _call: OutboundCall =
OutboundCall::start("unit_dropped", "/early").request_bytes(10);
}
OutboundCall::start("unit_finished", "/once").finish(Some(200), None);
let rendered: String = handle().render();
assert!(
rendered.contains(
r#"http_client_request_duration_seconds_count{target="unit_dropped",route="/early",status="error"} 1"#
),
"{rendered}"
);
assert!(
!rendered.contains(r#"body_size_bytes_count{target="unit_dropped""#),
"a dropped call records no sizes"
);
assert!(
rendered.contains(
r#"http_client_request_duration_seconds_count{target="unit_finished",route="/once",status="200"} 1"#
),
"{rendered}"
);
assert!(
!rendered.contains(r#"target="unit_finished",route="/once",status="error""#),
"finish must not also record on drop"
);
}
}