use std::pin::Pin;
use std::sync::{Arc, OnceLock};
use std::task::{self, Poll};
use std::time::Instant;
use axum::body::{Body, Bytes};
use axum::extract::DefaultBodyLimit;
use axum::middleware::Next;
use axum::response::Html;
use axum::response::{IntoResponse, Response};
use http::{HeaderValue, Method, StatusCode, header};
use http_body::{Body as HttpBody, Frame, SizeHint};
use tracing::{Instrument, Span};
use super::telemetry::REQUEST_TARGET;
use crate::context::{App, Context, InContext, Internals, RequestState};
use crate::errors::{Handled, ResponseBoundary};
use crate::http::RequestId;
use crate::http::middleware::TrustProxies;
use crate::http::request::origin;
use crate::http::request_id;
use crate::session::Flash;
pub(super) struct Kernel {
pub(super) app: Arc<App>,
pub(super) proxies: TrustProxies,
pub(super) health: Option<String>,
}
pub(super) fn wrap(router: axum::Router, kernel: Kernel, boundary: ResponseBoundary) -> axum::Router {
let kernel = Arc::new(kernel);
let app = Arc::clone(&kernel.app);
router
.layer(axum::middleware::from_fn(
move |request: axum::extract::Request, next: Next| with_services(request, next, Arc::clone(&app)),
))
.layer(DefaultBodyLimit::disable())
.layer(boundary)
.layer(axum::middleware::from_fn(
move |request: axum::extract::Request, next: Next| handle(request, next, Arc::clone(&kernel)),
))
}
async fn with_services(mut request: axum::extract::Request, next: Next, app: Arc<App>) -> Response {
match app.part::<super::Boot>().run().await {
Ok(()) => {
request.extensions_mut().insert(app.services.clone());
next.run(request).await
}
Err(error) => error.into_response(),
}
}
async fn handle(mut request: axum::extract::Request, next: Next, kernel: Arc<Kernel>) -> Response {
kernel.proxies.apply(&mut request);
trim_trailing_slashes(&mut request, &kernel.app.config).await;
request.extensions_mut().insert(Arc::clone(&kernel.app.config));
request.extensions_mut().insert(kernel.app.encrypter.clone());
request.extensions_mut().insert(crate::auth::AuthCache::default());
let started = Instant::now();
let method = request.method().clone();
let path = request.uri().path().to_owned();
let id = RequestId::of(request.headers());
request.extensions_mut().insert(id.clone());
let origin = origin(request.headers(), request.uri());
let is_health_check =
(method == Method::GET || method == Method::HEAD) && kernel.health.as_deref() == Some(path.as_str());
let is_reload_stream = kernel.app.config.app.debug && method == Method::GET && path == crate::view::reload::PATH;
let span = if is_health_check || is_reload_stream {
Span::none()
} else {
request_span(&mut request, &id, &origin)
};
if let Some(RecordRoot(recorded)) = request.extensions().get::<RecordRoot>() {
let _ = recorded.set(origin.clone());
}
let context = Context::new(Arc::clone(&kernel.app), Some(RequestState::new(&request, origin)));
let mut line = RequestLine {
context: context.clone(),
span: span.clone(),
method,
path,
started,
quiet: is_health_check || is_reload_stream || !kernel.app.config.app.env.is_local(),
status: CLIENT_CLOSED_REQUEST,
};
let response = if is_health_check {
Some(health(&kernel.app).instrument(span.clone()).await)
} else if is_reload_stream {
Some(crate::view::reload::stream(&context))
} else {
let cut_off = context.cutting_off();
let handled = context.clone().scope(next.run(request)).instrument(span.clone());
tokio::select! {
biased;
() = cut_off => None,
response = handled => Some(response),
}
};
let mut response = match response {
Some(response) => response.map(|body| InContext::wrap(body, context.clone(), span.clone())),
None => (
StatusCode::SERVICE_UNAVAILABLE,
[(header::CONNECTION, "close")],
"The server stopped before the request finished.",
)
.into_response(),
};
if let Ok(value) = HeaderValue::try_from(id.as_str()) {
response.headers_mut().entry(request_id::HEADER).or_insert(value);
}
let _entered = span.enter();
if response.extensions_mut().remove::<Flash>().is_some() {
tracing::warn!(
target: REQUEST_TARGET,
"data flashed with a redirect was dropped, since the route has no session; \
flash data needs the `web` middleware group"
);
}
let status = response.status().as_u16();
span.record("http.response.status_code", i64::from(status));
if response.status().is_server_error() {
match response.extensions().get::<Handled>() {
Some(handled) => super::telemetry::fail(&span, &*handled.error),
None => super::telemetry::fail(&span, &super::telemetry::Summary::server_status(response.status())),
}
}
if matches!(status, 100..=199 | 204 | 304) {
line.status = status;
}
response.map(|body| Body::new(Logged { body, line, status }))
}
fn request_span(request: &mut axum::extract::Request, id: &RequestId, origin: &str) -> Span {
let method = request.method();
let path = request.uri().path();
let otel_method = super::telemetry::http_method(method.as_str());
let span = tracing::info_span!(
target: REQUEST_TARGET,
"request",
id = %id,
method = %method,
path = %path,
route = tracing::field::Empty,
otel.name = otel_method.name,
otel.kind = "server",
otel.status_code = tracing::field::Empty,
http.request.method = otel_method.attribute,
http.request.method_original = otel_method.original,
http.route = tracing::field::Empty,
http.response.status_code = tracing::field::Empty,
url.path = %path,
url.scheme = origin.split_once("://").map(|(scheme, _)| scheme),
);
#[cfg(feature = "opentelemetry")]
super::telemetry::continue_trace(&span, request.headers());
request
.extensions_mut()
.insert(super::telemetry::RequestSpan(span.clone()));
span
}
const CLIENT_CLOSED_REQUEST: u16 = 499;
struct RequestLine {
context: Context,
span: Span,
method: Method,
path: String,
started: Instant,
quiet: bool,
status: u16,
}
impl Drop for RequestLine {
fn drop(&mut self) {
let Self {
method, path, status, ..
} = self;
let elapsed = self.started.elapsed();
let duration_ms = crate::foundation::telemetry::duration_ms(elapsed);
let elapsed = crate::console::theme::elapsed(elapsed);
let _entered = self.span.enter();
self.context.clone().sync_scope(|| {
if self.quiet {
tracing::debug!(target: REQUEST_TARGET, status, duration_ms, "{method} {path} {status} {elapsed}");
} else {
tracing::info!(target: REQUEST_TARGET, status, duration_ms, "{method} {path} {status} {elapsed}");
}
});
drop(_entered);
super::telemetry::end_now(&self.span);
}
}
struct Logged {
body: Body,
line: RequestLine,
status: u16,
}
impl HttpBody for Logged {
type Data = Bytes;
type Error = axum::Error;
fn poll_frame(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Result<Frame<Bytes>, axum::Error>>> {
let this = self.get_mut();
let polled = Pin::new(&mut this.body).poll_frame(cx);
if matches!(polled, Poll::Ready(None | Some(Err(_)))) {
this.line.status = this.status;
}
polled
}
fn is_end_stream(&self) -> bool {
self.body.is_end_stream()
}
fn size_hint(&self) -> SizeHint {
self.body.size_hint()
}
}
impl Drop for Logged {
fn drop(&mut self) {
if self.body.is_end_stream() {
self.line.status = self.status;
}
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct RecordRoot(pub(crate) Arc<OnceLock<String>>);
async fn trim_trailing_slashes(request: &mut axum::extract::Request, config: &crate::config::Config) {
let path = request.uri().path();
if path.len() <= 1 || !path.ends_with('/') {
return;
}
let trimmed = path.trim_end_matches('/');
let trimmed = if trimmed.is_empty() { "/" } else { trimmed };
let decoded = percent_encoding::percent_decode_str(path).decode_utf8_lossy();
let in_public = config.app.public_path(decoded.trim_start_matches('/'));
if !decoded.contains("..")
&& tokio::fs::metadata(&in_public)
.await
.is_ok_and(|metadata| metadata.is_dir())
{
return;
}
let path_and_query = request
.uri()
.query()
.map_or_else(|| trimmed.to_owned(), |query| format!("{trimmed}?{query}"));
let mut parts = request.uri().clone().into_parts();
if let Ok(path_and_query) = path_and_query.parse() {
parts.path_and_query = Some(path_and_query);
if let Ok(uri) = http::Uri::from_parts(parts) {
*request.uri_mut() = uri;
}
}
}
async fn health(app: &App) -> Response {
match app.part::<super::Boot>().run().await {
Ok(()) => Html(HEALTHY).into_response(),
Err(error) => {
crate::foundation::telemetry::logging(
&error,
|| tracing::error!(target: REQUEST_TARGET, %error, "the health check failed: the application can't boot"),
);
(StatusCode::SERVICE_UNAVAILABLE, Html(UNHEALTHY)).into_response()
}
}
}
const HEALTHY: &str = r#"<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Application up</title>
<style>html{min-height:100%;background:linear-gradient(oklch(84.5% 0.143 164.978),#fff)}</style></head><body></body></html>"#;
const UNHEALTHY: &str = r#"<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Application down</title>
<style>html{min-height:100%;background:linear-gradient(oklch(70.4% 0.191 22.216),#fff)}</style></head><body></body></html>"#;
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Notify;
use std::pin::Pin;
use std::task::{self, Poll};
use axum::body::{Body, Bytes};
use http_body::{Body as HttpBody, Frame, SizeHint};
use crate::Application;
use crate::context::Context;
use crate::routing::Router;
use crate::testing::MakesHttpRequests;
struct Lazy(bool);
impl HttpBody for Lazy {
type Data = Bytes;
type Error = std::convert::Infallible;
fn poll_frame(
self: Pin<&mut Self>,
_cx: &mut task::Context<'_>,
) -> Poll<Option<Result<Frame<Bytes>, Self::Error>>> {
if std::mem::replace(&mut self.get_mut().0, true) {
return Poll::Ready(None);
}
let read_in = if Context::current().is_some() { "ctx" } else { "no!" };
Poll::Ready(Some(Ok(Frame::data(Bytes::from_static(read_in.as_bytes())))))
}
fn size_hint(&self) -> SizeHint {
SizeHint::with_exact(3)
}
}
#[derive(Default)]
struct Gate {
started: Notify,
released: Notify,
}
fn app(gate: &Arc<Gate>) -> Application {
let gate = Arc::clone(gate);
Application::configure()
.replace_env(crate::config::Env::from_iter([("APP_KEY", "")]))
.with_routing(|routing, _| {
routing.api(move |route: &mut Router| {
route.get("/lazy", || async { Body::new(Lazy(false)) });
route.get("/empty", || async { http::StatusCode::NO_CONTENT });
route.get("/held", move || {
let gate = Arc::clone(&gate);
async move {
gate.started.notify_one();
gate.released.notified().await;
"finished"
}
});
route.get("/pending-body", || async {
Body::from_stream(futures_util::stream::pending::<Result<Bytes, std::io::Error>>())
});
route.get("/panicking-body", || async {
let chunks = futures_util::stream::iter([false, true]);
crate::http::Streamed::new(futures_util::StreamExt::map(chunks, |fail| {
assert!(!fail, "the stream broke");
"partial"
}))
});
});
})
.create()
}
fn get(uri: &str) -> http::Request<Body> {
http::Request::get(uri)
.header("host", "localhost")
.body(Body::empty())
.unwrap()
}
#[tokio::test]
async fn bodies_keep_their_length_and_end() {
let router = app(&Arc::default()).into_router();
let lazy = tower::ServiceExt::oneshot(router.clone(), get("/api/lazy"))
.await
.unwrap();
assert_eq!(lazy.body().size_hint().exact(), Some(3));
assert!(!lazy.body().is_end_stream());
let empty = tower::ServiceExt::oneshot(router, get("/api/empty")).await.unwrap();
assert!(empty.body().is_end_stream());
}
#[tokio::test]
async fn bodies_of_known_length_are_read_in_the_context() {
app(&Arc::default())
.get("/api/lazy")
.await
.assert_ok()
.assert_see("ctx");
}
#[tokio::test]
async fn a_body_that_panics_is_reported_and_fails() {
let reports = crate::errors::RecordReports::default();
let mut request = get("/api/panicking-body");
request.extensions_mut().insert(reports.clone());
let response = tower::ServiceExt::oneshot(app(&Arc::default()).into_router(), request)
.await
.unwrap();
let body = http_body_util::BodyExt::collect(response.into_body()).await;
assert!(body.is_err(), "the client can tell the response was cut short");
let reports = reports.0.lock().unwrap();
assert_eq!(reports.len(), 1, "{reports:?}");
let message = reports[0].to_string();
assert!(message.starts_with(concat!("panic at ", file!(), ":")), "{message}");
assert!(message.ends_with(": the stream broke"), "{message}");
}
#[tokio::test]
async fn requests_running_when_the_server_begins_to_stop_finish() {
let gate = Arc::default();
let app = app(&gate);
let stop = async {
gate.started.notified().await;
app.begin_shutdown();
gate.released.notify_one();
};
let (response, ()) = tokio::join!(app.get("/api/held"), stop);
response.assert_ok().assert_see("finished");
}
#[tokio::test]
async fn requests_still_running_are_cut_off() {
let gate = Arc::default();
let app = app(&gate);
let cut_off = async {
gate.started.notified().await;
app.cut_off_requests();
};
let handled = tokio::time::timeout(Duration::from_secs(5), app.get("/api/held"));
let (response, ()) = tokio::join!(handled, cut_off);
response
.expect("the request is cut off")
.assert_status(503)
.assert_see("The server stopped before the request finished.");
}
#[tokio::test]
async fn bodies_still_streaming_are_cut_off() {
let app = app(&Arc::default());
let router = app.clone().into_router();
let pending = tower::ServiceExt::oneshot(router.clone(), get("/api/pending-body"))
.await
.unwrap();
let ready = tower::ServiceExt::oneshot(router, get("/api/lazy")).await.unwrap();
app.cut_off_requests();
for response in [pending, ready] {
let body = tokio::time::timeout(
Duration::from_secs(5),
http_body_util::BodyExt::collect(response.into_body()),
)
.await;
assert!(body.expect("the body is cut off").is_err());
}
}
}