slabs-framework 0.2.0

Batteries-included, agent-first Transaction Script web framework in Rust
Documentation
//! Batteries-included Transaction Script web framework in Rust.
//!
//! # What this crate owns
//!
//! - Facade re-exports of every Slabs sub-crate: `assets`, `auth`, `cache`, `core`, `db`, `html`,
//!   `http`, `jobs`, `mail`, `realtime`, `storage`, `test`, and `webhooks`.
//! - Top-level re-exports: `id`, `AppConfig`, `AppManifest`, `JobMeta`, `RouteMeta`, `SlabError`,
//!   `SlabResult`, `build_router`, `AppCtx`, `JobDef`, `JobRegistry`, `RateLimiter`, `ScheduleDef`,
//!   and `SlabDef`.
//! - [`prelude`]: single import (`use slabs::prelude::*;`) for slab and job files.
//! - [`discover_slabs!`]: macro that includes `$OUT_DIR/discovered_slabs.rs` generated by `slabs-build`.
//! - [`SlabsApp`]: boots [`AppCtx`], runs migrations, builds the router, and serves HTTP plus background workers.
//! - [`init_tracing`]: initializes `tracing_subscriber` with `RUST_LOG` and optional JSON output.
//!
//! # Agent invariants
//!
//! - Invoke `slabs::discover_slabs!();` once in the application crate's `src/lib.rs`. It generates `discovered_slabs`, `discovered_jobs`, `collect_slabs()`, and `collect_jobs()`.
//! - Import `use slabs::prelude::*;` inside slab files instead of wiring sub-crates individually.
//! - Boot the app with [`SlabsApp::boot`], passing a `sqlx::migrate::Migrator`, `collect_slabs()`, and `collect_jobs()`.
//! - Attach recurring jobs with [`SlabsApp::with_schedules`] before calling [`SlabsApp::serve`].
//! - [`SlabsApp::serve`] spawns background job workers and schedules, binds `config.bind_addr`, and shuts down cleanly on `SIGINT` or `SIGTERM`.
//! - Call [`init_tracing`] at the top of `main()`. Set `SLABS_LOG_FORMAT=json` for structured JSON logs and `RUST_LOG` to override the default filter (`info,tower_http=info,sqlx=warn`).
//!
//! # Example
//!
//! ```rust,no_run
//! use slabs::{AppConfig, SlabsApp};
//!
//! // In src/lib.rs, after calling slabs_build::discover() in build.rs:
//! // slabs::discover_slabs!();
//! // pub static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("./migrations");
//!
//! async fn run(migrator: &sqlx::migrate::Migrator) -> slabs::SlabResult<()> {
//!     slabs::init_tracing();
//!     let config = AppConfig::from_env("my_app");
//!     let app = SlabsApp::boot(config, migrator, vec![], vec![]).await?;
//!     app.serve().await
//! }
//! ```

pub use slabs_assets as assets;
pub use slabs_auth as auth;
pub use slabs_cache as cache;
pub use slabs_core as core;
pub use slabs_db as db;
pub use slabs_html as html;
pub use slabs_http as http;
pub use slabs_jobs as jobs;
pub use slabs_mail as mail;
pub use slabs_realtime as realtime;
pub use slabs_storage as storage;
pub use slabs_test as test;
pub use slabs_webhooks as webhooks;

pub use slabs_core::{
    fingerprint, id, position, slug, AppConfig, AppManifest, JobMeta, RouteMeta, SlabError,
    SlabResult, Validate,
};
pub use slabs_db::{AuditEntry, AuditLog, CursorPage, Pagination};
pub use slabs_html::{Flash, FlashKind};
pub use slabs_http::{
    build_router, AppCtx, JobDef, JobRegistry, RateLimiter, ScheduleDef, SlabDef,
};

/// Standard Slabs types, helpers, and `maud` HTML macros re-exported for slab and job files.
///
/// Import with `use slabs::prelude::*;` at the top of a transaction script.
pub mod prelude {
    pub use slabs_auth::{Principal, Session, SESSION_COOKIE_NAME};
    pub use slabs_core::{
        fingerprint, id, position, slug, AppConfig, SlabError, SlabResult, Validate,
    };
    pub use slabs_db::{AuditEntry, AuditLog, CursorPage, Pagination, QueryBuilder};
    pub use slabs_html::{self as html, html as maud, htmx, Flash, FlashKind, Markup, PreEscaped};
    pub use slabs_http::{AppCtx, JobDef, ScheduleDef, SlabDef};
    pub use slabs_mail::Email;
    pub use slabs_storage::BlobMeta;
}

/// Include the compile-time discovered transaction scripts and background jobs generated by `slabs_build::discover()`.
///
/// Place this macro once in your application crate's `src/lib.rs`. It expands `$OUT_DIR/discovered_slabs.rs`,
/// defining `discovered_slabs`, `discovered_jobs`, `collect_slabs()`, and `collect_jobs()`.
#[macro_export]
macro_rules! discover_slabs {
    () => {
        include!(concat!(env!("OUT_DIR"), "/discovered_slabs.rs"));
    };
}

/// High-level boot entry point for a Slabs application.
#[derive(Debug)]
pub struct SlabsApp {
    /// Shared runtime context passed to HTTP slabs and background jobs.
    pub ctx: AppCtx,
    /// Built Axum router containing all discovered slabs and built-in endpoints.
    pub router: axum::Router,
    /// Registry of background job handlers.
    pub job_registry: JobRegistry,
    /// Recurring maintenance job schedules started alongside the server.
    pub schedules: Vec<ScheduleDef>,
}

impl SlabsApp {
    /// Connect subsystems, run database migrations, and assemble the HTTP router and job registry.
    pub async fn boot(
        config: AppConfig,
        migrator: &sqlx::migrate::Migrator,
        slabs: Vec<SlabDef>,
        jobs: Vec<JobDef>,
    ) -> SlabResult<Self> {
        let ctx = AppCtx::connect(config).await?;
        ctx.db.migrate(migrator).await?;
        let router = build_router(ctx.clone(), slabs, &jobs);
        let job_registry = JobRegistry::new(jobs);

        Ok(Self {
            ctx,
            router,
            job_registry,
            schedules: Vec::new(),
        })
    }

    /// Attach recurring maintenance schedules to run while the server is active.
    #[must_use]
    pub fn with_schedules(mut self, schedules: Vec<ScheduleDef>) -> Self {
        self.schedules = schedules;
        self
    }

    /// Serve HTTP, background job workers, and recurring schedules with graceful shutdown on `SIGINT` or `SIGTERM`.
    ///
    /// On shutdown signal, this stops job workers and schedule tasks via a `tokio::sync::watch`
    /// channel and drains in-flight HTTP requests before returning.
    pub async fn serve(self) -> SlabResult<()> {
        let addr = self.ctx.config.bind_addr.clone();
        let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);

        self.job_registry
            .spawn_workers_with_shutdown(&self.ctx, &shutdown_rx);
        if !self.schedules.is_empty() {
            self.job_registry.spawn_schedules_with_shutdown(
                &self.ctx,
                self.schedules,
                &shutdown_rx,
            );
        }

        let listener = tokio::net::TcpListener::bind(&addr)
            .await
            .map_err(|e| SlabError::internal(format!("failed to bind {addr}: {e}")))?;

        tracing::info!(
            app = %self.ctx.config.app_name,
            addr = %addr,
            "slabs server listening"
        );

        axum::serve(listener, self.router)
            .with_graceful_shutdown(shutdown_signal(shutdown_tx))
            .await
            .map_err(|e| SlabError::internal(format!("server error: {e}")))
    }
}

async fn shutdown_signal(shutdown_tx: tokio::sync::watch::Sender<bool>) {
    let ctrl_c = async {
        let _ = tokio::signal::ctrl_c().await;
    };

    #[cfg(unix)]
    let terminate = async {
        if let Ok(mut sig) =
            tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
        {
            sig.recv().await;
        }
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        () = ctrl_c => {},
        () = terminate => {},
    }

    tracing::info!("shutdown signal received, draining requests and stopping job workers...");
    let _ = shutdown_tx.send(true);
}

/// Initialize `tracing_subscriber` using `RUST_LOG` (defaulting to `info,tower_http=info,sqlx=warn`).
///
/// Set `SLABS_LOG_FORMAT=json` to emit newline-delimited JSON logs in production.
pub fn init_tracing() {
    use tracing_subscriber::{fmt, EnvFilter};
    let filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new("info,tower_http=info,sqlx=warn"));

    let use_json = std::env::var("SLABS_LOG_FORMAT").is_ok_and(|v| v.eq_ignore_ascii_case("json"));

    if use_json {
        let _ = fmt().json().with_env_filter(filter).try_init();
    } else {
        let _ = fmt().with_env_filter(filter).try_init();
    }
}