Skip to main content

webserver_base/webserver/
outbound.rs

1//! Metrics for calls the app makes to other services.
2
3use std::time::{Duration, Instant};
4
5use super::telemetry::byte_sample;
6
7/// Records one outbound HTTP call:
8/// `http_client_request_duration_seconds`,
9/// `http_client_request_body_size_bytes` and
10/// `http_client_response_body_size_bytes`, all labelled `target`, `route`,
11/// `status`.
12///
13/// `target` (the service: `"accounts"`, `"apns"`) and `route` (the call's
14/// template: `"/v1/users/{id}"`, never the filled-in URL) are `&'static str`
15/// on purpose: each distinct value is a new series, so they must come from a
16/// fixed set, never from ids, user input or IPs.
17///
18/// `status` is the HTTP status (`other` outside 100 to 599); `None` (no response: timeout, refused
19/// connection) is labelled `error`. A size that is unknown (a streamed body)
20/// is `None` and records nothing.
21pub fn record_outbound(
22    target: &'static str,
23    route: &'static str,
24    status: Option<u16>,
25    elapsed: Duration,
26    request_bytes: Option<u64>,
27    response_bytes: Option<u64>,
28) {
29    let status: String = status_label(status);
30    metrics::histogram!(
31        "http_client_request_duration_seconds",
32        "target" => target, "route" => route, "status" => status.clone()
33    )
34    .record(elapsed.as_secs_f64());
35    if let Some(bytes) = request_bytes {
36        metrics::histogram!(
37            "http_client_request_body_size_bytes",
38            "target" => target, "route" => route, "status" => status.clone()
39        )
40        .record(byte_sample(bytes));
41    }
42    if let Some(bytes) = response_bytes {
43        metrics::histogram!(
44            "http_client_response_body_size_bytes",
45            "target" => target, "route" => route, "status" => status
46        )
47        .record(byte_sample(bytes));
48    }
49}
50
51/// A timer around one outbound call; see [`record_outbound`] for the labels.
52///
53/// ```
54/// use webserver_base::webserver::OutboundCall;
55///
56/// let call: OutboundCall = OutboundCall::start("accounts", "/v1/users/{id}").request_bytes(120);
57/// // ... send the request ...
58/// call.finish(Some(200), Some(2048));
59/// ```
60///
61/// Dropping it without `finish` (a timeout or refused connection that exits
62/// early through `?`) records the duration so far as `status="error"`, with no
63/// sizes.
64#[derive(Debug)]
65#[must_use = "call finish() when the response (or the failure) arrives"]
66pub struct OutboundCall {
67    target: &'static str,
68    route: &'static str,
69    started: Instant,
70    request_bytes: Option<u64>,
71    finished: bool,
72}
73
74impl OutboundCall {
75    /// Starts the clock.
76    pub fn start(target: &'static str, route: &'static str) -> Self {
77        Self {
78            target,
79            route,
80            started: Instant::now(),
81            request_bytes: None,
82            finished: false,
83        }
84    }
85
86    /// The request body's size, when known.
87    pub const fn request_bytes(mut self, bytes: u64) -> Self {
88        self.request_bytes = Some(bytes);
89        self
90    }
91
92    /// Records the call: its status (`None` when no response came) and the
93    /// response body's size, when known.
94    pub fn finish(mut self, status: Option<u16>, response_bytes: Option<u64>) {
95        self.finished = true;
96        record_outbound(
97            self.target,
98            self.route,
99            status,
100            self.started.elapsed(),
101            self.request_bytes,
102            response_bytes,
103        );
104    }
105}
106
107impl Drop for OutboundCall {
108    fn drop(&mut self) {
109        if !self.finished {
110            record_outbound(
111                self.target,
112                self.route,
113                None,
114                self.started.elapsed(),
115                None,
116                None,
117            );
118        }
119    }
120}
121
122/// A status outside 100 to 599 cannot come from a well-formed response.
123fn status_label(status: Option<u16>) -> String {
124    match status {
125        Some(code @ 100..=599) => code.to_string(),
126        Some(_) => String::from("other"),
127        None => String::from("error"),
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use std::time::Duration;
134
135    use super::{OutboundCall, record_outbound, status_label};
136    use crate::webserver::telemetry::handle;
137
138    #[test]
139    fn a_status_outside_the_http_range_cannot_grow_the_series_count() {
140        assert_eq!("204", status_label(Some(204)));
141        assert_eq!("other", status_label(Some(999)));
142        assert_eq!("other", status_label(Some(0)));
143        assert_eq!("error", status_label(None));
144    }
145
146    #[test]
147    fn an_outbound_call_records_duration_and_both_sizes_under_its_labels() {
148        let _ = handle();
149        record_outbound(
150            "unit_target",
151            "/v1/things/{id}",
152            Some(200),
153            Duration::from_millis(30),
154            Some(300),
155            Some(5000),
156        );
157
158        let rendered: String = handle().render();
159        let labels: &str = r#"target="unit_target",route="/v1/things/{id}",status="200""#;
160        for series in [
161            "http_client_request_duration_seconds_count",
162            "http_client_request_body_size_bytes_count",
163            "http_client_response_body_size_bytes_count",
164        ] {
165            let line: String = format!("{series}{{{labels}}} 1");
166            assert!(rendered.contains(&line), "{line} missing: {rendered}");
167        }
168        let sum: String = format!("http_client_request_body_size_bytes_sum{{{labels}}} 300");
169        assert!(rendered.contains(&sum), "{rendered}");
170        let bucket: String =
171            format!("http_client_response_body_size_bytes_bucket{{{labels},le=\"16384\"}} 1");
172        assert!(rendered.contains(&bucket), "{rendered}");
173    }
174
175    #[test]
176    fn a_failed_call_without_sizes_records_only_the_duration_as_error() {
177        let _ = handle();
178        OutboundCall::start("unit_down", "/ping").finish(None, None);
179
180        let rendered: String = handle().render();
181        assert!(
182            rendered.contains(
183                r#"http_client_request_duration_seconds_count{target="unit_down",route="/ping",status="error"} 1"#
184            ),
185            "{rendered}"
186        );
187        assert!(
188            !rendered.contains(r#"body_size_bytes_count{target="unit_down""#),
189            "unknown sizes record nothing"
190        );
191    }
192
193    #[test]
194    fn a_call_dropped_without_finish_records_one_error() {
195        let _ = handle();
196        {
197            let _call: OutboundCall =
198                OutboundCall::start("unit_dropped", "/early").request_bytes(10);
199        }
200        OutboundCall::start("unit_finished", "/once").finish(Some(200), None);
201
202        let rendered: String = handle().render();
203        assert!(
204            rendered.contains(
205                r#"http_client_request_duration_seconds_count{target="unit_dropped",route="/early",status="error"} 1"#
206            ),
207            "{rendered}"
208        );
209        assert!(
210            !rendered.contains(r#"body_size_bytes_count{target="unit_dropped""#),
211            "a dropped call records no sizes"
212        );
213        assert!(
214            rendered.contains(
215                r#"http_client_request_duration_seconds_count{target="unit_finished",route="/once",status="200"} 1"#
216            ),
217            "{rendered}"
218        );
219        assert!(
220            !rendered.contains(r#"target="unit_finished",route="/once",status="error""#),
221            "finish must not also record on drop"
222        );
223    }
224}