use anyhow::{Context, Result};
use axum::Router;
use std::future::Future;
use std::pin::Pin;
use tracing::{info, warn};
pub async fn serve(router: Router, addr: &str) -> Result<()> {
ServerBuilder::new(router).serve(addr).run().await
}
pub struct ServerBuilder {
router: Router,
addr: Option<String>,
shutdown_signal: Option<Pin<Box<dyn Future<Output = ()> + Send>>>,
}
impl ServerBuilder {
pub fn new(router: Router) -> Self {
Self {
router,
addr: None,
shutdown_signal: None,
}
}
pub fn serve(mut self, addr: impl Into<String>) -> Self {
self.addr = Some(addr.into());
self
}
pub fn with_graceful_shutdown_signal(
mut self,
signal: impl Future<Output = ()> + Send + 'static,
) -> Self {
self.shutdown_signal = Some(Box::pin(signal));
self
}
pub fn with_graceful_shutdown(self) -> Self {
self.with_graceful_shutdown_signal(async {
match tokio::signal::ctrl_c().await {
Ok(()) => {
info!("Shutting down gracefully...");
}
Err(e) => {
warn!("Ctrl+C handler unavailable: {e}");
}
}
})
}
pub async fn run(self) -> Result<()> {
let addr = self
.addr
.as_deref()
.context("No listen address set — call .serve(addr) before .run()")?;
let listener = tokio::net::TcpListener::bind(addr)
.await
.with_context(|| format!("Failed to bind to {addr}"))?;
info!("Server running at http://{addr}");
match self.shutdown_signal {
Some(signal) => {
axum::serve(listener, self.router)
.with_graceful_shutdown(signal)
.await
.with_context(|| "Server error")?;
}
None => {
axum::serve(listener, self.router)
.await
.with_context(|| "Server error")?;
}
}
Ok(())
}
}