//! Bounded HTTP serving and operating-system shutdown signals. use std::{ future::{Future, pending}, io, net::SocketAddr, time::Duration, }; use axum::Router; use axum_server::Handle; use tokio::net::TcpListener; use crate::{AppState, IdentityRevalidation, config::DeploymentMode, error::Result}; const DRAIN_TIMEOUT: Duration = Duration::from_secs(30); /// Serve requests until shutdown, drain bounded work, then checkpoint `SQLite`. /// /// # Errors /// /// Returns an error when serving or the final checkpoint fails. pub async fn serve( listener: TcpListener, state: AppState, shutdown: impl Future + Send + 'static, ) -> Result<()> { let checkpoint = state.repository.clone(); let collector = state.repository.clone(); let shutdown_state = state.clone(); let orphan_ttl = state.config.blob_orphan_ttl; let gc_interval = state.config.blob_gc_interval; let identity_interval = state.config.identity_revalidation_interval; let maintenance = tokio::spawn(async move { loop { tokio::time::sleep(gc_interval).await; match collector.collect_orphan_blobs(orphan_ttl).await { Ok(0) => {} Ok(count) => tracing::info!(count, "deleted orphaned blobs"), Err(error) => tracing::error!(%error, "orphaned blob deletion failed"), } match collector.collect_repository_blocks().await { Ok(0) => {} Ok(count) => tracing::info!(count, "deleted unreferenced repository blocks"), Err(error) => tracing::error!(%error, "repository block deletion failed"), } } }); let identity_maintenance = (state.config.deployment_mode == DeploymentMode::Production).then(|| { let state = state.clone(); tokio::spawn(async move { loop { tokio::time::sleep(identity_interval).await; match state.revalidate_network_identity().await { Ok(IdentityRevalidation::Unchanged) => {} Ok(IdentityRevalidation::Invalidated) => { tracing::warn!("hosted handle became invalid"); } Ok(IdentityRevalidation::Recovered) => { tracing::info!("hosted handle recovered"); } Err(error) => { tracing::warn!(%error, "hosted handle revalidation was inconclusive"); } } } }) }); let shutdown = async move { shutdown.await; shutdown_state.stream_shutdown.send_replace(true); }; let server_result = serve_router(listener, super::router(state), shutdown, DRAIN_TIMEOUT).await; maintenance.abort(); if let Some(identity_maintenance) = identity_maintenance { identity_maintenance.abort(); } let checkpoint_result = checkpoint.checkpoint(); server_result?; checkpoint_result } async fn serve_router( listener: TcpListener, router: Router, shutdown: impl Future + Send + 'static, drain_timeout: Duration, ) -> io::Result<()> { let listener = listener.into_std()?; let handle: Handle = Handle::new(); let shutdown_handle = handle.clone(); let shutdown_task = tokio::spawn(async move { shutdown.await; shutdown_handle.graceful_shutdown(Some(drain_timeout)); }); let result = axum_server::from_tcp(listener)? .handle(handle) .serve(router.into_make_service_with_connect_info::()) .await; shutdown_task.abort(); result } /// Wait for Ctrl-C or, on Unix, SIGTERM. pub async fn shutdown_signal() { let ctrl_c = async { if let Err(error) = tokio::signal::ctrl_c().await { tracing::error!(%error, "could not install Ctrl-C handler"); pending::<()>().await; } "Ctrl-C" }; #[cfg(unix)] let terminate = async { match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { Ok(mut signal) => { signal.recv().await; "SIGTERM" } Err(error) => { tracing::error!(%error, "could not install SIGTERM handler"); pending::<&str>().await } } }; #[cfg(not(unix))] let terminate = pending::<&str>(); let signal = tokio::select! { signal = ctrl_c => signal, signal = terminate => signal, }; tracing::info!(signal, "shutdown signal received; draining requests"); } #[cfg(test)] mod tests { use std::{ sync::Arc, time::{Duration, Instant}, }; use axum::{Router, extract::State, routing::get}; use tokio::{ net::{TcpListener, TcpStream}, sync::{Notify, oneshot}, time::timeout, }; use super::serve_router; #[derive(Clone)] struct Gate { entered: Arc, release: Arc, } #[tokio::test] async fn graceful_shutdown_drains_an_in_flight_response() { let gate = Gate::new(); let (address, server, shutdown) = server(&gate, Duration::from_secs(5)).await; let request = tokio::spawn(reqwest::get(format!("http://{address}/slow"))); gate.entered.notified().await; shutdown.send(()).unwrap(); wait_until_admission_stops(address).await; gate.release.notify_one(); assert!(request.await.unwrap().unwrap().status().is_success()); server.await.unwrap().unwrap(); } #[tokio::test] async fn graceful_shutdown_force_closes_after_the_drain_bound() { let gate = Gate::new(); let drain_timeout = Duration::from_millis(20); let (address, server, shutdown) = server(&gate, drain_timeout).await; let request = tokio::spawn(reqwest::get(format!("http://{address}/slow"))); gate.entered.notified().await; let started = Instant::now(); shutdown.send(()).unwrap(); timeout(Duration::from_secs(1), server) .await .unwrap() .unwrap() .unwrap(); assert!(started.elapsed() >= drain_timeout); assert!( timeout(Duration::from_secs(1), request) .await .unwrap() .unwrap() .is_err() ); } impl Gate { fn new() -> Self { Self { entered: Arc::new(Notify::new()), release: Arc::new(Notify::new()), } } } async fn wait_until_admission_stops(address: std::net::SocketAddr) { let deadline = Instant::now() + Duration::from_secs(1); loop { if TcpStream::connect(address).await.is_err() { return; } assert!( Instant::now() < deadline, "server continued accepting after shutdown" ); tokio::time::sleep(Duration::from_millis(1)).await; } } async fn server( gate: &Gate, drain_timeout: Duration, ) -> ( std::net::SocketAddr, tokio::task::JoinHandle>, oneshot::Sender<()>, ) { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let (shutdown, receiver) = oneshot::channel(); let router = Router::new() .route( "/slow", get(|State(gate): State| async move { gate.entered.notify_one(); gate.release.notified().await; }), ) .with_state(gate.clone()); let server = tokio::spawn(serve_router( listener, router, async move { let _ = receiver.await; }, drain_timeout, )); (address, server, shutdown) } }