use std::net::{IpAddr, SocketAddr};
use std::time::Instant;
use axum::Router;
use axum::extract::Request;
use axum::middleware::{Next, from_fn};
use axum::response::Response;
use axum::routing::get;
use clap::Parser;
use log::{info, warn};
use crate::health::{HealthBody, ServeMeta};
use crate::static_mount::StaticMount;
#[derive(Parser, Debug, Clone)]
pub struct ServeArgs {
#[arg(long, default_value = "127.0.0.1")]
pub host: String,
#[arg(long, short = 'p', default_value_t = 8787)]
pub port: u16,
#[arg(long)]
pub open: bool,
}
impl ServeArgs {
pub fn socket_addr(&self) -> Result<SocketAddr, anyhow::Error> {
let ip: IpAddr = self
.host
.parse()
.map_err(|e| anyhow::anyhow!("invalid --host {:?}: {e}", self.host))?;
Ok(SocketAddr::from((ip, self.port)))
}
}
pub fn serve_router(meta: ServeMeta, api: Router, static_mount: StaticMount) -> Router {
let started = Instant::now();
let kit = Router::new().route(
"/health",
get(move || async move { axum::Json(HealthBody::from_meta(meta, started)) }),
);
static_mount
.apply(kit.merge(api))
.layer(from_fn(log_http_request))
}
async fn log_http_request(req: Request, next: Next) -> Response {
let method = req.method().clone();
let path = req.uri().path().to_owned();
let query = req
.uri()
.query()
.map(|q| format!("?{q}"))
.unwrap_or_default();
let response = next.run(req).await;
info!("{method} {path}{query} -> {}", response.status());
response
}
pub async fn run(
meta: ServeMeta,
args: ServeArgs,
api: Router,
static_mount: StaticMount,
) -> Result<(), anyhow::Error> {
let addr = args.socket_addr()?;
if !addr.ip().is_loopback() {
warn!(
"binding to non-loopback address {addr}; this exposes the API on the network (no auth)"
);
}
let app = serve_router(meta, api, static_mount);
let listener = tokio::net::TcpListener::bind(addr).await?;
let local = listener.local_addr()?;
let url = format!("http://{local}");
info!(
"panza listening on {url} (service={}, version={})",
meta.service, meta.version
);
if args.open {
open_url(&url);
}
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await?;
Ok(())
}
async fn shutdown_signal() {
let _ = tokio::signal::ctrl_c().await;
}
fn open_url(url: &str) {
#[cfg(target_os = "macos")]
{
if let Err(e) = std::process::Command::new("open").arg(url).spawn() {
warn!("failed to open browser: {e}");
}
}
#[cfg(target_os = "linux")]
{
if let Err(e) = std::process::Command::new("xdg-open").arg(url).spawn() {
warn!("failed to open browser: {e}");
}
}
#[cfg(target_os = "windows")]
{
if let Err(e) = std::process::Command::new("cmd")
.args(["/C", "start", url])
.spawn()
{
warn!("failed to open browser: {e}");
}
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
{
warn!("--open is not supported on this platform; open {url} manually");
}
}