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