use std::sync::Arc;
use std::time::Duration;
use axum::extract::{Request, State};
use axum::http::{HeaderValue, StatusCode};
use axum::middleware::{from_fn_with_state, Next};
use axum::response::{IntoResponse, Response};
use axum::Router;
use tokio::sync::Semaphore;
use crate::problem::{Problem, ProblemResponse};
use crate::request_id::RequestIdExt;
const BACKPRESSURE_RETRY_AFTER: HeaderValue = HeaderValue::from_static("1");
#[derive(Debug, Clone, Default)]
pub struct RouteLimit {
timeout: Option<Duration>,
max_in_flight: Option<usize>,
}
impl RouteLimit {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn timeout(mut self, budget: Duration) -> Self {
self.timeout = Some(budget);
self
}
#[must_use]
pub fn max_in_flight(mut self, max: usize) -> Self {
self.max_in_flight = Some(max.max(1));
self
}
}
#[derive(Clone)]
struct Rule {
prefix: String,
timeout: Option<Duration>,
semaphore: Option<Arc<Semaphore>>,
}
#[derive(Clone, Default)]
pub struct RouteControls {
rules: Vec<Rule>,
}
impl RouteControls {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn route(mut self, prefix: impl Into<String>, limit: RouteLimit) -> Self {
self.rules.push(Rule {
prefix: prefix.into(),
timeout: limit.timeout,
semaphore: limit.max_in_flight.map(|n| Arc::new(Semaphore::new(n))),
});
self.rules
.sort_by_key(|r| std::cmp::Reverse(r.prefix.len()));
self
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
fn match_rule(&self, path: &str) -> Option<&Rule> {
self.rules.iter().find(|r| path.starts_with(&r.prefix))
}
}
pub fn with_route_controls(router: Router, controls: RouteControls) -> Router {
if controls.is_empty() {
return router;
}
router.layer(from_fn_with_state(Arc::new(controls), route_controls))
}
async fn route_controls(
State(controls): State<Arc<RouteControls>>,
request: Request,
next: Next,
) -> Response {
let path = request.uri().path().to_owned();
let Some(rule) = controls.match_rule(&path) else {
return next.run(request).await;
};
let request_id = request.extensions().request_id();
let _permit = match &rule.semaphore {
Some(semaphore) => match Arc::clone(semaphore).try_acquire_owned() {
Ok(permit) => Some(permit),
Err(_) => return overloaded_response(&path, request_id),
},
None => None,
};
match rule.timeout {
Some(budget) => match tokio::time::timeout(budget, next.run(request)).await {
Ok(response) => response,
Err(_) => gateway_timeout_response(&path, request_id),
},
None => next.run(request).await,
}
}
fn overloaded_response(path: &str, request_id: Option<String>) -> Response {
let mut response = ProblemResponse(
Problem::new(StatusCode::SERVICE_UNAVAILABLE, "service overloaded")
.with_detail("the route is at its concurrency limit; retry shortly")
.with_instance(path.to_owned())
.with_request_id_opt(request_id),
)
.into_response();
response
.headers_mut()
.insert("retry-after", BACKPRESSURE_RETRY_AFTER);
response
}
fn gateway_timeout_response(path: &str, request_id: Option<String>) -> Response {
ProblemResponse(
Problem::new(StatusCode::GATEWAY_TIMEOUT, "route timed out")
.with_detail("the route did not complete within its configured timeout")
.with_instance(path.to_owned())
.with_request_id_opt(request_id),
)
.into_response()
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::time::Duration;
use axum::body::Body;
use axum::http::Request as HttpRequest;
use axum::routing::get;
use axum::Router;
use tokio::sync::Notify;
use tower::ServiceExt;
#[tokio::test]
async fn request_over_the_budget_returns_504() {
let app = with_route_controls(
Router::new().route(
"/slow",
get(|| async {
tokio::time::sleep(Duration::from_millis(200)).await;
"done"
}),
),
RouteControls::new()
.route("/slow", RouteLimit::new().timeout(Duration::from_millis(5))),
);
let res = app
.oneshot(HttpRequest::get("/slow").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(res.status(), StatusCode::GATEWAY_TIMEOUT);
}
#[tokio::test]
async fn request_within_the_budget_passes() {
let app = with_route_controls(
Router::new().route("/fast", get(|| async { "done" })),
RouteControls::new().route("/fast", RouteLimit::new().timeout(Duration::from_secs(5))),
);
let res = app
.oneshot(HttpRequest::get("/fast").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test]
async fn unmatched_path_is_not_controlled() {
let app = with_route_controls(
Router::new().route(
"/other",
get(|| async {
tokio::time::sleep(Duration::from_millis(50)).await;
"done"
}),
),
RouteControls::new()
.route("/slow", RouteLimit::new().timeout(Duration::from_millis(1))),
);
let res = app
.oneshot(HttpRequest::get("/other").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test]
async fn concurrency_limit_sheds_overflow_with_503() {
let gate = Arc::new(Notify::new());
let entered = Arc::new(Notify::new());
let app = {
let gate = Arc::clone(&gate);
let entered = Arc::clone(&entered);
with_route_controls(
Router::new().route(
"/held",
get(move || {
let gate = Arc::clone(&gate);
let entered = Arc::clone(&entered);
async move {
entered.notify_one();
gate.notified().await;
"done"
}
}),
),
RouteControls::new().route("/held", RouteLimit::new().max_in_flight(1)),
)
};
let first = {
let app = app.clone();
tokio::spawn(async move {
app.oneshot(HttpRequest::get("/held").body(Body::empty()).unwrap())
.await
.unwrap()
})
};
entered.notified().await;
let second = app
.clone()
.oneshot(HttpRequest::get("/held").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(second.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(
second
.headers()
.get("retry-after")
.map(|v| v.to_str().unwrap()),
Some("1")
);
gate.notify_one();
let first = first.await.unwrap();
assert_eq!(first.status(), StatusCode::OK);
}
}