capy-framework 0.4.0

An opinionated full-stack Rust web framework with strong conventions and sensible defaults.
Documentation
use crate::{AppConfig, AppContext, AppError, Result, Routes};
use capy_db::{MigratorTrait, NoMigrations};
use std::{collections::BTreeMap, marker::PhantomData, path::PathBuf, sync::Arc, time::Duration};
use tracing_subscriber::EnvFilter;

/// Application builder: configuration, database, tracing, migrations, and HTTP.
pub struct App<M = NoMigrations> {
    routes: Routes,
    api_routes: Option<Routes>,
    frontend: Option<PathBuf>,
    config: Option<AppConfig>,
    request_timeouts: BTreeMap<String, Option<Duration>>,
    observer: crate::diagnostics::Observer,
    migrations: PhantomData<M>,
}

impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}

impl App {
    /// Begin an application using configuration from the current directory.
    pub fn new() -> Self {
        Self {
            routes: Routes::new(),
            api_routes: None,
            frontend: None,
            config: None,
            request_timeouts: BTreeMap::new(),
            observer: None,
            migrations: PhantomData,
        }
    }
}

impl<M: MigratorTrait> App<M> {
    /// Install an application-owned, nonblocking response observer for telemetry.
    pub fn observe_requests(mut self, observer: impl crate::RequestObserver) -> Self {
        self.observer = Some(Arc::new(observer));
        self
    }

    /// Override the response-header deadline for a full matched route template,
    /// such as `/api/events` or `/api/posts/{id}`. `None` intentionally disables
    /// it. Response body streaming is never subject to this header deadline.
    pub fn request_timeout_for(
        mut self,
        route: impl Into<String>,
        timeout: Option<Duration>,
    ) -> Self {
        self.request_timeouts.insert(route.into(), timeout);
        self
    }

    /// Mount API routes under `/api`, preserving JSON errors within that namespace.
    /// Declare paths such as `/posts` without repeating the prefix.
    pub fn api_routes(mut self, routes: Routes) -> Self {
        self.api_routes = Some(routes);
        self
    }

    /// Serve built frontend assets and use index.html for non-API browser routes.
    /// The path is relative to the application's working directory. Production
    /// startup requires a readable index.html; development may use Vite instead.
    pub fn frontend(mut self, directory: impl Into<PathBuf>) -> Self {
        self.frontend = Some(directory.into());
        self
    }

    /// Set the application's routes.
    pub fn routes(mut self, routes: Routes) -> Self {
        self.routes = routes;
        self
    }

    /// Use explicit typed configuration, useful for tests and embedded apps.
    pub fn config(mut self, config: AppConfig) -> Self {
        self.config = Some(config);
        self
    }

    /// Register a native SeaORM migrator for the application's CLI commands.
    /// Serving never applies migrations implicitly.
    pub fn migrations<N: MigratorTrait>(self, _migrator: N) -> App<N> {
        App {
            routes: self.routes,
            api_routes: self.api_routes,
            frontend: self.frontend,
            config: self.config,
            request_timeouts: self.request_timeouts,
            observer: self.observer,
            migrations: PhantomData,
        }
    }

    /// Build a service using an existing context, without binding a TCP port.
    /// The returned Axum router can be tested or served with native tooling.
    pub fn into_router(self, context: AppContext) -> axum::Router {
        let http = context.config.http.clone();
        let policy = crate::http_policy::HttpPolicy {
            default_timeout: (http.request_timeout_seconds != 0)
                .then(|| Duration::from_secs(http.request_timeout_seconds)),
            overrides: self.request_timeouts,
        };
        let mut router = self.routes.into_router();
        if let Some(api) = self.api_routes {
            router = router.nest("/api", api.into_router());
        }
        if let Some(directory) = self.frontend {
            router =
                router.fallback(move |request| crate::frontend::serve(directory.clone(), request));
        }
        let mut router = router
            .with_state(context)
            .layer(axum::extract::DefaultBodyLimit::max(http.max_body_bytes))
            .layer(axum::middleware::from_fn_with_state(
                policy,
                crate::http_policy::deadline,
            ));
        if http.compression {
            router = router.layer(tower_http::compression::CompressionLayer::new());
        }
        router
            .layer(axum::middleware::from_fn_with_state(
                self.observer,
                crate::diagnostics::request,
            ))
            .layer(
                tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer::new([
                    axum::http::header::AUTHORIZATION,
                    axum::http::header::COOKIE,
                ]),
            )
            .layer(
                tower_http::sensitive_headers::SetSensitiveResponseHeadersLayer::new([
                    axum::http::header::SET_COOKIE,
                ]),
            )
    }

    /// Serve by default, or execute the command forwarded by `capy`.
    /// Supported arguments: `serve`, `check`, `routes`, `migrate`, `migrate:rollback`,
    /// and `migrate:status`. Migrations are explicit and rollback reverts one.
    pub async fn run(self) -> Result<()> {
        let mut args = std::env::args().skip(1);
        let command = args.next().unwrap_or_else(|| "serve".into());
        if args.next().is_some() {
            return Err(AppError::Configuration(
                "Unexpected arguments. Use the capy CLI for application commands.".into(),
            ));
        }
        self.run_command(&command).await
    }

    /// Run a specific application command without reading process arguments.
    pub async fn run_command(self, command: &str) -> Result<()> {
        if command == "routes" {
            for route in self.routes.inventory() {
                println!("{:<7} {}", route.method, route.path);
            }
            if let Some(api) = &self.api_routes {
                for route in api.inventory() {
                    println!("{:<7} /api{}", route.method, route.path);
                }
            }
            return Ok(());
        }
        if !matches!(
            command,
            "serve" | "check" | "migrate" | "migrate:rollback" | "migrate:status"
        ) {
            return Err(AppError::Configuration(format!(
                "Unknown application command: {command}"
            )));
        }
        let config = match &self.config {
            Some(config) => config.clone(),
            None => AppConfig::load()?,
        };
        config.validate()?;
        if command == "check" || (command == "serve" && config.app.environment == "production") {
            if let Some(directory) = &self.frontend {
                crate::frontend::validate(directory)?;
            }
        }
        if command == "check" {
            let migrations = M::migrations();
            let mut names = std::collections::BTreeSet::new();
            for migration in &migrations {
                if !names.insert(migration.name()) {
                    return Err(AppError::Configuration(
                        "Duplicate registered migration name.".into(),
                    ));
                }
            }
            println!(
                "Configuration valid; {} migrations registered. No database connection opened.",
                migrations.len()
            );
            return Ok(());
        }
        init_logging(&config);
        let db = capy_db::connect(&config.database).await?;
        match command {
            "migrate" => {
                M::up(&db, None).await?;
                println!("Migrations applied.");
            }
            "migrate:rollback" => {
                M::down(&db, Some(1)).await?;
                println!("Rolled back the latest migration.");
            }
            "migrate:status" => {
                let statuses = capy_db::status::<M>(&db).await?;
                if statuses.is_empty() {
                    println!("No migrations registered.");
                }
                for status in statuses {
                    println!(
                        "{:<8} {}",
                        if status.applied { "Applied" } else { "Pending" },
                        status.name
                    );
                }
            }
            _ => {
                let listener =
                    tokio::net::TcpListener::bind((config.host(), config.port())).await?;
                let address = listener.local_addr()?;
                if config.app.environment == "production" {
                    tracing::info!(%address, environment = %config.app.environment, "Capy ready");
                } else if std::env::var_os("CAPY_DEV").is_some() {
                    println!(
                        "✓ Database connected\n✓ Backend ready\nServer running on http://{address}"
                    );
                } else {
                    println!("Capy v{}\n\nA calmer way to build web apps in Rust.\n\nApplication\n  http://{address}\n\nEnvironment\n  {}\n\nDatabase\n  {}\n\nReady.",
                        env!("CARGO_PKG_VERSION"), config.app.environment,
                        if config.database.url.starts_with("sqlite:") { "SQLite" } else { "PostgreSQL" });
                }
                let shutdown_timeout = Duration::from_secs(config.server.shutdown_timeout_seconds);
                let context = AppContext {
                    config: Arc::new(config),
                    db,
                };
                serve(
                    listener,
                    self.into_router(context),
                    shutdown_timeout,
                    shutdown_signal(),
                )
                .await?;
            }
        }
        Ok(())
    }
}

// axum-server owns connection cancellation. Merely dropping axum::serve's
// graceful future leaves its detached connection tasks running in shared runtimes.
pub(crate) async fn serve(
    listener: tokio::net::TcpListener,
    router: axum::Router,
    timeout: Duration,
    signal: impl std::future::Future<Output = ()>,
) -> Result<()> {
    let handle = axum_server::Handle::new();
    let server = axum_server::from_tcp(listener.into_std()?)?
        .handle(handle.clone())
        .serve(router.into_make_service());
    tokio::pin!(server);
    tokio::select! {
        result = &mut server => { result?; }
        () = signal => {
            tracing::info!("shutdown requested");
            handle.graceful_shutdown(None);
            tracing::info!("waiting for active requests");
            match tokio::time::timeout(timeout, &mut server).await {
                Ok(result) => result?,
                Err(_) => {
                    tracing::warn!("shutdown deadline reached");
                    handle.shutdown();
                    server.await?;
                }
            }
        }
    }
    tracing::info!("server stopped");
    Ok(())
}

fn init_logging(config: &AppConfig) {
    let filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new(crate::diagnostics::DEFAULT_FILTER));
    if config.app.environment != "production"
        && std::env::var("CAPY_DEV_LOG").is_ok_and(|value| value == "1")
    {
        let _ = tracing_subscriber::fmt()
            .with_env_filter(filter)
            .with_ansi(false)
            .json()
            .with_writer(crate::dev_logging::writer)
            .try_init();
    } else if config.app.environment == "production" {
        let _ = tracing_subscriber::fmt()
            .with_env_filter(filter)
            .json()
            .try_init();
    } else {
        let _ = tracing_subscriber::fmt()
            .with_env_filter(filter)
            .compact()
            .try_init();
    }
}

async fn shutdown_signal() {
    let ctrl_c = async {
        let _ = tokio::signal::ctrl_c().await;
    };
    #[cfg(unix)]
    let terminate = async {
        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
            Ok(mut stream) => {
                stream.recv().await;
            }
            Err(_) => std::future::pending::<()>().await,
        }
    };
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();
    tokio::select! { () = ctrl_c => {}, () = terminate => {} }
}