use super::drive;
use crate::{AppConfig, lifecycle::Shared, web::HttpState};
use axum::{
Router,
extract::Request,
routing::{get, post},
};
use http_body_util::BodyExt;
use std::{sync::Arc, time::Duration};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt, duplex},
sync::Notify,
time::{Instant, advance, timeout},
};
#[tokio::test(start_paused = true)]
async fn backpressured_normal_size_and_timeout_responses_obey_selected_deadline() {
for (path, length, cutoff_ms, terminal) in [
("/", 0, 1000, "completed"),
("/", 1025, 1000, "failed"),
("/hang", 0, 1250, "timed_out"),
] {
let shared = Shared::new("backpressure".into());
shared.begin_running();
let config = AppConfig {
request_timeout: Duration::from_secs(1),
body_idle_timeout: Duration::from_secs(10),
request_body_limit: 1024,
max_in_flight: 1,
..AppConfig::default()
};
let router = Router::new()
.route("/", get(|| async { "hello" }))
.route("/hang", get(std::future::pending::<&'static str>));
let state = Arc::new(HttpState::new(router, shared.clone(), &config));
let (mut client, server) = duplex(1);
let connection = tokio::spawn(drive(server, "127.0.0.1:1".parse().unwrap(), state));
let started = Instant::now();
client.write_all(format!("GET {path} HTTP/1.1\r\nHost: test\r\nContent-Length: {length}\r\nConnection: close\r\n\r\n").as_bytes()).await.unwrap();
let mut byte = [0];
client.read_exact(&mut byte).await.unwrap();
assert_eq!(byte[0], b'H');
let cutoff = started + Duration::from_millis(cutoff_ms);
advance(cutoff - Instant::now() - Duration::from_millis(1)).await;
tokio::task::yield_now().await;
assert!(
!connection.is_finished(),
"must retain transport until the selected cutoff"
);
advance(Duration::from_millis(1)).await;
connection.await.unwrap().unwrap();
assert_eq!(Instant::now(), cutoff);
let metrics = shared.metrics.render();
assert!(
metrics.contains("servlet_exchanges_active 0\n"),
"{metrics}"
);
assert!(
metrics.contains("servlet_exchanges_finished_total 1\n"),
"{metrics}"
);
assert!(
metrics.contains(&format!(
"servlet_exchanges_outcomes_total{{outcome=\"{terminal}\"}} 1\n"
)),
"{metrics}"
);
assert!(
metrics.contains("servlet_transport_errors_total 1\n"),
"{metrics}"
);
}
}
#[tokio::test(start_paused = true)]
async fn buffered_response_timeout_does_not_mark_a_later_handler_timed_out() {
let shared = Shared::new("pipelined".into());
shared.begin_running();
let config = AppConfig {
request_timeout: Duration::from_millis(250),
body_idle_timeout: Duration::from_secs(10),
..AppConfig::default()
};
let entered = Arc::new(Notify::new());
let next = entered.clone();
let router = Router::new()
.route(
"/first",
post(|request: Request| async move {
tokio::spawn(async move {
request.into_body().collect().await.unwrap();
});
"first response"
}),
)
.route(
"/second",
get(move || async move {
next.notify_one();
std::future::pending::<&'static str>().await
}),
);
let state = Arc::new(HttpState::new(router, shared.clone(), &config));
let (mut client, server) = duplex(1);
let connection = tokio::spawn(drive(server, "127.0.0.1:1".parse().unwrap(), state));
let started = Instant::now();
client
.write_all(b"POST /first HTTP/1.1\r\nHost: test\r\nContent-Length: 1\r\n\r\n")
.await
.unwrap();
let mut byte = [0];
client.read_exact(&mut byte).await.unwrap();
assert_eq!(byte[0], b'H');
advance(Duration::from_millis(100)).await;
client
.write_all(b"xGET /second HTTP/1.1\r\nHost: test\r\n\r\n")
.await
.unwrap();
timeout(Duration::from_millis(100), entered.notified())
.await
.expect("second handler must start while the first response is blocked");
advance(Duration::from_millis(150)).await;
connection.await.unwrap().unwrap();
assert_eq!(Instant::now(), started + config.request_timeout);
let metrics = shared.metrics.render();
for (outcome, count) in [("completed", 1), ("cancelled", 1), ("timed_out", 0)] {
assert!(
metrics.contains(&format!(
"servlet_exchanges_outcomes_total{{outcome=\"{outcome}\"}} {count}\n"
)),
"{metrics}"
);
}
assert!(
metrics.contains("servlet_transport_errors_total 1\n"),
"{metrics}"
);
}