Files
pruefwerk/compliance-core/src/shutdown.rs
T
sharang 88495f0c77
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy Dashboard (push) Successful in 5m37s
CI / Deploy Agent (push) Successful in 7m57s
CI / Deploy MCP (push) Successful in 2m42s
test(shutdown): wait for the handler to start instead of 100 ms (#356)
2026-09-23 15:46:48 +00:00

231 lines
8.2 KiB
Rust

//! Graceful shutdown shared by the agent and the MCP server.
//!
//! Orca stops a container with SIGTERM and kills it a few seconds later, so a
//! server has to stop accepting new connections at once, let requests already
//! in flight finish, and give up on anything still open after a bounded grace
//! period (a streaming MCP session or a slow upload never ends by itself).
use std::future::IntoFuture;
use std::time::Duration;
use tokio::sync::watch;
/// How long in-flight requests get after SIGTERM before remaining connections
/// are dropped. Kept under Docker's default 10 s stop timeout (no service sets
/// a longer one) so the process exits on its own instead of being killed.
pub const GRACE_PERIOD: Duration = Duration::from_secs(8);
/// Resolve on SIGTERM (container stop) or Ctrl+C (local run).
///
/// If a handler cannot be installed, that branch never resolves, so the other
/// one still works; the failure is logged rather than ending the process.
pub async fn signal() {
let ctrl_c = async {
if let Err(e) = tokio::signal::ctrl_c().await {
tracing::error!("cannot listen for Ctrl+C: {e}");
std::future::pending::<()>().await;
}
};
#[cfg(unix)]
let terminate = async {
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
Ok(mut sigterm) => {
sigterm.recv().await;
}
Err(e) => {
tracing::error!("cannot listen for SIGTERM: {e}");
std::future::pending::<()>().await;
}
}
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
() = ctrl_c => tracing::info!("Ctrl+C received, shutting down"),
() = terminate => tracing::info!("SIGTERM received, shutting down"),
}
}
/// Fires the shutdown for every [`Shutdown`] handle made from the same
/// [`channel`]. Dropping it fires it too, so a crashed owner never leaves
/// servers running with nobody left to stop them.
#[derive(Debug)]
pub struct ShutdownTrigger(watch::Sender<bool>);
impl ShutdownTrigger {
/// Tell every server and background loop to stop.
pub fn fire(&self) {
// `send_replace` stores the value even with no receiver left, where
// `send` would fail; either way there is nothing to report.
self.0.send_replace(true);
}
}
/// A cloneable "has shutdown started?" handle for servers and loops.
#[derive(Debug, Clone)]
pub struct Shutdown(watch::Receiver<bool>);
impl Shutdown {
/// Resolve once shutdown has been fired (or its trigger dropped).
///
/// Takes `self` by value because axum's `with_graceful_shutdown` wants an
/// owned `'static` future; clone the handle first to wait more than once.
pub async fn wait(mut self) {
// `Err` means the trigger was dropped, which counts as shutdown.
let _ = self.0.wait_for(|stopping| *stopping).await;
}
/// `true` once shutdown has been fired or its trigger dropped.
pub fn is_fired(&self) -> bool {
*self.0.borrow() || self.0.has_changed().is_err()
}
}
/// Create a linked trigger and handle. Clone the handle for each server.
pub fn channel() -> (ShutdownTrigger, Shutdown) {
let (tx, rx) = watch::channel(false);
(ShutdownTrigger(tx), Shutdown(rx))
}
/// Serve `router` until `shutdown` fires, then stop accepting connections and
/// give in-flight requests `grace` to finish before dropping what is left.
///
/// # Errors
///
/// Returns the listener's I/O error if serving fails before shutdown.
pub async fn serve(
listener: tokio::net::TcpListener,
router: axum::Router,
shutdown: Shutdown,
grace: Duration,
) -> std::io::Result<()> {
let server = axum::serve(listener, router).with_graceful_shutdown(shutdown.clone().wait());
let deadline = async move {
shutdown.wait().await;
tokio::time::sleep(grace).await;
};
tokio::select! {
result = server.into_future() => result,
() = deadline => {
tracing::warn!(
grace_secs = grace.as_secs(),
"grace period over, dropping connections still open"
);
Ok(())
}
}
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
use axum::routing::get;
use tokio::sync::oneshot;
/// Bind an ephemeral port and return it with its listener.
async fn listener() -> (tokio::net::TcpListener, std::net::SocketAddr) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind ephemeral port");
let addr = listener.local_addr().expect("local addr");
(listener, addr)
}
#[tokio::test]
async fn dropping_the_trigger_counts_as_shutdown() {
let (trigger, shutdown) = channel();
assert!(!shutdown.is_fired());
drop(trigger);
assert!(shutdown.is_fired());
tokio::time::timeout(Duration::from_secs(1), shutdown.wait())
.await
.expect("wait resolves once the trigger is gone");
}
#[tokio::test]
async fn in_flight_request_finishes_after_shutdown_fires() {
// Arrange: a handler that says when it has started, then blocks until
// the test releases it.
let (started_tx, started_rx) = oneshot::channel::<()>();
let (release_tx, release_rx) = oneshot::channel::<()>();
let handles = std::sync::Arc::new(tokio::sync::Mutex::new(Some((started_tx, release_rx))));
let router = axum::Router::new().route(
"/slow",
get(move || {
let handles = handles.clone();
async move {
if let Some((started, release)) = handles.lock().await.take() {
let _ = started.send(());
let _ = release.await;
}
"done"
}
}),
);
let (listener, addr) = listener().await;
let (trigger, shutdown) = channel();
let server = tokio::spawn(serve(listener, router, shutdown, Duration::from_secs(5)));
// Act: start the request and fire shutdown once the handler is running.
// Waiting a fixed time instead raced a slow runner: a connection
// accepted but not yet read is idle, and graceful shutdown rightly
// closes it, which failed the test without any request being dropped.
let request = tokio::spawn(reqwest::get(format!("http://{addr}/slow")));
tokio::time::timeout(Duration::from_secs(5), started_rx)
.await
.expect("the request reaches the handler")
.expect("handler started");
trigger.fire();
tokio::time::sleep(Duration::from_millis(100)).await;
let _ = release_tx.send(());
// Assert: the request completed and the server then exited on its own.
let body = request
.await
.expect("request task")
.expect("request completes during drain")
.text()
.await
.expect("body");
assert_eq!(body, "done");
tokio::time::timeout(Duration::from_secs(2), server)
.await
.expect("server exits after draining")
.expect("server task")
.expect("serve result");
}
#[tokio::test]
async fn grace_period_bounds_a_request_that_never_ends() {
let router = axum::Router::new().route(
"/hang",
get(|| async {
std::future::pending::<()>().await;
"never"
}),
);
let (listener, addr) = listener().await;
let (trigger, shutdown) = channel();
let server = tokio::spawn(serve(
listener,
router,
shutdown,
Duration::from_millis(200),
));
let _request = tokio::spawn(reqwest::get(format!("http://{addr}/hang")));
tokio::time::sleep(Duration::from_millis(100)).await;
trigger.fire();
tokio::time::timeout(Duration::from_secs(2), server)
.await
.expect("server gives up after the grace period")
.expect("server task")
.expect("serve result");
}
}