use std::io;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use axum::Router;
use axum::serve::{Listener as _, ListenerExt as _};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use crate::info_source::InfoSource;
use crate::snapshot::Snapshot;
use crate::telemetry::Telemetry;
pub(crate) struct Listener {
address: SocketAddr,
shutdown: CancellationToken,
task: JoinHandle<()>,
}
pub(crate) type SnapshotSource = Arc<dyn Fn() -> Snapshot + Send + Sync>;
#[derive(Clone)]
pub(crate) struct Routes {
pub(crate) snapshot: SnapshotSource,
pub(crate) telemetry: Arc<Telemetry>,
pub(crate) info: Arc<InfoSource>,
}
impl axum::extract::FromRef<Routes> for SnapshotSource {
fn from_ref(routes: &Routes) -> Self {
routes.snapshot.clone()
}
}
impl Listener {
pub(crate) async fn bind(
host: &str,
port: u16,
router: Router,
what: &'static str,
) -> Result<Self, io::Error> {
let address = resolve(host, port).await?;
let listener = tokio::net::TcpListener::bind(address).await?;
let listener = listener.tap_io(|stream| {
if let Err(error) = stream.set_nodelay(true) {
tracing::debug!(%error, "cannot enable TCP_NODELAY on an accepted connection");
}
});
let address = listener.local_addr()?;
let shutdown = CancellationToken::new();
let stopped = shutdown.clone();
let task = tokio::spawn(async move {
let stopped = async move { stopped.cancelled_owned().await };
let make = router.into_make_service_with_connect_info::<SocketAddr>();
let serving = axum::serve(listener, make).with_graceful_shutdown(stopped);
if let Err(error) = serving.await {
tracing::error!(%error, listener = what, "the listener stopped with an error");
}
});
tracing::info!(%address, listener = what, "the listener is up");
Ok(Self {
address,
shutdown,
task,
})
}
pub(crate) fn address(&self) -> SocketAddr {
self.address
}
pub(crate) async fn shutdown(self) {
self.shutdown.cancel();
let _ = self.task.await;
}
}
async fn resolve(host: &str, port: u16) -> io::Result<SocketAddr> {
if let Ok(ip) = host.parse::<IpAddr>() {
return Ok(SocketAddr::new(ip, port));
}
let mut addresses = tokio::net::lookup_host((host, port)).await?;
addresses.next().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("host '{host}' is not resolved"),
)
})
}