Skip to main content

slabs/
lib.rs

1//! Batteries-included Transaction Script web framework in Rust.
2//!
3//! # What this crate owns
4//!
5//! - Facade re-exports of every Slabs sub-crate: `assets`, `auth`, `cache`, `core`, `db`, `html`,
6//!   `http`, `jobs`, `mail`, `realtime`, `storage`, `test`, and `webhooks`.
7//! - Top-level re-exports: `id`, `AppConfig`, `AppEnv`, `AppManifest`, `JobMeta`, `RouteMeta`,
8//!   `SlabError`, `SlabResult`, `build_router`, `client_ip`, `AppCtx`, `ClientIp`, `JobDef`,
9//!   `JobRegistry`, `RateLimiter`, `ScheduleDef`, `SlabDef`, `PresenceEntry`, `PresenceGuard`,
10//!   `validate_ws_origin`, `json_script`, `redirect_external`, `Flash`, and `FlashKind`.
11//! - [`prelude`]: single import (`use slabs::prelude::*;`) for slab and job files.
12//! - [`discover_slabs!`]: macro that includes `$OUT_DIR/discovered_slabs.rs` generated by `slabs-build`.
13//! - [`SlabsApp`]: validates config, boots [`AppCtx`], runs migrations, builds the router, and serves HTTP plus background workers.
14//! - [`init_tracing`]: initializes `tracing_subscriber` with `RUST_LOG` and optional JSON output.
15//!
16//! # Agent invariants
17//!
18//! - Invoke `slabs::discover_slabs!();` once in the application crate's `src/lib.rs`. It generates `discovered_slabs`, `discovered_jobs`, `collect_slabs()`, and `collect_jobs()`.
19//! - Import `use slabs::prelude::*;` inside slab files instead of wiring sub-crates individually.
20//! - Boot the app with [`SlabsApp::boot`], passing a `sqlx::migrate::Migrator`, `collect_slabs()`, and `collect_jobs()`.
21//! - Attach recurring jobs with [`SlabsApp::with_schedules`] before calling [`SlabsApp::serve`].
22//! - [`SlabsApp::serve`] spawns background job workers and schedules, binds `config.bind_addr`, and shuts down cleanly on `SIGINT` or `SIGTERM`.
23//! - 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`).
24//!
25//! # Example
26//!
27//! ```rust,no_run
28//! use slabs::{AppConfig, SlabsApp};
29//!
30//! // In src/lib.rs, after calling slabs_build::discover() in build.rs:
31//! // slabs::discover_slabs!();
32//! // pub static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("./migrations");
33//!
34//! async fn run(migrator: &sqlx::migrate::Migrator) -> slabs::SlabResult<()> {
35//!     slabs::init_tracing();
36//!     let config = AppConfig::from_env("my_app");
37//!     let app = SlabsApp::boot(config, migrator, vec![], vec![]).await?;
38//!     app.serve().await
39//! }
40//! ```
41
42pub use slabs_assets as assets;
43pub use slabs_auth as auth;
44pub use slabs_cache as cache;
45pub use slabs_core as core;
46pub use slabs_db as db;
47pub use slabs_html as html;
48pub use slabs_http as http;
49pub use slabs_jobs as jobs;
50pub use slabs_mail as mail;
51pub use slabs_realtime as realtime;
52pub use slabs_storage as storage;
53pub use slabs_test as test;
54pub use slabs_webhooks as webhooks;
55
56pub use slabs_core::{
57    fingerprint, id, position, slug, AppConfig, AppEnv, AppManifest, JobMeta, RouteMeta, SlabError,
58    SlabResult, Validate,
59};
60pub use slabs_db::{
61    AuditEntry, AuditLog, CursorPage, IncidentInput, IncidentOutcome, IncidentRecord, Incidents,
62    Pagination,
63};
64pub use slabs_html::{json_script, redirect_external, Flash, FlashKind};
65pub use slabs_http::{
66    build_router, client_ip, AppCtx, ClientIp, JobDef, JobRegistry, RateLimiter, ScheduleDef,
67    SlabDef,
68};
69pub use slabs_realtime::{validate_ws_origin, PresenceEntry, PresenceGuard};
70
71/// Standard Slabs types, helpers, and `maud` HTML macros re-exported for slab and job files.
72///
73/// Import with `use slabs::prelude::*;` at the top of a transaction script.
74/// Note: `PreEscaped` is intentionally omitted from the prelude to discourage accidental raw HTML
75/// injection; import `slabs::html::PreEscaped` explicitly when needed.
76pub mod prelude {
77    pub use slabs_auth::{Principal, Session, SESSION_COOKIE_NAME};
78    pub use slabs_core::{
79        fingerprint, id, position, slug, AppConfig, AppEnv, SlabError, SlabResult, Validate,
80    };
81    pub use slabs_db::{
82        AuditEntry, AuditLog, CursorPage, IncidentInput, IncidentOutcome, IncidentRecord,
83        Incidents, Pagination, QueryBuilder,
84    };
85    pub use slabs_html::{
86        self as html, html as maud, htmx, json_script, redirect_external, Flash, FlashKind, Markup,
87    };
88    pub use slabs_http::{client_ip, AppCtx, ClientIp, JobDef, ScheduleDef, SlabDef};
89    pub use slabs_mail::Email;
90    pub use slabs_realtime::{validate_ws_origin, PresenceEntry, PresenceGuard};
91    pub use slabs_storage::BlobMeta;
92}
93
94/// Include the compile-time discovered transaction scripts and background jobs generated by `slabs_build::discover()`.
95///
96/// Place this macro once in your application crate's `src/lib.rs`. It expands `$OUT_DIR/discovered_slabs.rs`,
97/// defining `discovered_slabs`, `discovered_jobs`, `collect_slabs()`, and `collect_jobs()`.
98#[macro_export]
99macro_rules! discover_slabs {
100    () => {
101        include!(concat!(env!("OUT_DIR"), "/discovered_slabs.rs"));
102    };
103}
104
105/// High-level boot entry point for a Slabs application.
106#[derive(Debug)]
107pub struct SlabsApp {
108    /// Shared runtime context passed to HTTP slabs and background jobs.
109    pub ctx: AppCtx,
110    /// Built Axum router containing all discovered slabs and built-in endpoints.
111    pub router: axum::Router,
112    /// Registry of background job handlers.
113    pub job_registry: JobRegistry,
114    /// Recurring maintenance job schedules started alongside the server.
115    pub schedules: Vec<ScheduleDef>,
116}
117
118impl SlabsApp {
119    /// Validate configuration, connect subsystems, run database migrations, and assemble the HTTP
120    /// router and job registry.
121    pub async fn boot(
122        config: AppConfig,
123        migrator: &sqlx::migrate::Migrator,
124        slabs: Vec<SlabDef>,
125        jobs: Vec<JobDef>,
126    ) -> SlabResult<Self> {
127        config.validate()?;
128        let ctx = AppCtx::connect(config).await?;
129        ctx.db.migrate(migrator).await?;
130        let router = build_router(ctx.clone(), slabs, &jobs);
131        let job_registry = JobRegistry::new(jobs);
132
133        Ok(Self {
134            ctx,
135            router,
136            job_registry,
137            schedules: Vec::new(),
138        })
139    }
140
141    /// Attach recurring maintenance schedules to run while the server is active.
142    #[must_use]
143    pub fn with_schedules(mut self, schedules: Vec<ScheduleDef>) -> Self {
144        self.schedules = schedules;
145        self
146    }
147
148    /// Serve HTTP, background job workers, and recurring schedules with graceful shutdown on `SIGINT` or `SIGTERM`.
149    ///
150    /// On shutdown signal, this marks the server as draining (causing `GET /health/ready` to
151    /// return `503`), stops background workers from claiming new jobs via a `tokio::sync::watch`
152    /// channel, drains in-flight HTTP requests, awaits running workers for up to 15 seconds, and
153    /// checkpoints and closes the `SQLite` pools cleanly before exiting.
154    pub async fn serve(self) -> SlabResult<()> {
155        let addr = self.ctx.config.bind_addr.clone();
156        let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
157
158        let mut worker_handles = self
159            .job_registry
160            .spawn_workers_with_shutdown(&self.ctx, &shutdown_rx);
161        if !self.schedules.is_empty() {
162            worker_handles.extend(self.job_registry.spawn_schedules_with_shutdown(
163                &self.ctx,
164                self.schedules,
165                &shutdown_rx,
166            ));
167        }
168
169        let listener = tokio::net::TcpListener::bind(&addr)
170            .await
171            .map_err(|e| SlabError::internal(format!("failed to bind {addr}: {e}")))?;
172
173        tracing::info!(
174            app = %self.ctx.config.app_name,
175            addr = %addr,
176            env = %self.ctx.config.env.as_str(),
177            "slabs server listening"
178        );
179
180        let ctx_for_shutdown = self.ctx.clone();
181        let serve_result = axum::serve(
182            listener,
183            self.router
184                .into_make_service_with_connect_info::<std::net::SocketAddr>(),
185        )
186        .with_graceful_shutdown(shutdown_signal(ctx_for_shutdown, shutdown_tx))
187        .await;
188
189        let drain_workers = async {
190            for handle in worker_handles {
191                let _ = handle.await;
192            }
193        };
194        if tokio::time::timeout(std::time::Duration::from_secs(15), drain_workers)
195            .await
196            .is_err()
197        {
198            tracing::warn!("timed out waiting 15s for background workers to drain");
199        }
200
201        self.ctx.db.checkpoint_and_close().await;
202
203        serve_result.map_err(|e| SlabError::internal(format!("server error: {e}")))
204    }
205}
206
207async fn shutdown_signal(ctx: AppCtx, shutdown_tx: tokio::sync::watch::Sender<bool>) {
208    let ctrl_c = async {
209        let _ = tokio::signal::ctrl_c().await;
210    };
211
212    #[cfg(unix)]
213    let terminate = async {
214        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
215            Ok(mut sig) => {
216                sig.recv().await;
217            }
218            Err(err) => {
219                tracing::warn!(error = %err, "failed to install SIGTERM handler");
220                std::future::pending::<()>().await;
221            }
222        }
223    };
224
225    #[cfg(not(unix))]
226    let terminate = std::future::pending::<()>();
227
228    tokio::select! {
229        () = ctrl_c => {},
230        () = terminate => {},
231    }
232
233    tracing::info!("shutdown signal received, draining requests and stopping job workers...");
234    ctx.set_draining();
235    let _ = shutdown_tx.send(true);
236}
237
238/// Initialize `tracing_subscriber` using `RUST_LOG` (defaulting to `info,tower_http=info,sqlx=warn`).
239///
240/// Set `SLABS_LOG_FORMAT=json` to emit newline-delimited JSON logs in production.
241pub fn init_tracing() {
242    use tracing_subscriber::{fmt, EnvFilter};
243    let filter = EnvFilter::try_from_default_env()
244        .unwrap_or_else(|_| EnvFilter::new("info,tower_http=info,sqlx=warn"));
245
246    let use_json = std::env::var("SLABS_LOG_FORMAT").is_ok_and(|v| v.eq_ignore_ascii_case("json"));
247
248    if use_json {
249        let _ = fmt().json().with_env_filter(filter).try_init();
250    } else {
251        let _ = fmt().with_env_filter(filter).try_init();
252    }
253}