#![cfg(feature = "http-stack")]
use std::{
convert::Infallible,
future::Future,
mem::DropGuard,
pin::Pin,
sync::{
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
task::{Context, Poll},
time::Duration,
};
use axum::{
Router,
body::{Body, Bytes, to_bytes},
http::{Request, StatusCode, header::CONTENT_TYPE},
routing::{get, post},
};
use footing::http::{
HttpMiddlewareSettings, HttpMiddlewareStack, ProblemDetails, REQUEST_ID_HEADER_NAME,
RequestContext, RequestId, TraceParent, error::PROBLEM_JSON_MEDIA_TYPE,
};
use http_body::Frame;
use tokio::time::Sleep;
use tower::ServiceExt;
const TIMEOUT: Duration = Duration::from_secs(5);
const TRACEPARENT: &str = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
const TRACE_ID: &str = "4bf92f3577b34da6a3ce929d0e0e4736";
fn settings() -> HttpMiddlewareSettings {
HttpMiddlewareSettings::default()
.with_timeout(Some(TIMEOUT))
.with_trace(false)
.with_compression(false)
}
fn apply(settings: HttpMiddlewareSettings, router: Router) -> Router {
HttpMiddlewareStack::builder(settings.build().unwrap())
.build()
.unwrap()
.apply(router)
}
async fn never_responds() -> &'static str {
std::future::pending().await
}
async fn problem(response: axum::response::Response) -> ProblemDetails {
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(response.headers()[CONTENT_TYPE], PROBLEM_JSON_MEDIA_TYPE);
let body = to_bytes(response.into_body(), 4096).await.unwrap();
let problem: ProblemDetails = serde_json::from_slice(&body).unwrap();
assert_eq!(problem.status(), 503);
assert_eq!(problem.code(), "response_timeout");
assert_eq!(problem.title(), "Service Unavailable");
problem
}
#[tokio::test(start_paused = true)]
async fn timeout_problem_reuses_context_and_outer_response_headers() {
let app = apply(settings(), Router::new().route("/", get(never_responds)));
let mut request = Request::get("/")
.header(REQUEST_ID_HEADER_NAME, "ignored-header-id")
.body(Body::empty())
.unwrap();
request.extensions_mut().insert(
RequestContext::new(RequestId::new("installed-context-id").unwrap())
.with_traceparent(TraceParent::new(TRACEPARENT).unwrap()),
);
let response = app.oneshot(request).await.unwrap();
assert_eq!(
response.headers()[REQUEST_ID_HEADER_NAME],
"installed-context-id"
);
assert_eq!(response.headers()["x-content-type-options"], "nosniff");
let problem = problem(response).await;
assert_eq!(problem.request_id(), Some("installed-context-id"));
assert_eq!(problem.trace_id(), Some(TRACE_ID));
}
#[tokio::test(start_paused = true)]
async fn timeout_problem_uses_the_context_created_by_the_stack() {
let app = apply(settings(), Router::new().route("/", get(never_responds)));
let response = app
.oneshot(
Request::get("/")
.header("traceparent", TRACEPARENT)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let request_id = response.headers()[REQUEST_ID_HEADER_NAME]
.to_str()
.unwrap()
.to_owned();
let problem = problem(response).await;
assert_eq!(problem.request_id(), Some(request_id.as_str()));
assert_eq!(problem.trace_id(), Some(TRACE_ID));
}
#[tokio::test(start_paused = true)]
async fn disabling_context_does_not_synthesize_identifiers_but_preserves_existing_context() {
let app = apply(
settings().with_request_context(false),
Router::new().route("/", get(never_responds)),
);
for existing_context in [false, true] {
let mut request = Request::get("/")
.header(REQUEST_ID_HEADER_NAME, "unprocessed-header-id")
.header("traceparent", TRACEPARENT)
.body(Body::empty())
.unwrap();
if existing_context {
request.extensions_mut().insert(
RequestContext::new(RequestId::new("existing-context-id").unwrap())
.with_traceparent(TraceParent::new(TRACEPARENT).unwrap()),
);
}
let response = app.clone().oneshot(request).await.unwrap();
assert!(!response.headers().contains_key(REQUEST_ID_HEADER_NAME));
let problem = problem(response).await;
assert_eq!(
problem.request_id(),
existing_context.then_some("existing-context-id")
);
assert_eq!(problem.trace_id(), existing_context.then_some(TRACE_ID));
}
}
#[tokio::test(start_paused = true)]
async fn elapsed_deadline_wins_and_drops_the_in_flight_handler() {
let cancelled = Arc::new(AtomicBool::new(false));
let handler_cancelled = cancelled.clone();
let app = apply(
settings(),
Router::new().route(
"/",
get(move || {
let guard = DropGuard::new(handler_cancelled.clone(), |cancelled| {
cancelled.store(true, Ordering::SeqCst);
});
async move {
tokio::time::sleep(TIMEOUT).await;
drop(guard);
"completed at the deadline"
}
}),
),
);
let response = app.oneshot(Request::new(Body::empty())).await.unwrap();
assert!(cancelled.load(Ordering::SeqCst));
problem(response).await;
}
#[tokio::test(start_paused = true)]
async fn handler_responses_are_not_rewritten_based_on_their_status() {
let app = apply(
settings(),
Router::new().route(
"/",
get(|| async { (StatusCode::REQUEST_TIMEOUT, "application response") }),
),
);
let response = app.oneshot(Request::new(Body::empty())).await.unwrap();
assert_eq!(response.status(), StatusCode::REQUEST_TIMEOUT);
assert_eq!(
response.headers()[CONTENT_TYPE],
"text/plain; charset=utf-8"
);
assert_eq!(
to_bytes(response.into_body(), 1024).await.unwrap(),
"application response"
);
}
struct DelayedBody {
delay: Pin<Box<Sleep>>,
polls: Arc<AtomicUsize>,
sent: bool,
}
impl DelayedBody {
fn new(polls: Arc<AtomicUsize>) -> Self {
Self {
delay: Box::pin(tokio::time::sleep(TIMEOUT * 2)),
polls,
sent: false,
}
}
}
impl http_body::Body for DelayedBody {
type Data = Bytes;
type Error = Infallible;
fn poll_frame(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
if self.sent {
return Poll::Ready(None);
}
self.polls.fetch_add(1, Ordering::SeqCst);
std::task::ready!(self.delay.as_mut().poll(cx));
self.sent = true;
Poll::Ready(Some(Ok(Frame::data(Bytes::from_static(b"delayed body")))))
}
}
#[tokio::test(start_paused = true)]
async fn response_bodies_are_neither_buffered_nor_limited_by_the_response_deadline() {
let polls = Arc::new(AtomicUsize::new(0));
let handler_polls = polls.clone();
let app = apply(
settings(),
Router::new().route(
"/",
get(move || {
let polls = handler_polls.clone();
async move { Body::new(DelayedBody::new(polls)) }
}),
),
);
let response = app.oneshot(Request::new(Body::empty())).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(polls.load(Ordering::SeqCst), 0);
assert_eq!(
to_bytes(response.into_body(), 1024).await.unwrap(),
"delayed body"
);
}
#[tokio::test(start_paused = true)]
async fn reading_the_request_body_remains_inside_the_response_deadline() {
let app = apply(
settings(),
Router::new().route(
"/",
post(|body: Body| async move {
to_bytes(body, 1024).await.unwrap();
"received"
}),
),
);
let polls = Arc::new(AtomicUsize::new(0));
let request = Request::post("/")
.body(Body::new(DelayedBody::new(polls.clone())))
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert!(polls.load(Ordering::SeqCst) > 0);
problem(response).await;
}