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::{
65    bug_report_widget, bug_report_widget_with_label, json_script, redirect_external, Flash,
66    FlashKind,
67};
68pub use slabs_http::{
69    build_router, client_ip, AppCtx, ClientIp, JobDef, JobRegistry, RateLimiter, ScheduleDef,
70    SlabDef,
71};
72pub use slabs_realtime::{validate_ws_origin, PresenceEntry, PresenceGuard};
73
74/// Standard Slabs types, helpers, and `maud` HTML macros re-exported for slab and job files.
75///
76/// Import with `use slabs::prelude::*;` at the top of a transaction script.
77/// Note: `PreEscaped` is intentionally omitted from the prelude to discourage accidental raw HTML
78/// injection; import `slabs::html::PreEscaped` explicitly when needed.
79pub mod prelude {
80    pub use slabs_auth::{Principal, Session, SESSION_COOKIE_NAME};
81    pub use slabs_core::{
82        fingerprint, id, position, slug, AppConfig, AppEnv, SlabError, SlabResult, Validate,
83    };
84    pub use slabs_db::{
85        AuditEntry, AuditLog, CursorPage, IncidentInput, IncidentOutcome, IncidentRecord,
86        Incidents, Pagination, QueryBuilder,
87    };
88    pub use slabs_html::{
89        self as html, bug_report_widget, bug_report_widget_with_label, html as maud, htmx,
90        json_script, redirect_external, Flash, FlashKind, Markup,
91    };
92    pub use slabs_http::{client_ip, AppCtx, ClientIp, JobDef, ScheduleDef, SlabDef};
93    pub use slabs_mail::Email;
94    pub use slabs_realtime::{validate_ws_origin, PresenceEntry, PresenceGuard};
95    pub use slabs_storage::BlobMeta;
96}
97
98/// Include the compile-time discovered transaction scripts and background jobs generated by `slabs_build::discover()`.
99///
100/// Place this macro once in your application crate's `src/lib.rs`. It expands `$OUT_DIR/discovered_slabs.rs`,
101/// defining `discovered_slabs`, `discovered_jobs`, `collect_slabs()`, and `collect_jobs()`.
102#[macro_export]
103macro_rules! discover_slabs {
104    () => {
105        include!(concat!(env!("OUT_DIR"), "/discovered_slabs.rs"));
106    };
107}
108
109/// High-level boot entry point for a Slabs application.
110#[derive(Debug)]
111pub struct SlabsApp {
112    /// Shared runtime context passed to HTTP slabs and background jobs.
113    pub ctx: AppCtx,
114    /// Built Axum router containing all discovered slabs and built-in endpoints.
115    pub router: axum::Router,
116    /// Registry of background job handlers.
117    pub job_registry: JobRegistry,
118    /// Recurring maintenance job schedules started alongside the server.
119    pub schedules: Vec<ScheduleDef>,
120}
121
122impl SlabsApp {
123    /// Validate configuration, connect subsystems, run database migrations, and assemble the HTTP
124    /// router and job registry.
125    pub async fn boot(
126        config: AppConfig,
127        migrator: &sqlx::migrate::Migrator,
128        slabs: Vec<SlabDef>,
129        jobs: Vec<JobDef>,
130    ) -> SlabResult<Self> {
131        config.validate()?;
132        let ctx = AppCtx::connect(config).await?;
133        ctx.db.migrate(migrator).await?;
134        let router = build_router(ctx.clone(), slabs, &jobs);
135        let job_registry = JobRegistry::new(jobs);
136
137        Ok(Self {
138            ctx,
139            router,
140            job_registry,
141            schedules: Vec::new(),
142        })
143    }
144
145    /// Attach recurring maintenance schedules to run while the server is active.
146    #[must_use]
147    pub fn with_schedules(mut self, schedules: Vec<ScheduleDef>) -> Self {
148        self.schedules = schedules;
149        self
150    }
151
152    /// Serve HTTP, background job workers, and recurring schedules with graceful shutdown on `SIGINT` or `SIGTERM`.
153    ///
154    /// On shutdown signal, this marks the server as draining (causing `GET /health/ready` to
155    /// return `503`), stops background workers from claiming new jobs via a `tokio::sync::watch`
156    /// channel, drains in-flight HTTP requests, and awaits running workers for up to 15 seconds.
157    pub async fn serve(self) -> SlabResult<()> {
158        let addr = self.ctx.config.bind_addr.clone();
159        let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
160
161        let mut worker_handles = self
162            .job_registry
163            .spawn_workers_with_shutdown(&self.ctx, &shutdown_rx);
164        if !self.schedules.is_empty() {
165            worker_handles.extend(self.job_registry.spawn_schedules_with_shutdown(
166                &self.ctx,
167                self.schedules,
168                &shutdown_rx,
169            ));
170        }
171
172        let listener = tokio::net::TcpListener::bind(&addr)
173            .await
174            .map_err(|e| SlabError::internal(format!("failed to bind {addr}: {e}")))?;
175
176        tracing::info!(
177            app = %self.ctx.config.app_name,
178            addr = %addr,
179            env = %self.ctx.config.env.as_str(),
180            "slabs server listening"
181        );
182
183        let ctx_for_shutdown = self.ctx.clone();
184        let serve_result = axum::serve(
185            listener,
186            self.router
187                .into_make_service_with_connect_info::<std::net::SocketAddr>(),
188        )
189        .with_graceful_shutdown(shutdown_signal(ctx_for_shutdown, shutdown_tx))
190        .await;
191
192        let drain_workers = async {
193            for handle in worker_handles {
194                let _ = handle.await;
195            }
196        };
197        if tokio::time::timeout(std::time::Duration::from_secs(15), drain_workers)
198            .await
199            .is_err()
200        {
201            tracing::warn!("timed out waiting 15s for background workers to drain");
202        }
203
204        serve_result.map_err(|e| SlabError::internal(format!("server error: {e}")))
205    }
206}
207
208async fn shutdown_signal(ctx: AppCtx, shutdown_tx: tokio::sync::watch::Sender<bool>) {
209    let ctrl_c = async {
210        let _ = tokio::signal::ctrl_c().await;
211    };
212
213    #[cfg(unix)]
214    let terminate = async {
215        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
216            Ok(mut sig) => {
217                sig.recv().await;
218            }
219            Err(err) => {
220                tracing::warn!(error = %err, "failed to install SIGTERM handler");
221                std::future::pending::<()>().await;
222            }
223        }
224    };
225
226    #[cfg(not(unix))]
227    let terminate = std::future::pending::<()>();
228
229    tokio::select! {
230        () = ctrl_c => {},
231        () = terminate => {},
232    }
233
234    tracing::info!("shutdown signal received, draining requests and stopping job workers...");
235    ctx.set_draining();
236    let _ = shutdown_tx.send(true);
237}
238
239/// Initialize `tracing_subscriber` using `RUST_LOG` (defaulting to `info,tower_http=info,sqlx=warn`).
240///
241/// Set `SLABS_LOG_FORMAT=json` to emit newline-delimited JSON logs in production.
242pub fn init_tracing() {
243    use tracing_subscriber::{fmt, EnvFilter};
244    let filter = EnvFilter::try_from_default_env()
245        .unwrap_or_else(|_| EnvFilter::new("info,tower_http=info,sqlx=warn"));
246
247    let use_json = std::env::var("SLABS_LOG_FORMAT").is_ok_and(|v| v.eq_ignore_ascii_case("json"));
248
249    if use_json {
250        let _ = fmt().json().with_env_filter(filter).try_init();
251    } else {
252        let _ = fmt().with_env_filter(filter).try_init();
253    }
254}