//! `visa [serve|migrate|seed-demo|help]`: the server and its admin commands. use std::process::ExitCode; use anyhow::{Context, Result, bail, ensure}; use tracing::info; use visa::config::Config; use visa::{dates, db, seed, web}; const USAGE: &str = "\ visa: immigration records, deadlines and extension packs (visa.buildfor.life) Usage: visa [COMMAND] Commands: serve run the web server (default); applies pending migrations first migrate apply pending database migrations and exit seed-demo add invented demo people (local development only) help show this text Settings come from the environment; see src/config.rs or README.md."; #[tokio::main] async fn main() -> ExitCode { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .init(); let cmd = std::env::args().nth(1).unwrap_or_else(|| "serve".into()); match run(&cmd).await { Ok(()) => ExitCode::SUCCESS, Err(e) => { eprintln!("visa: {e:#}"); ExitCode::FAILURE } } } async fn run(cmd: &str) -> Result<()> { match cmd { "serve" => serve().await, "migrate" => { let cfg = Config::from_env()?; let pool = db::connect(&cfg).await?; db::migrate(&pool).await?; println!("migrations applied"); Ok(()) } "seed-demo" => { let cfg = Config::from_env()?; ensure!( !cfg.login_enabled(), "seed-demo writes invented people and runs only in local development \ (VISA_INSECURE_NO_LOGIN=1, no VISA_OIDC_ISSUER)" ); let pool = db::connect(&cfg).await?; db::migrate(&pool).await?; if seed::demo(&pool, dates::today()).await? { println!("demo people added"); } else { println!("demo people are there already"); } Ok(()) } "help" | "--help" | "-h" => { println!("{USAGE}"); Ok(()) } other => bail!("unknown command {other:?}; `visa help` lists the commands"), } } async fn serve() -> Result<()> { let cfg = Config::from_env()?; let pool = db::connect(&cfg).await?; db::migrate(&pool).await?; let listen = cfg.listen; let login = cfg.login_enabled(); let st = web::AppState::new(cfg, pool)?; web::spawn_background(st.clone()); let app = web::router(st); let listener = tokio::net::TcpListener::bind(listen) .await .with_context(|| format!("cannot listen on {listen}"))?; if !login { info!("no login: VISA_INSECURE_NO_LOGIN is set (loopback only)"); } info!("listening on http://{listen}"); axum::serve(listener, app) .with_graceful_shutdown(shutdown()) .await .context("serving")?; Ok(()) } async fn shutdown() { let ctrl_c = async { let _ = tokio::signal::ctrl_c().await; }; #[cfg(unix)] let term = async { if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { s.recv().await; } }; #[cfg(not(unix))] let term = std::future::pending::<()>(); tokio::select! { _ = ctrl_c => {}, _ = term => {}, } info!("shutting down"); }