Something went wrong. Try again.
Chris’s PDS implementation
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255//! 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<Output = ()> + 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<Output = ()> + Send + 'static, drain_timeout: Duration,) -> io::Result<()> { let listener = listener.into_std()?; let handle: Handle<SocketAddr> = 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::<SocketAddr>()) .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<Notify>, release: Arc<Notify>, }
#[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<std::io::Result<()>>, 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<Gate>| 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) }}