Skip to main content

webserver_base/webserver/
overload.rs

1//! A deliberate "too busy" reply, which the trace layer must not report as a fault.
2//!
3//! The trace layer files every 5xx as a failed response at `error`, and
4//! `error` reaches Sentry. An app that sheds load on purpose (a full queue, a
5//! busy dependency) would turn each shed request into a Sentry event, a flood
6//! exactly when the app is busiest. Marking the response keeps it out.
7
8use std::time::Duration;
9
10use axum::http::{HeaderValue, StatusCode, header};
11use axum::response::{IntoResponse, Response};
12
13/// Response extension: this 5xx is a deliberate overload or unavailable reply,
14/// not a fault. The trace layer treats the response as a success: no
15/// `response failed` error and no Sentry event. The request is still logged at
16/// `info` with its status and counted in `http_requests_total` under that
17/// status, so shedding stays visible in logs and metrics.
18///
19/// Insert it with `response.extensions_mut().insert(DeliberateOverload)`, or
20/// build the whole reply with [`overloaded`].
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct DeliberateOverload;
23
24/// A `503 Service Unavailable` with a `Retry-After` of `retry_after` (rounded
25/// up to whole seconds, at least one), marked [`DeliberateOverload`].
26#[must_use]
27pub fn overloaded(retry_after: Duration) -> Response {
28    let seconds: u64 = retry_after
29        .as_secs()
30        .saturating_add(u64::from(retry_after.subsec_nanos() > 0))
31        .max(1);
32    let mut response: Response = StatusCode::SERVICE_UNAVAILABLE.into_response();
33    response
34        .headers_mut()
35        .insert(header::RETRY_AFTER, HeaderValue::from(seconds));
36    response.extensions_mut().insert(DeliberateOverload);
37    response
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    #[test]
45    fn a_reply_is_a_503_with_a_retry_after_and_the_marker() {
46        let response: Response = overloaded(Duration::from_millis(1500));
47        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
48        assert_eq!(response.headers()[header::RETRY_AFTER], "2");
49        assert!(response.extensions().get::<DeliberateOverload>().is_some());
50    }
51
52    #[test]
53    fn the_retry_after_is_at_least_one_second() {
54        let response: Response = overloaded(Duration::ZERO);
55        assert_eq!(response.headers()[header::RETRY_AFTER], "1");
56    }
57}