Introduction
Everything you need to build and ship web apps in Rust.
Every HTTP endpoint in Slabs is one self-contained file with raw SQL, explicit transactions, and compile-time discovery. Humans and parallel AI agents can ship twenty endpoints at once with zero merge conflicts.
Get started
Install the CLI, generate a standalone application, and run the health check before writing your first endpoint:
cargo install slabs-cli
slabs new app my_app
cd my_app
slabs doctor
slabs dev
slabs new app creates a working project with slabs-framework 0.5, compile-time slab discovery, Tailwind CSS v4, a cargo-chef and Litestream Dockerfile, bundled .claude/skills/, and a GitHub Actions CI workflow. In Rust code, slabs-framework exposes the slabs crate name (use slabs::prelude::*;).
Follow a tutorial
Start here if you want to build something real and see every piece run together.
Read the guides
Jump straight to a task when you know what you need to build, lock down, or deploy.
Study reference apps
Real applications teach faster than isolated snippets. Three full-stack apps rebuilt from Ruby on Rails live in sogamoso/slabs-examples.
Read the doctrine and dive deeper
Understand why Slabs rejects MVC layers, hidden callbacks, and Node build chains, or look up exact APIs and system tables.
For AI agents
Point your coding agent directly at the plain-text index, the single-file Markdown handbook, or any page’s raw Markdown source under raw/.
Build your first Slabs app in 10 minutes
You are going to build a working note-taking app from scratch. By the end of this tutorial, you will have a SQLite migration, two self-contained HTTP endpoints with co-located tests, and a running local server with live HTMX form updates.
Prerequisites
Install mise so you have pinned versions of rust, standalone tailwindcss v4, and cargo-nextest. Install the slabs CLI from crates.io (or run it directly inside the Slabs workspace):
cargo install slabs-cli
Create a new application
Generate a standalone project and run slabs doctor to verify your toolchain and defaults:
slabs new app quicknotes
cd quicknotes
slabs doctor
Look at the files slabs new app created:
| File | Role |
|---|---|
Cargo.toml | Declares slabs-framework = "0.5" (imported in Rust as slabs), slabs-build = "0.5", axum, maud, sqlx, and safety lints including unsafe_code = "forbid". |
build.rs | Calls slabs_build::discover(); so Cargo registers every .rs file in slabs/<feature>/ and jobs/ at compile time. |
src/lib.rs | Invokes slabs::discover_slabs!();, defines MIGRATOR, and exports boot plus a #[cfg(test)] test_app helper. |
src/main.rs | Calls slabs::init_tracing(), loads AppConfig::from_env("quicknotes"), boots the app, and binds the HTTP server. |
assets/input.css | Imports Tailwind CSS v4 and scans ../slabs for utility classes. |
Dockerfile and litestream.yml | Multi-stage cargo-chef container build with pinned Litestream v0.3.13 replication and docker-entrypoint.sh. |
.claude/skills/ | Five bundled agent skills for authoring slabs, migrations, reviews, deploys, and incident fixes. |
There is no routes.rs, models/, or controllers/ folder anywhere in the tree.
Add a SQL migration
Create migrations/0001_notes.sql to define a notes table:
CREATE TABLE IF NOT EXISTS notes (
id TEXT PRIMARY KEY NOT NULL,
body TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_notes_created_at
ON notes (created_at DESC);
Apply the migration to a local SQLite database and write the full schema snapshot to schema.sql:
DATABASE_URL="sqlite://quicknotes.db?mode=rwc" slabs db migrate
DATABASE_URL="sqlite://quicknotes.db?mode=rwc" slabs db dump-schema
Open schema.sql. It contains your notes table and the twelve system tables owned by Slabs (slabs_sessions, slabs_jobs, slabs_incidents, slabs_audit_log, and eight others). Read schema.sql before writing any new SQL query.
Write a slab to list notes
Create slabs/notes/list_notes.rs. Do not edit src/lib.rs or any router file. slabs-build discovers and registers this file on the next build.
#![allow(unused)]
fn main() {
use axum::extract::State;
use slabs::prelude::*;
pub fn slab() -> SlabDef {
SlabDef::get("/", handle)
.name("notes.list_notes")
.summary("Render the notes page and creation form")
}
#[derive(sqlx::FromRow)]
struct NoteRow {
id: String,
body: String,
created_at: String,
}
async fn handle(State(ctx): State<AppCtx>) -> SlabResult<Markup> {
let notes: Vec<NoteRow> = sqlx::query_as(
"SELECT id, body, created_at
FROM notes
ORDER BY created_at DESC, id DESC
LIMIT 50",
)
.fetch_all(ctx.db.reader())
.await?;
let styles = ctx.assets.stylesheet_urls();
let scripts = ctx.assets.behavior_urls();
Ok(html::document(
"Quicknotes",
&styles,
&scripts,
maud! {
main class="max-w-2xl mx-auto p-6 space-y-6" {
h1 class="text-2xl font-bold" { "Quicknotes" }
form hx-post="/notes"
hx-target="#notes-list"
hx-swap="afterbegin"
"hx-on::after-request"="this.reset()"
class="flex gap-2" {
input type="text"
name="body"
placeholder="Write a note..."
required
class="input flex-1";
button type="submit" class="btn" { "Save" }
}
section id="notes-list" class="space-y-2" {
@for note in ¬es {
article id=(format!("note-{}", note.id)) class="card p-3" {
p class="text-sm" { (note.body) }
p class="text-xs text-muted-foreground mt-1" { (note.created_at) }
}
}
}
}
},
))
}
#[cfg(test)]
mod tests {
use axum::http::StatusCode;
#[tokio::test]
async fn renders_home_page() {
let app = crate::test_app().await;
let res = app.get("/").await;
assert_eq!(res.status, StatusCode::OK);
assert!(res.text().contains("Quicknotes"));
}
}
}
Three mechanisms are at work in this file:
ctx.db.reader()executes theSELECTon the 16-connection read-only SQLite WAL pool.html::document(...)loads Basecoat UI, HTMX 2, SSE, Idiomorph, Alpine.js 3, and your compiled Tailwind stylesheet from/_slabs/vendor/and/assets/{hash}/....#[cfg(test)] mod testsboots an isolated in-memory SQLite database throughcrate::test_app().await.
Write a slab to create a note
Create slabs/notes/create_note.rs. It validates form input, generates a prefixed ULID with id::new("nte"), inserts the row inside a BEGIN IMMEDIATE transaction, and returns an HTML fragment that HTMX prepends to #notes-list.
#![allow(unused)]
fn main() {
use axum::{extract::State, http::StatusCode, Form};
use chrono::Utc;
use serde::Deserialize;
use slabs::prelude::*;
pub fn slab() -> SlabDef {
SlabDef::post("/notes", handle)
.name("notes.create_note")
.summary("Insert a note and return an HTML fragment")
}
#[derive(Debug, Deserialize)]
pub struct Input {
pub body: String,
}
async fn handle(
State(ctx): State<AppCtx>,
Form(input): Form<Input>,
) -> SlabResult<(StatusCode, Markup)> {
let body = input.body.trim().to_string();
if body.is_empty() {
return Err(SlabError::validation("body", "note body cannot be blank"));
}
let note_id = id::new("nte");
let now = Utc::now().to_rfc3339();
let mut tx = ctx.db.begin().await?;
sqlx::query("INSERT INTO notes (id, body, created_at) VALUES (?, ?, ?)")
.bind(¬e_id)
.bind(&body)
.bind(&now)
.execute(&mut *tx)
.await?;
tx.commit().await?;
let fragment = maud! {
article id=(format!("note-{note_id}")) class="card p-3" {
p class="text-sm" { (body) }
p class="text-xs text-muted-foreground mt-1" { (now) }
}
};
Ok((StatusCode::CREATED, fragment))
}
#[cfg(test)]
mod tests {
use axum::http::StatusCode;
#[tokio::test]
async fn creates_note_and_rejects_blank_input() {
let app = crate::test_app().await;
let bad = app.post_form("/notes", &[("body", " ")]).await;
assert_eq!(bad.status, StatusCode::UNPROCESSABLE_ENTITY);
let created = app.post_form("/notes", &[("body", "Ship Slabs")]).await;
assert_eq!(created.status, StatusCode::CREATED);
assert!(created.text().contains("Ship Slabs"));
let list = app.get("/").await;
assert!(list.text().contains("Ship Slabs"));
}
}
}
Format, check, and run the server
Format both src/ and the auto-discovered slabs/ directory, then run the full 6-step slabs check gate (formatting, static [security] scan, Clippy, Rustdoc, doctests, and parallel tests):
slabs fmt
slabs check --no-docs
Compile Tailwind CSS and start the live development server:
slabs dev
Open http://127.0.0.1:3000. Submit a note and watch HTMX prepend it without a full page reload. In development mode (SLABS_ENV=development), visit http://127.0.0.1:3000/_slabs/manifest to inspect the JSON route manifest and http://127.0.0.1:3000/health/ready to check database readiness.
What you built
slabs-builddiscovered every.rsfile inslabs/<feature>/at compile time without a central router file.ctx.db.reader()ran reads concurrently, andctx.db.begin().await?opened aBEGIN IMMEDIATEwrite transaction.- Each slab carried its own input validation, SQL, HTML template, and isolated
#[tokio::test]tests.
Next, follow Add live updates with SSE, HTMX, and Idiomorph to push live DOM updates and online presence to every connected browser.
Add live updates with SSE, HTMX, and Idiomorph
Extend your Slabs app so changes made in one browser tab appear immediately in every other open tab. You will add an SSE stream with ctx.realtime.sse_stream, broadcast Maud HTML fragments with ctx.realtime.publish_html, morph regions in place with Idiomorph, track online participants with ctx.realtime.track_presence, and guard WebSocket upgrades with validate_ws_origin.
How Slabs realtime works
AppCtx.realtime is an in-process broadcast hub backed by tokio::sync::broadcast. Each named topic (such as "board:brd_123" or "room:rm_456") holds a 256-message ring buffer.
ctx.realtime.sse_stream(topic)returns an AxumSseresponse with a 15-second"ping"keep-alive comment. Slow receivers skip lagged events instead of disconnecting.ctx.realtime.publish_html(topic, event, html)pushes an HTML fragment to every subscriber ontopic.ctx.realtime.track_presence(topic, user_id, meta)registers an online participant and returns aPresenceGuardthat removes the entry automatically when the connection drops.html::document(...)loads/_slabs/vendor/htmx.min.js,/_slabs/vendor/htmx-ext-sse.js, and/_slabs/vendor/idiomorph-ext.min.js, and attacheshx-ext="morph"on<body>.
Step 1. Add an SSE stream slab
Create slabs/realtime/notes_sse.rs. Check authentication or room permissions first on private streams, then return ctx.realtime.sse_stream(...).
#![allow(unused)]
fn main() {
use axum::{extract::State, response::IntoResponse};
use slabs::prelude::*;
pub fn slab() -> SlabDef {
SlabDef::get("/notes/stream", handle)
.name("realtime.notes_sse")
.summary("Stream live note HTML fragments over SSE")
}
async fn handle(State(ctx): State<AppCtx>) -> impl IntoResponse {
ctx.realtime.sse_stream("notes:global")
}
#[cfg(test)]
mod tests {
use axum::http::StatusCode;
#[tokio::test]
async fn sse_route_is_registered_in_manifest() {
let app = crate::test_app().await;
let res = app.get("/_slabs/manifest").await;
assert_eq!(res.status, StatusCode::OK);
assert!(res.text().contains("/notes/stream"));
}
}
}
Step 2. Publish HTML after the database commit
Publish to ctx.realtime only after tx.commit().await? succeeds. Browsers will never receive an event for a transaction that rolled back.
Update slabs/notes/create_note.rs:
#![allow(unused)]
fn main() {
use axum::{extract::State, http::StatusCode, Form};
use chrono::Utc;
use serde::Deserialize;
use slabs::prelude::*;
pub fn slab() -> SlabDef {
SlabDef::post("/notes", handle)
.name("notes.create_note")
.summary("Insert a note and broadcast it to SSE subscribers")
}
#[derive(Debug, Deserialize)]
pub struct Input {
pub body: String,
}
async fn handle(
State(ctx): State<AppCtx>,
Form(input): Form<Input>,
) -> SlabResult<StatusCode> {
let body = input.body.trim().to_string();
if body.is_empty() {
return Err(SlabError::validation("body", "note body cannot be blank"));
}
let note_id = id::new("nte");
let now = Utc::now().to_rfc3339();
let mut tx = ctx.db.begin().await?;
sqlx::query("INSERT INTO notes (id, body, created_at) VALUES (?, ?, ?)")
.bind(¬e_id)
.bind(&body)
.bind(&now)
.execute(&mut *tx)
.await?;
tx.commit().await?;
let fragment = maud! {
article id=(format!("note-{note_id}")) class="card p-3" {
p class="text-sm" { (body) }
p class="text-xs text-muted-foreground mt-1" { (now) }
}
};
ctx.realtime
.publish_html("notes:global", "note_created", fragment.into_string());
Ok(StatusCode::NO_CONTENT)
}
}
Returning StatusCode::NO_CONTENT from the form post lets the SSE stream insert the new element once for both the sender and every other connected viewer, so the page never renders duplicate rows.
Step 3. Connect HTMX SSE in your page slab
In slabs/notes/list_notes.rs, add hx-ext="sse", sse-connect="/notes/stream", and sse-swap="note_created" to the list container:
#![allow(unused)]
fn main() {
section id="notes-list"
hx-ext="sse"
sse-connect="/notes/stream"
sse-swap="note_created"
hx-swap="afterbegin"
class="space-y-2" {
@for note in ¬es {
article id=(format!("note-{}", note.id)) class="card p-3" {
p class="text-sm" { (note.body) }
p class="text-xs text-muted-foreground mt-1" { (note.created_at) }
}
}
}
}
Step 4. Morph updated regions with Idiomorph
When an event replaces a card, form, or modal body instead of appending a new row, use hx-swap="morph:innerHTML" or hx-swap="morph:outerHTML". Idiomorph diffs the incoming HTML against the live DOM and patches only changed attributes and text nodes. Open inputs keep focus and scroll positions stay put.
#![allow(unused)]
fn main() {
// Replace an existing board region in place when its columns change
ctx.realtime.publish_html(
&format!("board:{board_id}"),
"board_updated",
rendered_columns.into_string(),
);
}
In the HTML container:
#![allow(unused)]
fn main() {
div id="board-columns"
hx-ext="sse"
sse-connect=(format!("/boards/{board_id}/stream"))
sse-swap="board_updated"
hx-swap="morph:innerHTML" {
// Server-rendered columns
}
}
Step 5. Track online presence and guard WebSockets
ctx.realtime includes in-memory presence tracking for rooms, boards, and collaborative documents. Hold the returned PresenceGuard for the lifetime of the connection so the participant is removed automatically on disconnect.
#![allow(unused)]
fn main() {
use serde_json::json;
let _presence = ctx.realtime.track_presence(
&format!("room:{room_id}"),
&session.user_id,
json!({ "name": user_name }),
);
// List currently connected participants on the topic
let online: Vec<PresenceEntry> = ctx
.realtime
.list_presence(&format!("room:{room_id}"));
}
If a slab upgrades a connection to a WebSocket, validate the browser Origin header before accepting the upgrade to block Cross-Site WebSocket Hijacking (CSWSH):
#![allow(unused)]
fn main() {
use axum::http::HeaderMap;
use slabs::prelude::*;
if !validate_ws_origin(&headers, &ctx.config.cors_origins) {
return Err(SlabError::forbidden("cross-origin websocket blocked"));
}
}
validate_ws_origin requires a valid Origin header matching either the request Host or an explicit origin configured in SLABS_CORS_ORIGINS.
Step 6. Test realtime broadcasts and presence in isolation
You do not need a browser to verify SSE broadcasts or presence tracking. Subscribe to the topic on app.ctx.realtime before calling the mutation slab:
#![allow(unused)]
fn main() {
#[tokio::test]
async fn create_note_broadcasts_html_fragment() {
let app = crate::test_app().await;
let mut rx = app.ctx.realtime.subscribe("notes:global");
let res = app
.post_form("/notes", &[("body", "Broadcast test")])
.await;
assert_eq!(res.status, axum::http::StatusCode::NO_CONTENT);
let msg = rx.try_recv().expect("expected realtime message");
assert_eq!(msg.event, "note_created");
assert!(msg.data.contains("Broadcast test"));
}
}
Run mise exec -- cargo nextest run to verify the test passes, then open two browser windows side by side with slabs dev to watch notes appear live.
Write an atomic transaction with a background job
Use this guide when an HTTP endpoint must update one or more domain tables and schedule background work (email, webhooks, or audit logs) so both commit together or both roll back together.
Open a BEGIN IMMEDIATE transaction
Call ctx.db.begin().await? at the start of the write section. begin() opens a BEGIN IMMEDIATE transaction on the single-connection SQLite writer pool. Pass &mut *tx to sqlx::query and &mut tx to ctx.jobs.enqueue_in_tx.
#![allow(unused)]
fn main() {
// slabs/orders/place_order.rs
use axum::{extract::State, http::StatusCode, Json};
use axum_extra::extract::CookieJar;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_json::json;
use slabs::prelude::*;
pub fn slab() -> SlabDef {
SlabDef::post("/api/orders", handle)
.name("orders.place_order")
.summary("Create an order and enqueue a confirmation email atomically")
}
#[derive(Debug, Deserialize)]
pub struct Input {
pub sku: String,
pub quantity: i64,
}
#[derive(Debug, Serialize)]
pub struct Output {
pub order_id: String,
}
async fn handle(
State(ctx): State<AppCtx>,
jar: CookieJar,
Json(input): Json<Input>,
) -> SlabResult<(StatusCode, Json<Output>)> {
let session = ctx.auth.require_session(&jar).await?;
if input.quantity <= 0 {
return Err(SlabError::validation("quantity", "must be greater than zero"));
}
let order_id = id::new("ord");
let now = Utc::now().to_rfc3339();
let mut tx = ctx.db.begin().await?;
sqlx::query(
"INSERT INTO orders (id, user_id, sku, quantity, created_at)
VALUES (?, ?, ?, ?, ?)",
)
.bind(&order_id)
.bind(&session.user_id)
.bind(input.sku.trim())
.bind(input.quantity)
.bind(&now)
.execute(&mut *tx)
.await?;
ctx.jobs
.enqueue_in_tx(
&mut tx,
"send_order_receipt",
json!({ "order_id": order_id, "user_id": session.user_id }),
)
.await?;
tx.commit().await?;
Ok((StatusCode::CREATED, Json(Output { order_id })))
}
}
If any query fails before tx.commit().await?, SQLite rolls back both the orders insert and the slabs_jobs insert.
Guard shared edits with an Optimistic Offline Lock
When two users open the same editable record (such as a card, document, or project setting) and submit updates from separate HTTP requests, a plain UPDATE ... WHERE id = ? silently overwrites the first save. Prevent lost updates with an opt-in SQL Optimistic Offline Lock.
Add a version column to shared editable tables in your migration:
ALTER TABLE cards ADD COLUMN version INTEGER NOT NULL DEFAULT 1;
Include the client’s version in the request payload, increment it atomically inside WHERE id = ? AND version = ?, and return SlabError::conflict (409 Conflict) when rows_affected() == 0:
#![allow(unused)]
fn main() {
let mut tx = ctx.db.begin().await?;
let res = sqlx::query(
"UPDATE cards
SET title = ?, body = ?, updated_at = ?, version = version + 1
WHERE id = ? AND version = ?",
)
.bind(input.title.trim())
.bind(&input.body)
.bind(&now)
.bind(&card_id)
.bind(input.version)
.execute(&mut *tx)
.await?;
if res.rows_affected() == 0 {
return Err(SlabError::conflict(
"Card was modified by another request. Reload and retry.",
));
}
tx.commit().await?;
}
If you need to distinguish a deleted record (404 Not Found) from a stale version (409 Conflict), run a quick SELECT 1 FROM cards WHERE id = ? inside the same rows_affected() == 0 branch before choosing between SlabError::not_found and SlabError::conflict.
When not to use an Optimistic Offline Lock
Keep version checks opt-in and only on shared editable records. Skip them for:
- Append-only rows such as chat messages, events, audit logs, and ledger entries that are inserted once and never edited in place.
- Hot counters such as view counts, vote totals, or stock decrements, where an atomic
UPDATE ... SET count = count + 1 WHERE id = ?avoids unnecessary conflict retries. - CRDT real-time collaborative documents where concurrent edits merge at the character or operation level instead of rejecting whole-row saves.
Customize queue name, retries, or delay
Use enqueue_with_options_in_tx when a job needs a named queue, a custom max_attempts, or a delay in seconds:
#![allow(unused)]
fn main() {
ctx.jobs
.enqueue_with_options_in_tx(
&mut tx,
"send_order_receipt",
"mail",
json!({ "order_id": order_id }),
8, // max_attempts (default is 5)
30, // delay_seconds before eligible to run
)
.await?;
}
Failed jobs retry with exponential backoff (2^attempts seconds, capped at 1024 seconds). Once attempts >= max_attempts, the worker marks the job status as "dead".
Dispatch outbound webhooks in the same transaction
Call ctx.webhooks.dispatch_in_tx before committing when an action notifies external webhook subscribers:
#![allow(unused)]
fn main() {
ctx.webhooks
.dispatch_in_tx(
&mut tx,
&account_id,
"order.placed",
&json!({ "order_id": order_id }),
)
.await?;
}
dispatch_in_tx inserts HMAC-SHA256 signed rows into slabs_webhook_deliveries and enqueues "slabs.deliver_webhook" jobs on the "webhooks" queue inside the same transaction. During live HTTP delivery (SLABS_WEBHOOKS_LIVE=true), slabs-webhooks uses a custom SSRF-safe DNS resolver that blocks loopback, private, link-local, metadata, and IPv4-mapped IPv6 addresses at connect time, disables HTTP redirects, enforces a 10-second timeout, and caps response reads at 2 KiB.
Write the matching background job
Create jobs/send_order_receipt.rs. slabs-build discovers every .rs file in jobs/ at compile time and registers it with JobRegistry.
#![allow(unused)]
fn main() {
// jobs/send_order_receipt.rs
use serde_json::Value;
use slabs::prelude::*;
pub fn job() -> JobDef {
JobDef::new("send_order_receipt", run)
.queue("default")
.max_attempts(5)
.summary("Send an order receipt email")
}
async fn run(ctx: AppCtx, payload: Value) -> SlabResult<()> {
let order_id = payload
.get("order_id")
.and_then(|v| v.as_str())
.ok_or_else(|| SlabError::bad_request("missing order_id"))?;
let user_id = payload
.get("user_id")
.and_then(|v| v.as_str())
.ok_or_else(|| SlabError::bad_request("missing user_id"))?;
let (email,): (String,) = sqlx::query_as("SELECT email FROM users WHERE id = ?")
.bind(user_id)
.fetch_one(ctx.db.reader())
.await?;
ctx.mail
.send(Email {
from: String::new(),
to: email,
subject: format!("Order {order_id} confirmed"),
text_body: format!("Your order {order_id} is confirmed."),
html_body: None,
})
.await?;
Ok(())
}
}
Never call ctx.mail.send(...) inside an open database transaction. Mailer::send performs network I/O when Resend or SMTP is configured and writes to slabs_mail_outbox outside your transaction. Always enqueue a job inside tx and send email from the job handler.
Attach a recurring schedule
To enqueue a job on a fixed interval while the server runs, attach ScheduleDef::every in src/lib.rs:
#![allow(unused)]
fn main() {
use serde_json::json;
use slabs::{ScheduleDef, SlabsApp};
use std::time::Duration;
let app = SlabsApp::boot(config, &MIGRATOR, collect_slabs(), collect_jobs()).await?;
let app = app.with_schedules(vec![
ScheduleDef::every(Duration::from_secs(3600), "cleanup_expired", json!({})),
]);
}
Drain jobs synchronously in tests
In your co-located #[tokio::test], call app.drain_jobs().await to execute every ready queued job right away, or call app.run_job_now("job_name", payload).await to invoke one handler directly:
#![allow(unused)]
fn main() {
let processed = app.drain_jobs().await;
assert_eq!(processed, 1);
let emails = app.sent_emails().await;
assert_eq!(emails.len(), 1);
assert!(emails[0].subject.contains("confirmed"));
}
Validate multiple input fields at once
When an endpoint accepts several fields, collect all errors in one pass with Validate::new(). Calling .finish()? returns Ok(()) when every check passes or Err(SlabError::ValidationErrors(...)) (HTTP 422 Unprocessable Entity):
#![allow(unused)]
fn main() {
let mut v = Validate::new();
v.required("sku", &input.sku)
.max_len("sku", &input.sku, 64)
.email("receipt_email", &input.receipt_email)
.one_of("priority", &input.priority, &["standard", "rush"])
.check("quantity", input.quantity > 0, "must be greater than zero");
v.finish()?;
}
Validate supports required, min_len, max_len, email, url, one_of, check, push, is_empty, errors, and finish. When validation fails, Slabs responds with HTTP 422 and sorted field keys:
{
"error": "validation_error",
"fields": {
"quantity": ["must be greater than zero"],
"sku": ["is required"]
}
}
Paginate lists with keyset cursors
Avoid OFFSET scans and extra COUNT(*) queries by pairing Pagination with CursorPage::from_rows. Extract Query(page): Query<Pagination>, fetch page.fetch_limit(default, max) rows (clamped_limit + 1), and pass the Vec to CursorPage::from_rows:
#![allow(unused)]
fn main() {
use axum::{extract::{Query, State}, Json};
use serde::Serialize;
use slabs::prelude::*;
#[derive(Debug, Serialize, sqlx::FromRow)]
struct OrderRow {
id: String,
sku: String,
created_at: String,
}
async fn handle(
State(ctx): State<AppCtx>,
Query(page): Query<Pagination>,
) -> SlabResult<Json<CursorPage<OrderRow>>> {
let limit = usize::try_from(page.clamped_limit(20, 100)).unwrap_or(20);
let fetch_limit = page.fetch_limit(20, 100);
let rows: Vec<OrderRow> = if let Some(cursor) = &page.cursor {
sqlx::query_as(
"SELECT id, sku, created_at FROM orders
WHERE id < ?
ORDER BY id DESC
LIMIT ?",
)
.bind(cursor)
.bind(fetch_limit)
.fetch_all(ctx.db.reader())
.await?
} else {
sqlx::query_as(
"SELECT id, sku, created_at FROM orders
ORDER BY id DESC
LIMIT ?",
)
.bind(fetch_limit)
.fetch_all(ctx.db.reader())
.await?
};
let result = CursorPage::from_rows(rows, limit, |row| row.id.clone());
Ok(Json(result))
}
}
CursorPage::from_rows truncates rows to limit, sets has_more to true when the extra row existed, and sets next_cursor from the last retained row (or None on the final page).
Record transactional audit logs
Call ctx.audit.record_in_tx inside an open transaction to write an immutable entry into slabs_audit_log atomically with your domain update. If the transaction rolls back, the audit row rolls back too.
#![allow(unused)]
fn main() {
let mut tx = ctx.db.begin().await?;
sqlx::query("UPDATE rooms SET archived_at = ? WHERE id = ?")
.bind(&now)
.bind(&room_id)
.execute(&mut *tx)
.await?;
ctx.audit
.record_in_tx(
&mut tx,
Some(&session.user_id),
"room.archived",
"room",
&room_id,
&json!({ "reason": input.reason }),
)
.await?;
tx.commit().await?;
}
record_in_tx returns the generated aud_<ulid> ID. Read audit history on the read pool with ctx.audit.list_for_target("room", &room_id, 50).await? or ctx.audit.list_recent(50).await?. Both return Vec<AuditEntry>.
Verify inbound webhooks and block replays
When your app receives webhooks from external providers (such as Stripe, GitHub, or another Slabs app), verify the raw request bytes before parsing JSON, check the timestamp window, and claim an idempotency key inside the same database transaction as your domain update:
#![allow(unused)]
fn main() {
use axum::{
body::Bytes,
extract::State,
http::{HeaderMap, StatusCode},
};
use slabs::{prelude::*, webhooks::Webhooks};
async fn handle(
State(ctx): State<AppCtx>,
headers: HeaderMap,
body: Bytes,
) -> SlabResult<StatusCode> {
let secret = std::env::var("PROVIDER_WEBHOOK_SECRET")
.map_err(|_| SlabError::internal("missing PROVIDER_WEBHOOK_SECRET"))?;
let sig = headers
.get("x-provider-signature")
.and_then(|v| v.to_str().ok())
.ok_or_else(|| SlabError::unauthorized("missing signature"))?;
if !Webhooks::verify_incoming_hmac_sha256(&secret, &body, sig, "sha256=") {
return Err(SlabError::unauthorized("invalid webhook signature"));
}
let ts: i64 = headers
.get("x-provider-timestamp")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse().ok())
.ok_or_else(|| SlabError::unauthorized("missing timestamp"))?;
if !Webhooks::verify_timestamp_window(ts, 300) {
return Err(SlabError::unauthorized("stale webhook timestamp"));
}
let event: serde_json::Value = serde_json::from_slice(&body)
.map_err(|_| SlabError::bad_request("invalid JSON payload"))?;
let event_id = event["id"]
.as_str()
.ok_or_else(|| SlabError::bad_request("missing event id"))?;
let mut tx = ctx.db.begin().await?;
let claimed = ctx
.webhooks
.claim_idempotency_in_tx(&mut tx, "provider", event_id)
.await?;
if !claimed {
tx.commit().await?;
return Ok(StatusCode::OK);
}
// Apply domain updates and enqueue jobs inside `tx`...
tx.commit().await?;
Ok(StatusCode::OK)
}
}
Pass "" as the prefix argument to verify_incoming_hmac_sha256 when a provider sends a raw hex digest without "sha256=". claim_idempotency_in_tx runs INSERT OR IGNORE INTO slabs_idempotency_keys on tx. It returns Ok(true) on the first claim and Ok(false) on replays. If tx rolls back before commit, the key is released so the provider can retry cleanly.
Authenticate with sessions, magic links, and Bearer tokens
Slabs puts explicit authentication helpers on ctx.auth and fixed-window rate limiting on ctx.rate_limit. Authentication never hides in route-group middleware. You call the exact guard you need on line 1 of each slab handler.
Choose an authentication guard
| Guard | Accepts | On failure |
|---|---|---|
ctx.auth.optional_session(&jar).await? | Active session cookie | Returns Ok(None) |
ctx.auth.require_session(&jar).await? | Valid session cookie | HTTP 401 Unauthorized |
ctx.auth.require_admin(&jar).await? | Valid session with role == "admin" | HTTP 401 or HTTP 403 Forbidden |
ctx.auth.optional_auth(&jar, &headers).await? | Authorization: Bearer token or session cookie | Returns Ok(None) |
ctx.auth.require_auth(&jar, &headers).await? | Valid Bearer token or session cookie | HTTP 401 Unauthorized |
ctx.auth.require_write_auth(&jar, &headers).await? | Valid Bearer token (permission == "write") or session | HTTP 401 or HTTP 403 Forbidden |
When a request includes an Authorization: Bearer ... header, optional_auth, require_auth, and require_write_auth validate only that Bearer token. They never fall back to the session cookie if the Bearer token is invalid.
When cookie_secure is true (the default in staging and production), Slabs names the session cookie __Host-slabs_session (Path=/, Secure, HttpOnly, SameSite=Lax, no Domain attribute). In local development over HTTP (cookie_secure == false), the cookie name is slabs_session.
Hash and verify passwords asynchronously with Argon2id
Your application owns its users table in migrations/. ctx.auth.hash_password, ctx.auth.verify_password, and ctx.auth.verify_password_constant_time are async functions. They offload Argon2id onto tokio::task::spawn_blocking with a concurrency semaphore and a 1024-byte password cap so slow hashes never block the async runtime.
Create a user and session cookie atomically inside one transaction:
#![allow(unused)]
fn main() {
use axum::{extract::State, http::StatusCode, Json};
use axum_extra::extract::CookieJar;
use chrono::Utc;
use serde::Deserialize;
use slabs::prelude::*;
#[derive(Debug, Deserialize)]
pub struct SignUpInput {
pub email: String,
pub password: String,
}
async fn handle(
State(ctx): State<AppCtx>,
jar: CookieJar,
Json(input): Json<SignUpInput>,
) -> SlabResult<(StatusCode, CookieJar)> {
let email = input.email.trim().to_lowercase();
ctx.rate_limit.check(&format!("auth:signup:{email}"), 5, 300)?;
let user_id = id::new("usr");
let password_hash = ctx.auth.hash_password(&input.password).await?;
let now = Utc::now().to_rfc3339();
let mut tx = ctx.db.begin().await?;
sqlx::query(
"INSERT INTO users (id, email, password_hash, role, created_at)
VALUES (?, ?, ?, 'member', ?)",
)
.bind(&user_id)
.bind(&email)
.bind(&password_hash)
.bind(&now)
.execute(&mut *tx)
.await?;
let (_session, cookie) = ctx
.auth
.create_session_in_tx(&mut tx, &user_id, "member", 30)
.await?;
tx.commit().await?;
Ok((StatusCode::CREATED, jar.add(cookie)))
}
}
During sign-in, prefer ctx.auth.verify_password_constant_time(&input.password, stored_hash.as_deref()).await?. When stored_hash is None, it still runs an Argon2id check against a dummy hash so callers cannot measure response timing to enumerate registered emails. To verify against a known hash directly, call ctx.auth.verify_password(&input.password, &stored_hash).await?. To sign out, call let clear = ctx.auth.destroy_session(&jar).await?; and return jar.add(clear).
Sign in with single-use 6-character magic links
issue_magic_link generates a 6-character code from an unambiguous alphabet (omitting 0, O, 1, and I) and stores only a keyed domain-separated HMAC bound to (email, purpose) in slabs_magic_links:
#![allow(unused)]
fn main() {
// Step 1: Issue code and send email
ctx.rate_limit.check(&format!("magic:req:{email}"), 5, 300)?;
let issued = ctx.auth.issue_magic_link(&email, "sign_in", 15).await?;
ctx.mail
.send(Email {
from: String::new(),
to: issued.email.clone(),
subject: "Your sign-in code".into(),
text_body: format!("Enter code {} within 15 minutes.", issued.code),
html_body: None,
})
.await?;
}
When the user submits the code, pass email, purpose, and the submitted code to consume_magic_link. It strips non-alphanumeric characters, uppercases the code, verifies the keyed HMAC for (email, purpose), and executes DELETE ... RETURNING so every code works at most once. After 5 failed attempts within 15 minutes for the same (email, purpose), Slabs locks out the pair and deletes any pending codes.
#![allow(unused)]
fn main() {
// Step 2: Consume code atomically and start a session
ctx.rate_limit.check(&format!("magic:consume:{email}"), 20, 60)?;
let consumed = ctx
.auth
.consume_magic_link(&email, "sign_in", &input.code)
.await?
.ok_or_else(|| SlabError::unauthorized("invalid or expired code"))?;
// Look up or create the user for consumed.email, then create a session:
let (_session, cookie) = ctx.auth.create_session(&user_id, &role, 30).await?;
Ok((StatusCode::OK, jar.add(cookie)))
}
Issue and verify personal Bearer access tokens
Personal access tokens let CLIs, scripts, and AI agents call your endpoints without browser cookies. Tokens start with slb_ and are stored only as SHA-256 digests in slabs_access_tokens.
#![allow(unused)]
fn main() {
// Require a browser session to mint a new token
let session = ctx.auth.require_session(&jar).await?;
let issued = ctx
.auth
.issue_access_token(&session.user_id, &session.role, "CI deploy script", "write")
.await?;
// Return `issued.token` once; plaintext tokens cannot be recovered later.
}
Protect API slabs with require_auth (read or write) or require_write_auth (requires permission == "write"):
#![allow(unused)]
fn main() {
async fn handle(
State(ctx): State<AppCtx>,
jar: CookieJar,
headers: axum::http::HeaderMap,
) -> SlabResult<axum::Json<serde_json::Value>> {
let principal = ctx.auth.require_write_auth(&jar, &headers).await?;
Ok(axum::Json(serde_json::json!({
"user_id": principal.user_id,
"auth_kind": principal.auth_kind,
"permission": principal.permission,
})))
}
}
Rely on built-in CSRF, CORS, safe redirects, and safe blob responses
Slabs ships defense-in-depth protections enabled by default in slabs-http, slabs-html, and slabs-storage:
- Fetch Metadata and Origin CSRF middleware runs on every cookie-authenticated
POST,PUT,PATCH, andDELETErequest (controlled bySLABS_CSRF_ENFORCE, defaulttrue). It rejects requests withSec-Fetch-Site: cross-siteand checksOriginagainst the requestHostorSLABS_CORS_ORIGINS. Requests authenticated withAuthorization: Bearerand inbound webhook paths (/webhooks*,/api/webhooks*) are exempt. - Cross-origin CORS stays disabled unless you set a comma-separated allowlist in
SLABS_CORS_ORIGINS. - For explicit double-submit form tokens, call
html::csrf_token(&ctx.auth, &session.id)when rendering andhtml::verify_csrf(&ctx.auth, &session.id, &form.csrf_token)?on submission. htmx::redirect(path)andhtmx::flash_redirect(...)validate thatpathis a safe relative path and fall back to"/"on open-redirect inputs such as//evil.com. For deliberate external URLs, callredirect_external(url)explicitly.json_script("boot-data", &payload)?renders<script type="application/json">with<,>,&, U+2028, and U+2029 escaped so user data cannot break out of the script tag.BlobMeta::into_safe_response(bytes, allow_inline_passive)setsX-Content-Type-Options: nosniff,Content-Security-Policy: default-src 'none'; sandbox, and forcesContent-Disposition: attachmentfor active file types such asimage/svg+xmlandtext/html.
Mint and verify purpose-bound signed tokens
Use ctx.auth.sign_token and ctx.auth.verify_token for stateless, expiring tokens such as password resets, email verification links, and signed blob download URLs. sign_token encodes {"p": purpose, "exp": unix_ts, "d": payload} as unpadded URL-safe base64 and appends .<hex_hmac_sig> signed with SLABS_SECRET_KEY.
Because purpose sits inside the signed envelope, a token minted for "email_verify" fails verification on "password_reset" or "blob_download". verify_token returns HTTP 401 Unauthorized when the format, HMAC signature, payload shape, purpose, or expiration check fails.
#![allow(unused)]
fn main() {
use serde::{Deserialize, Serialize};
use std::time::Duration;
#[derive(Debug, Serialize, Deserialize)]
struct ResetClaims {
user_id: String,
}
// Issue a 15-minute password reset token
let token = ctx.auth.sign_token(
"password_reset",
&ResetClaims { user_id: user.id.clone() },
Duration::from_secs(900),
)?;
// Verify on submission
let claims: ResetClaims = ctx.auth.verify_token("password_reset", &input.token)?;
}
You can pair the same token flow with BlobMeta::into_safe_response for time-limited downloads:
#![allow(unused)]
fn main() {
let signed_blob_id: String = ctx.auth.verify_token("blob_download", &query.token)?;
if signed_blob_id != path_blob_id {
return Err(SlabError::unauthorized("token does not match blob"));
}
let (meta, bytes) = ctx
.storage
.get(&path_blob_id)
.await?
.ok_or_else(|| SlabError::not_found("blob not found"))?;
Ok(meta.into_safe_response(bytes, true))
}
When you need signing or verification without a database handle (such as in unit tests), construct a stateless handle with Auth::for_signing(secret_key, cookie_secure).
Show one-shot flash banners across redirects
Use Flash, htmx::flash_redirect, htmx::take_flash, and html::flash_banner to carry feedback messages across POST-redirect-GET flows without storing UI state in SQLite.
Flash has four constructors (Flash::success, Flash::info, Flash::warning, Flash::error). Slabs serializes the message into an HMAC-signed slabs_flash cookie (HttpOnly, SameSite=Lax, Path=/, Max-Age=60, and Secure when cookie_secure is true).
In your mutation slab, return htmx::flash_redirect. It sets the signed cookie and responds with HTTP 303 See Other carrying both Location and HX-Redirect, so plain form posts and HTMX requests follow the redirect identically:
#![allow(unused)]
fn main() {
// slabs/settings/update_profile.rs
async fn handle(
State(ctx): State<AppCtx>,
jar: CookieJar,
Form(input): Form<ProfileForm>,
) -> SlabResult<axum::response::Response> {
let session = ctx.auth.require_session(&jar).await?;
// ... update profile in SQLite ...
Ok(htmx::flash_redirect(
&ctx.auth,
jar,
"/settings",
&Flash::success("Profile updated."),
))
}
}
In the destination GET slab, call htmx::take_flash(&ctx.auth, jar) to verify and clear the cookie in one step, render html::flash_banner(flash.as_ref()), and return the updated jar alongside your page:
#![allow(unused)]
fn main() {
// slabs/settings/show_settings.rs
async fn handle(
State(ctx): State<AppCtx>,
jar: CookieJar,
) -> SlabResult<(CookieJar, Markup)> {
let _session = ctx.auth.require_session(&jar).await?;
let (jar, flash) = htmx::take_flash(&ctx.auth, jar);
let page = html::document(
"Settings",
&ctx.assets.stylesheet_urls(),
&[],
maud! {
main class="mx-auto max-w-2xl p-6 space-y-4" {
(html::flash_banner(flash.as_ref()))
h1 { "Settings" }
}
},
);
Ok((jar, page))
}
}
html::flash_banner renders a Basecoat <div class="alert" role="status"> (with data-variant="destructive" for FlashKind::Error) when flash is Some, or empty markup when None. Tampered or expired cookies are discarded silently.
Enforce rate limits with proxy-aware client IPs
Call ctx.rate_limit.check(key, max_requests, window_secs)? at the top of any sensitive handler. When a key exceeds max_requests within window_secs, Slabs returns HTTP 429 Too Many Requests with a Retry-After header and JSON error body.
For unauthenticated endpoints such as login or password reset, extract the caller IP with client_ip(&headers, peer, ctx.config.trust_proxy):
#![allow(unused)]
fn main() {
use axum::extract::ConnectInfo;
use std::net::SocketAddr;
let ip = client_ip(&headers, Some(peer), ctx.config.trust_proxy);
ctx.rate_limit.check(&format!("auth:signin:{ip}"), 10, 300)?;
}
When SLABS_TRUST_PROXY=false (the default), client_ip ignores forwarding headers and uses the socket peer address so callers cannot spoof X-Forwarded-For. When SLABS_TRUST_PROXY=true behind a trusted reverse proxy (such as kamal-proxy, Fly Proxy, or Caddy), client_ip reads CF-Connecting-IP, Fly-Client-IP, or the rightmost valid IP in X-Forwarded-For.
RateLimiter stores fixed-window counters in process memory (capped at 50,000 entries) and prunes expired keys every 5 seconds.
Verify raw SQL at compile time and connect PostgreSQL
Slabs endpoints use runtime-bound sqlx::query and sqlx::query_as calls by default so every file compiles without a running database. When you want compile-time SQL type and column verification, generate offline .sqlx/ metadata with slabs db prepare. When you need a networked PostgreSQL database alongside or instead of SQLite, connect with slabs_db::PgDb.
Enable compile-time SQL checks with slabs db prepare
1. Enable the macros feature on sqlx
In your app’s Cargo.toml, add "macros" to the sqlx feature list:
sqlx = { version = "0.8", default-features = false, features = [
"runtime-tokio",
"tls-rustls",
"sqlite",
"migrate",
"chrono",
"json",
"macros",
] }
2. Write checked queries in your slab
Use sqlx::query! or sqlx::query_as! against ctx.db.reader() or &mut *tx:
#![allow(unused)]
fn main() {
let row = sqlx::query!(
"SELECT id, title FROM doc_pages WHERE section = ? AND slug = ?",
section,
slug,
)
.fetch_optional(ctx.db.reader())
.await?;
}
3. Generate offline .sqlx/ metadata
Run slabs db prepare. When DATABASE_URL is omitted, slabs db prepare creates a temporary SQLite file, runs Db::init_system_tables() and your migrations/ directory, executes cargo sqlx prepare, and deletes the temporary file:
slabs db prepare
To target a specific package or live database:
slabs --app-dir examples/fizzy db prepare --package fizzy
DATABASE_URL="postgres://user:pass@localhost:5432/app" slabs db prepare
Commit the generated .sqlx/ directory to git. During CI builds (SQLX_OFFLINE=true), rustc verifies every sqlx::query! call against .sqlx/ without a database connection.
Migrate and dump a PostgreSQL database
slabs-cli detects the engine automatically via DbEngine::detect(database_url). URLs starting with postgres:// or postgresql:// route to PgDb:
DATABASE_URL="postgres://user:pass@localhost:5432/mydb" slabs db migrate
DATABASE_URL="postgres://user:pass@localhost:5432/mydb" slabs db dump-schema
PgDb::migrate applies POSTGRES_SYSTEM_SCHEMA_SQL (creating all eleven slabs_* system tables with TIMESTAMPTZ, JSONB, BIGINT, and BOOLEAN columns) before running your SQL files in migrations/. PgDb::dump_schema_sql exports all public tables and indexes from information_schema.columns and pg_indexes. It skips internal _sqlx_% tables.
Connect PgDb in Rust
AppCtx.db is SQLite (slabs_db::Db). To query a standalone PostgreSQL database from Rust code, use slabs::db::PgDb:
#![allow(unused)]
fn main() {
use slabs::db::PgDb;
use slabs::SlabResult;
async fn load_accounts(database_url: &str) -> SlabResult<Vec<(String, String)>> {
let pg = PgDb::connect(database_url).await?;
pg.init_system_tables().await?;
let rows: Vec<(String, String)> = sqlx::query_as(
"SELECT id, email FROM accounts ORDER BY created_at DESC LIMIT 50",
)
.fetch_all(pg.pool())
.await?;
Ok(rows)
}
}
PgDb::connect configures a PgPool with up to 20 connections and a 5-second acquire timeout. Open transactions with let mut tx = pg.begin().await?; and verify connectivity with pg.ping().await?.
Escape FTS5 search queries safely
On SQLite FTS5 tables, never pass raw user input directly to MATCH ?. Characters like unmatched quotes, AND, NOT, or column prefixes (title:foo) cause SQLite syntax errors. Pass input through slabs::db::fts5_query:
#![allow(unused)]
fn main() {
if let Some(expr) = slabs::db::fts5_query(user_input) {
let rows: Vec<SearchRow> = sqlx::query_as(
"SELECT p.slug, p.title
FROM doc_pages_fts fts
JOIN doc_pages p ON p.slug = fts.slug
WHERE doc_pages_fts MATCH ?
ORDER BY bm25(doc_pages_fts)
LIMIT 20",
)
.bind(&expr)
.fetch_all(ctx.db.reader())
.await?;
}
}
fts5_query strips double quotes, splits on whitespace, wraps each token as "token"*, and joins them with AND. Blank input returns None.
Use Slabs agent skills in your workflow
Pair always-on repository rules in AGENTS.md and CLAUDE.md with the five procedural skills in skills/. Every new project created by slabs new app bundles all five skills under .claude/skills/.
Why static rules live in AGENTS.md and CLAUDE.md
Coding agents load AGENTS.md (and Claude Code loads CLAUDE.md) at the start of every session. Keep short repository invariants in AGENTS.md and point CLAUDE.md at it with one line:
@AGENTS.md
This keeps one source of truth across coding tools with no duplicated instructions. Reserve AGENTS.md for rules that apply to every edit:
- One endpoint per file under
slabs/<feature>/<action>.rsand one background job per file underjobs/<name>.rs. - No
models/,controllers/,repositories/,services/, or centralroutes.rs. - Pool selection (
ctx.db.reader()for reads,ctx.db.begin().await?for multi-step writes) and parameterized SQL. - Explicit line-1 auth and rate-limit guards, safe Markdown rendering (
html::render_markdown), and verification commands (slabs doctor,slabs check).
Multi-step procedures do not belong in AGENTS.md. Putting long checklists into the root file inflates every session prompt even when an agent is doing unrelated work. Move repeatable workflows into focused SKILL.md files that agents load on demand.
The five Slabs agent skills
The Slabs repository ships five skills under skills/, and slabs new app copies all five into .claude/skills/:
| Skill file | When to use it | What it enforces |
|---|---|---|
skills/add-slab/SKILL.md | Adding a new HTTP endpoint, HTML page, or HTMX fragment handler. | Inspect schema.sql, create slabs/<feature>/<action>.rs with Axum 0.8 {param} syntax, put auth and rate-limit guards on line 1, use ctx.db.reader() or BEGIN IMMEDIATE transactions, enqueue jobs and webhooks inside tx, render user Markdown with html::render_markdown, write co-located tests, and run slabs css and slabs check. |
skills/add-migration/SKILL.md | Adding or changing SQLite or PostgreSQL tables, columns, indexes, or FTS5 tables. | Create a numbered migrations/<NNNN>_<description>.sql without editing applied migrations, follow expand-and-contract safety, avoid colliding with the twelve slabs_* system tables, run slabs db migrate and slabs db dump-schema to refresh schema.sql, update .sqlx/ with slabs db prepare when using macros, and run cargo nextest run. |
skills/review-slab/SKILL.md | Auditing a pull request or completed feature before merging. | Check for stray MVC folders or src/lib.rs route edits, leading _ prefixes on helper files, Axum 0.8 syntax, ctx.db.reader() vs BEGIN IMMEDIATE, parameterized binds, fts5_query escaping, atomic job enqueues instead of in-tx ctx.mail.send, line-1 auth and rate limits, html::render_markdown, BlobMeta::into_safe_response, json_script, fingerprint checks on optimistic updates, co-located tests, and slabs check. |
skills/deploy-app/SKILL.md | Shipping a release or rolling back a production deploy on Kamal 2, Fly.io, or a Linux VPS. | Run slabs doctor, slabs check --no-docs, and slabs css, generate configs with slabs deploy init --db sqlite|postgres, verify SLABS_ENV=production and a 32-byte SLABS_SECRET_KEY, confirm expand-and-contract migrations, take a pre-deploy SQLite or Litestream backup, tag Docker images with an immutable git SHA, respect SQLite single-writer rollout limits and PRAGMA wal_checkpoint(TRUNCATE) drain, check /health/ready and /_slabs/metrics, and keep rollback commands ready. |
skills/fix-incident/SKILL.md | Triaging and fixing active (open or reopened) runtime errors, slow routes, slow jobs, or user bug reports from slabs_incidents. | Pull slabs incidents list --json and slabs incidents perf --json, inspect slabs incidents show <id> (including its repro_test skeleton and recent_occurrences_json), read only the reported source_file and schema.sql, write a failing co-located test (using Db::explain_query_plan for slow queries), fix the bug, run slabs check, and resolve with slabs incidents resolve <id> --sha <sha>. See Track incidents, bug reports, and performance. |
Use skills in an existing Slabs app
- Keep
AGENTS.mdat your application root with your commands, schema notes, and architecture rules. - Add
CLAUDE.mdat your application root containing@AGENTS.md. - Copy
skills/add-slab/,skills/add-migration/,skills/review-slab/,skills/deploy-app/, andskills/fix-incident/fromsogamoso/slabsinto.claude/skills/(or link them into your agent’s global skills folder) so every agent follows the same build, migration, review, deployment, and incident-triage procedures.
Keep skills focused as your app grows
Add a new skill only for a repeatable, multi-step procedure with clear verification commands (such as adding a billing webhook or rotating keys). Keep each SKILL.md short, concrete, and scoped to one task. Move one-line rules that apply to every edit back into AGENTS.md.
Track incidents, bug reports, and performance
Slabs captures runtime crashes, dead-letter jobs, slow routes, slow jobs, and user bug reports into one SQLite or PostgreSQL table (slabs_incidents) with zero external services. Every record maps 1-to-1 to a single source_file (slabs/<feature>/<action>.rs or jobs/<name>.rs), and every matching tracing log event includes a structured slab_file field so humans and coding agents jump straight to the owning Transaction Script.
Active failures inbox (slabs_incidents / slabs.incident.v1)
Every runtime signal writes to slabs_incidents using the slabs.incident.v1 schema:
| Category | kind values | Trigger |
|---|---|---|
| Runtime crashes | http_5xx, panic, job_dead | Unhandled 5xx response, caught handler panic, or dead-lettered background job (including jobs dead-lettered after invalid JSON payloads). |
| Performance bottlenecks | slow_request, slow_job | HTTP request or background job exceeding its millisecond latency threshold. |
| User bug reports | user_bug_report | Submitted by your application’s own slabs/support/report_bug.rs slab generated with slabs new bug-report. |
Each incident hashes its kind, source_file, route, and normalized error into a deterministic fingerprint and moves through three lifecycle states (open, resolved, and reopened):
| Status | Meaning | Next transitions |
|---|---|---|
open | New active failure awaiting a fix. | resolved (manual resolve or stale auto-close) |
resolved | Fixed and optionally tagged with resolved_in_sha, or closed after the stale inactivity window. | reopened (if the same fingerprint fires again) |
reopened | Previously resolved failure that recurred on a later request or job run. | resolved (manual resolve or stale auto-close) |
Deduplication and auto-close rules keep the inbox focused on live failures:
- Repeating an
openorreopenedincident incrementsoccurrences, updateslast_seen_at, and appends torecent_occurrences_jsonwithout creating duplicate rows or sending repeat webhooks. - Repeating a
resolvedincident transitions it toreopened, clearsresolved_in_sha, incrementsoccurrences, updateslast_seen_at, and emits anincident.reopenedwebhook. - Querying with
status=active(the default) returns bothopenandreopenedrows ordered bylast_seen_at DESC. - Stale auto-close transitions any
openorreopenedincident with no new hits forSLABS_INCIDENT_STALE_DAYSdays (default30; set0to disable) toresolved. - Every row stores
source_file,route_pattern,git_sha,context_json,detail,repro_hint, andrecent_occurrences_json. - Structured
tracinglogs tag HTTP failures, panics, slow routes, and job errors withslab_file = "<source_file>"so log aggregation andslabs_incidentsshare the same file key.
Pinpoint regressions with recent occurrence history
Each incident stores a capped 10-entry JSON ring buffer in recent_occurrences_json. Whenever a matching fingerprint fires, Slabs appends an entry with four fields and drops the oldest entry once the list exceeds 10 items:
[
{
"seen_at": "2026-12-03T01:12:08.412019Z",
"git_sha": "8a4f2c1",
"request_id": "req_01JXYZ9A2B3C4D5E6F7G8H9J0K",
"latency_ms": 642
}
]
Reading recent_occurrences_json shows the exact deploy git_sha where a crash or latency regression started, along with the request_id and latency_ms of the last 10 hits.
Scaffold a user-owned bug report slab
Slabs does not ship a framework widget or client JavaScript bundle for bug reporting. Instead, generate a self-contained, user-owned slab inside your own repository:
slabs new bug-report
This command creates slabs/support/report_bug.rs without editing any existing file. Because the file lives in your slabs/ directory, slabs-build discovers it at compile time and you control its route, authentication guard, styling, and tests:
- Renders a zero-JS HTML/HTMX multipart form accepting a bug description and up to 3 image, video, or file attachments.
- Stores uploaded attachments safely with
ctx.storage.put_scoped("bug_report", ...)so each blob is scoped to bug reports and served with sandboxed headers. - Captures the authenticated
user_idon the server, a sanitizedRefererpath, and theUser-Agentheader without trusting client-supplied identity fields. - Records a
user_bug_reportincident directly intoctx.incidentswith the stored attachment blob IDs attached to the incident payload. - Includes co-located
#[cfg(test)] mod testsverifying form validation, attachment uploads, and incident persistence.
Measure per-route performance and catch query scans
1. Inspect fixed-bucket latency histograms at /_slabs/metrics
Slabs tracks request counts, 5xx counts, slow request counts, and fixed-bucket p50, p95, and p99 latency histograms per route, mapped directly to source_file. Request Prometheus text format by default, or pass Accept: application/json for structured JSON:
curl -H "Authorization: Bearer $SLABS_METRICS_TOKEN" \
-H "Accept: application/json" \
https://app.example.com/_slabs/metrics
Tune slow-operation and stale-incident thresholds with environment variables:
| Variable | Default | Effect |
|---|---|---|
SLABS_SLOW_REQUEST_MS | 500 | Records a slow_request incident when a non-streaming HTTP request meets or exceeds this duration in milliseconds. Excludes /_slabs/*, SSE, and WebSocket upgrades. |
SLABS_SLOW_JOB_MS | 5000 | Records a slow_job incident when a background job meets or exceeds this duration in milliseconds. |
SLABS_INCIDENT_STALE_DAYS | 30 | Auto-resolves open and reopened incidents with no occurrences for this many days. Set to 0 to disable stale auto-close. |
2. Assert indexed query plans in co-located tests
Call Db::explain_query_plan inside a slab’s #[cfg(test)] mod tests block to run SQLite EXPLAIN QUERY PLAN against a read-only SELECT or WITH statement and fail CI if a query regresses to a full table SCAN:
#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
#[tokio::test]
async fn messages_query_uses_room_index() {
let app = crate::test_app().await;
let plan = app
.ctx
.db
.explain_query_plan(
"SELECT id, body FROM messages WHERE room_id = 'room_1' ORDER BY created_at DESC LIMIT 50",
)
.await
.unwrap();
assert!(
plan.iter().any(|line| line.contains("USING INDEX")),
"expected indexed lookup, got plan: {plan:?}"
);
assert!(
!plan.iter().any(|line| line.starts_with("SCAN ")),
"unexpected full table scan: {plan:?}"
);
}
}
}
Consume incidents over HTTP, webhooks, and the CLI
1. Four-endpoint Bearer-protected HTTP API
Slabs exposes four JSON and blob endpoints under /_slabs/incidents, protected by a constant-time Authorization: Bearer $SLABS_METRICS_TOKEN check (in staging and production, these routes return 404 when SLABS_METRICS_TOKEN is unset):
| Method | Path | Behavior |
|---|---|---|
GET | /_slabs/incidents?status=active|open|reopened|resolved|all&limit=50 | Lists incidents ordered by last_seen_at DESC. Defaults to status=active (open plus reopened). |
GET | /_slabs/incidents/{id} | Returns one incident’s full metadata, source_file, context_json, recent_occurrences_json, attachment IDs, and a ready-to-paste repro_test Rust test skeleton. |
GET | /_slabs/incidents/{id}/attachments/{blob_id} | Streams a scoped bug-report attachment blob stored for that incident with safe download headers. |
POST | /_slabs/incidents/{id}/resolve | Transitions the incident to resolved with an optional JSON body {"resolved_in_sha": "<git_sha>"}. |
# List active (open and reopened) incidents
curl -H "Authorization: Bearer $SLABS_METRICS_TOKEN" \
"https://app.example.com/_slabs/incidents?status=active"
# Fetch one incident plus its ready-to-paste repro_test skeleton
curl -H "Authorization: Bearer $SLABS_METRICS_TOKEN" \
https://app.example.com/_slabs/incidents/inc_01JXYZ...
# Resolve after deploying the fix
curl -X POST \
-H "Authorization: Bearer $SLABS_METRICS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"resolved_in_sha":"8a4f2c1"}' \
https://app.example.com/_slabs/incidents/inc_01JXYZ.../resolve
2. Signed slabs.incident.v1 webhooks
Forward incident lifecycle transitions to Linear, Jira, GitHub Issues, or an automated agent trigger by setting two environment variables:
export SLABS_INCIDENT_WEBHOOK_URL="https://hooks.example.com/slabs-incidents"
export SLABS_INCIDENT_WEBHOOK_SECRET="replace-with-a-random-32-byte-secret"
Slabs sends an SSRF-validated POST request only on state transitions (incident.opened, incident.reopened, and incident.resolved), skipping noisy occurrence increments on already-active incidents:
X-Slabs-Protocol: slabs.incident.v1X-Slabs-Event: incident.opened | incident.reopened | incident.resolvedX-Slabs-Signature: sha256=<hmac-sha256-hex>(sent whenSLABS_INCIDENT_WEBHOOK_SECRETis set)
Downstream receivers can key external issues by the deterministic fingerprint field so Linear, Jira, or GitHub Issues update the same ticket when an incident reopens or resolves.
3. CLI commands and skills/fix-incident/SKILL.md
Engineers, CI scripts, and coding agents can inspect and resolve incidents from the terminal using SLABS_URL and SLABS_METRICS_TOKEN (or --url and --token):
# List active (open and reopened) incidents
slabs incidents list --json
# Filter by a specific status (active, open, reopened, resolved, or all)
slabs incidents list --status reopened --limit 20
# Inspect per-route p50/p95/p99 latency, job queue stats, and active incident count
slabs incidents perf --json
# Read full metadata, source_file, recent_occurrences_json, and the repro_test skeleton
slabs incidents show inc_01JXYZ...
# Mark an incident resolved after deploying the fix
slabs incidents resolve inc_01JXYZ... --sha 8a4f2c1
Pair these commands with skills/fix-incident/SKILL.md so a coding agent pulls the active inbox with slabs incidents list --json, inspects slabs incidents show <id>, opens only source_file and schema.sql, pastes and completes the repro_test regression test, implements the fix, runs slabs check, and calls slabs incidents resolve <id> --sha <sha>.
Format, lint, and test Slabs apps in CI
Run formatting, static security scanning, Clippy, Rustdoc, and parallel tests locally and in GitHub Actions without missing auto-discovered slab files.
Run the 6-step slabs check gate
In v0.5.0, slabs check runs the complete verification pipeline in one command:
slabs check
# Or skip Rustdoc checks in an application repo:
slabs check --no-docs
slabs check executes six stages in order:
- Formatting check (
cargo fmt --all -- --checkplusrustfmt --edition 2021 --checkacross discoveredslabs/andjobs/files). - Static
[security]scanner across the workspace (auto-discovered throughcargo metadata). cargo clippy --all-targets -- -D warnings.RUSTDOCFLAGS="-D warnings" cargo doc --no-deps(unless--no-docsis passed).cargo test --doc.cargo nextest run(falling back tocargo testwhencargo-nextestis not installed).
What the [security] static scanner checks
Every slabs check and slabs doctor run inspects your crate and discovered slab files for six classes of bugs:
- String interpolation or
format!(insidesqlx::query*calls. - Unannotated
PreEscaped(HTML escapes without an explicit safety justification. unsafeblocks or missingunsafe_code = "forbid"inCargo.toml.- Hardcoded secrets or default keys in source files.
.unwrap()or.expect(in production handler code underslabs/andjobs/(outside#[cfg(test)]).- Slab files under
slabs/that have no co-located#[cfg(test)]module.
Run targeted checks on changed or single slabs
During active development, you do not need to wait for the full workspace suite after every edit. Target only the slabs you touched with --changed or --slab:
# Check only slabs modified since HEAD (or against a specific git ref)
slabs check --changed
slabs check --changed --base origin/main
# Check a single slab by <feature>/<action>
slabs check --slab rooms/create_room
Targeted mode runs formatting, the [security] static scanner, and cargo-nextest (or cargo test) scoped exclusively to the selected slab(s). That gives humans and parallel AI agents a sub-second feedback loop while iterating. Run the full slabs check gate before merging.
Catch full-table scans with slabs check --explain
Missing indexes hide inside passing unit tests because test tables hold only a few rows. Audit every static query plan before merge with --explain or --strict-explain:
# Warn on unintended full-table SCANs
slabs check --explain
# Fail CI if any unannotated full-table SCAN is found
slabs check --strict-explain
slabs check --explain boots an in-memory SQLite database from migrations/ (or schema.sql), extracts static SELECT and WITH queries from slabs/ and jobs/, runs EXPLAIN QUERY PLAN on each query, and reports any unintended full-table SCAN.
When a full-table scan is deliberate (such as reading a ten-row settings table or running a bounded admin export), document the reason directly above the query with an inline opt-out comment:
#![allow(unused)]
fn main() {
// slabs:allow-scan: lookup table holds fewer than 20 static plan tiers
let tiers: Vec<PlanRow> = sqlx::query_as("SELECT id, name FROM plan_tiers ORDER BY sort_order")
.fetch_all(ctx.db.reader())
.await?;
}
Audit PR route and auth contracts with slabs manifest
Generate a deterministic summary of every discovered route, HTTP method, authentication guard, referenced SQL table, background job, and co-located test without compiling or booting the server:
# Print a human-readable contract summary
slabs manifest
# Emit JSON or write a checked-in snapshot
slabs manifest --json
slabs manifest --write slabs-manifest.json
# Diff the current app contract against a saved snapshot or git ref
slabs manifest --diff slabs-manifest.json
slabs manifest --diff origin/main
In pull requests and CI, slabs manifest --diff <snapshot_or_git_ref> flags removed routes and marks authentication guard downgrades (for example changing require_admin to require_session, or dropping a guard altogether) with [SECURITY] so reviewers catch breaking API changes and auth regressions before merge.
Verify full-stack flows in parallel with slabs dev --ephemeral
When multiple AI agents or browser scripts test the same repo at once, sharing port 3000 and one local .db file causes collisions. Boot an isolated throwaway instance instead:
slabs dev --ephemeral
slabs dev --ephemeral creates a temporary SQLite database, applies migrations, seeds it from seeds.sql, binds an ephemeral loopback port (127.0.0.1:0), prints SLABS_EPHEMERAL_URL=http://127.0.0.1:<port> once ready, and deletes the temporary database and storage directory on exit. Agents can run parallel browser checks or curl smoke tests against their own SLABS_EPHEMERAL_URL without touching the shared development database.
Run slabs doctor for environment checks
Before deploying or opening a pull request, run slabs doctor:
slabs doctor
slabs doctor verifies your Rust toolchain, unsafe_code = "forbid", schema.sql, .dockerignore, SLABS_ENV and SLABS_SECRET_KEY rules, and prints a summary of the [security] static scan.
Format both src/ and auto-discovered slabs/ and jobs/
slabs-build writes $OUT_DIR/discovered_slabs.rs with #[path = "..."] attributes pointing to files under slabs/ and jobs/. Because cargo fmt does not expand include! from OUT_DIR, running cargo fmt alone skips every file in slabs/ and jobs/.
Use slabs fmt:
# Format in place
slabs fmt
# Check in CI without modifying files
slabs fmt --check
If you run in an environment without the slabs binary on PATH, run cargo fmt followed by rustfmt:
mise exec -- cargo fmt --all -- --check
mise exec -- rustfmt --edition 2021 --check slabs/*/*.rs jobs/*.rs
Configure the two-tier Clippy policy
Slabs separates lint strictness between framework crates and application crates:
| Scope | Configured lints |
|---|---|
Framework crates (crates/*) | unsafe_code = "forbid", missing_docs = "warn", missing_debug_implementations = "warn", unreachable_pub = "warn", rust_2018_idioms = "warn", and clippy::pedantic. |
Application crates (slabs new app) | unsafe_code = "forbid", dbg_macro = "warn", todo = "warn", unimplemented = "warn", await_holding_lock = "deny", and await_holding_refcell_ref = "deny". |
Generated applications put these lints directly in Cargo.toml:
[lints.rust]
unsafe_code = "forbid"
[lints.clippy]
dbg_macro = "warn"
todo = "warn"
unimplemented = "warn"
await_holding_lock = "deny"
await_holding_refcell_ref = "deny"
Enforce permissive licenses and advisories with deny.toml
The Slabs workspace ships a root deny.toml for cargo-deny that checks RustSec advisories, restricts crate sources to crates.io, and enforces MIT-compatible licenses:
cargo deny check
Share rules with agents via AGENTS.md and CLAUDE.md
Put your formatting, security scan, Clippy, Tailwind, and cargo nextest commands in AGENTS.md, then add a one-line CLAUDE.md at the repo root:
@AGENTS.md
See Use Slabs agent skills in your workflow to pair those always-on rules with the four Slabs skills.
Run isolated tests with cargo-nextest
Every slab test boots an isolated in-memory SQLite database (sqlite::memory:) and a unique temporary storage directory through crate::test_app().await. Run the suite with per-test process isolation:
mise exec -- cargo nextest run
Rebuild Tailwind CSS v4 before committing UI changes
Tailwind CSS v4 scans slabs/ via @source "../slabs"; in assets/input.css. Whenever you add new utility classes to a slab, recompile assets/styles/app.css:
slabs css
GitHub Actions workflow template
slabs new app generates a least-privilege .github/workflows/ci.yml with permissions: { contents: read }:
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
jobs:
check:
name: Format, Clippy, and Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- uses: Swatinem/rust-cache@v2
- uses: taiki-e/install-action@nextest
- name: Check formatting
run: |
cargo fmt --all -- --check
rustfmt --edition 2021 --check slabs/*/*.rs
- name: Clippy
run: cargo clippy --all-targets -- -D warnings
- name: Tests
run: cargo nextest run
Ship a Progressive Web App and deploy to production
Every project generated by slabs new app starts ready to install as a Progressive Web App (PWA) and ready to ship as a single container binary. This guide covers production boot validation, health and metrics endpoints, container builds with cargo-chef and Litestream, deployment templates for Kamal 2, Fly.io, and Linux VPS hosts, expand-and-contract migrations, and fast rollbacks.
Pre-flight checks and fail-closed SLABS_ENV
Run all local checks before building a release image:
slabs doctor
slabs check --no-docs
slabs css
Set SLABS_ENV=production (or staging) in your deployment secret store. AppConfig::validate() runs inside SlabsApp::boot and refuses to bind a socket if required security settings fail:
SLABS_SECRET_KEYmust be at least 32 random bytes (generate one withopenssl rand -hex 32) and cannot match the development placeholder.SLABS_COOKIE_SECUREdefaults totrueinstagingandproduction. When enabled, the session cookie name becomes__Host-slabs_sessionand responses includeStrict-Transport-Security: max-age=31536000; includeSubDomains.- Development endpoints (
/_slabs/manifest,/_slabs/openapi.json, and/_slabs/mail) are not mounted outsidedevelopmentandtest. SLABS_TRUST_PROXYdefaults tofalse. Set it totrueonly behind a trusted reverse proxy (kamal-proxy, Fly Proxy, or Caddy) soclient_ipreads proxy headers safely.SLABS_CORS_ORIGINSdefaults to empty (no cross-origin CORS headers). Set a comma-separated allowlist only when another browser origin needs API access.SLABS_METRICS_TOKENprotectsGET /_slabs/metrics. Instagingandproduction,/_slabs/metricsreturns404unlessSLABS_METRICS_TOKENis set, and requiresAuthorization: Bearer <token>verified in constant time.
Health probes, graceful shutdown, and metrics
Slabs mounts three operational endpoints automatically:
| Route | Purpose | Behavior |
|---|---|---|
GET /health/live | Liveness probe | Returns 200 OK JSON {"status": "ok"}. |
GET /health/ready | Readiness probe for load balancers | Runs SELECT 1 on ctx.db.reader(). Returns 503 Service Unavailable while draining after SIGTERM or when the database check fails. |
GET /_slabs/metrics | Operational metrics | Returns Prometheus text (or JSON with Accept: application/json) covering HTTP counts, average latency, job queue stats, and active realtime topics. Protected by SLABS_METRICS_TOKEN in staging and production. |
When a container receives SIGINT or SIGTERM, SlabsApp::serve marks the readiness flag as draining (so /health/ready immediately returns 503), finishes in-flight HTTP requests, stops background job workers and schedules, and runs PRAGMA wal_checkpoint(TRUNCATE) on file-backed SQLite databases before exit. Running a truncating WAL checkpoint at the end of the drain flushes every committed frame back into the main .db file cleanly before the next container mounts the volume.
Generate deployment configs with slabs deploy init
Generate starter configuration for your target platform and database engine (--db sqlite default, or --db postgres):
# Kamal 2 (writes config/deploy.yml)
slabs deploy init --target kamal --db sqlite
slabs deploy init --target kamal --db postgres
# Fly.io (writes fly.toml)
slabs deploy init --target fly --db sqlite
slabs deploy init --target fly --db postgres
# Bare Linux VPS (writes deploy/Caddyfile and a hardened systemd unit)
slabs deploy init --target vps --db sqlite
slabs deploy init --target vps --db postgres
Each template configures SLABS_ENV=production, SLABS_TRUST_PROXY=true, /health/ready health checks, and a 20-second SIGTERM drain window, while matching the rollout concurrency to --db:
- With
--db sqliteon Kamal 2, the generatedconfig/deploy.ymlsetsboot.limit: 1anddrain_timeout: 20.kamal-proxybuffers incoming requests briefly while the old container drains in-flight traffic, checkpoints SQLite withPRAGMA wal_checkpoint(TRUNCATE), and exits before the new container mounts the volume and passes/health/ready. That keeps single-writer SQLite deploys free of dropped requests and lock contention. - With
--db postgres, multiple app containers can share the database concurrently, so the generated Kamal 2 and Fly.io configs use multi-replicarollingdeploys where new instances pass/health/readybefore old instances drain.
Build the cargo-chef and Litestream Dockerfile
slabs new app writes a multi-stage Dockerfile, .dockerignore, docker-entrypoint.sh, and litestream.yml:
- Stage 1 and 2 use
cargo-chefto cache compiled Rust dependencies separately from your source code and build withcargo build --release --locked. - The runtime stage runs on
debian:bookworm-slimas the non-rootslabsuser (UID10001), mounts/app/assetsread-only, and bundles pinned Litestreamv0.3.13. - Container defaults set
SLABS_ENV=production,SLABS_BIND=0.0.0.0:3000,DATABASE_URL=sqlite:///data/<name>.db?mode=rwc,SLABS_STORAGE_DIR=/data/storage,SLABS_ASSETS_DIR=/app/assets, andSLABS_LOG_FORMAT=json. - The
HEALTHCHECKprobesGET http://127.0.0.1:3000/health/ready.
Always tag container images with an immutable git commit SHA instead of :latest:
SHA=$(git rev-parse --short HEAD)
slabs css
docker build -t registry.example.com/myapp:${SHA} .
docker push registry.example.com/myapp:${SHA}
Replicate SQLite WAL continuously with Litestream
Because file-backed SQLite runs in WAL mode, Litestream streams WAL frames continuously to S3, Cloudflare R2, Tigris, or MinIO with zero application code changes. slabs new app writes litestream.yml:
dbs:
- path: /data/myapp.db
replicas:
- type: s3
bucket: ${LITESTREAM_BUCKET}
path: myapp/db
endpoint: ${LITESTREAM_ENDPOINT}
region: ${LITESTREAM_REGION:-auto}
Set these environment variables in your host or secret manager:
| Variable | Example | Purpose |
|---|---|---|
LITESTREAM_BUCKET | myapp-backups | Target S3 or R2 bucket name. |
LITESTREAM_ENDPOINT | https://<account>.r2.cloudflarestorage.com | S3-compatible endpoint URL. |
LITESTREAM_REGION | auto | Signing region (defaults to auto for Cloudflare R2). |
LITESTREAM_ACCESS_KEY_ID | ... | Bucket write access key ID. |
LITESTREAM_SECRET_ACCESS_KEY | ... | Bucket write secret key. |
docker-entrypoint.sh restores the latest snapshot on an empty volume and runs your binary under Litestream:
#!/usr/bin/env sh
set -eu
litestream restore -if-db-not-exists -if-replica-exists -config /app/litestream.yml /data/myapp.db
exec litestream replicate -config /app/litestream.yml -exec "/usr/local/bin/myapp"
Choose the right rollout strategy for SQLite vs PostgreSQL
- PostgreSQL (
--db postgres) supports multi-replicarollingor blue-green deploys. New replicas boot, passGET /health/ready, receive traffic, and old replicas drain for 20 seconds onSIGTERM. - Single-volume SQLite with Litestream (
--db sqlite) allows only one writer process to mount/data/<app>.dbat a time. Never run two active containers against the same SQLite volume:- On Kamal 2, keep
boot.limit: 1anddrain_timeout: 20.kamal-proxybuffers incoming requests while the old container drains onSIGTERMand runsPRAGMA wal_checkpoint(TRUNCATE), then hands traffic to the new container as soon as it passes/health/readywith zero dropped requests. - On Fly.io, keep
[deploy] strategy = "immediate"withkill_signal = "SIGTERM",kill_timeout = "20s", and the/health/readycheck. - On a bare VPS with Caddy and
systemd, place each release at/opt/<app>/releases/<sha>/<app>, swap/opt/<app>/currentwithln -sfn, and runsystemctl restart <app>withTimeoutStopSec=20sandhealth_uri /health/ready.
- On Kamal 2, keep
Expand-and-contract migrations and fast rollbacks
Keep every schema change backward-compatible with the previous release binary so a rollback never crashes on missing columns:
- Expand first. Add new tables, nullable columns, or columns with defaults in release N.
- Switch reads and writes to the new schema in release N or N+1.
- Contract later. Drop unused columns or tables only after the old image is no longer a rollback candidate.
Take a pre-deploy backup before migrating (sqlite3 /data/<app>.db "VACUUM INTO '/data/backup-pre-deploy.db'" or verify litestream snapshots /data/<app>.db). If /health/ready fails or errors spike after a deploy, roll back immediately to the previous git SHA:
# Kamal 2
kamal rollback <previous-sha>
# Fly.io
fly releases list
fly releases rollback <version>
# Bare VPS (systemd)
ln -sfn /opt/<app>/releases/<previous-sha> /opt/<app>/current
systemctl restart <app>
If bad writes corrupted SQLite data, stop the service first, then restore from Litestream (litestream restore -timestamp <RFC3339> -o /data/<app>.db /data/<app>.db) or copy /data/backup-pre-deploy.db back into place before restarting.
Progressive Web App slabs and hardened service worker
Every new Slabs app ships two discovered PWA slabs and an SVG app icon:
| File | Route | Purpose |
|---|---|---|
slabs/pwa/manifest.rs | GET /manifest.webmanifest | Serves the Web App Manifest (application/manifest+json; charset=utf-8) with display: "standalone", theme colors, and the content-hashed icon.svg URL from ctx.assets.url("icon.svg"). |
slabs/pwa/service_worker.rs | GET /service-worker.js | Serves the service worker (application/javascript; charset=utf-8) with Cache-Control: no-cache and Service-Worker-Allowed: /. |
assets/icon.svg | /assets/<hash>/icon.svg | Monochrome Rust Orange icon referenced by the manifest. Replacing the file busts browser caches through its content hash. |
html::document wires <link rel="manifest" href="/manifest.webmanifest"> in <head> and registers /service-worker.js on window load. In v0.5.0, the generated service worker enforces same-origin checks before caching responses or calling clients.openWindow, uses stale-while-revalidate for /_slabs/vendor/, uses cache-first for content-hashed /assets/, uses network-first with a 503 offline page for navigations, and wraps event.data.json() in try/catch.
Seed databases idempotently with slabs db seed
slabs new app creates a starter seeds.sql file. Write idempotent SQL (INSERT OR IGNORE on SQLite, ON CONFLICT DO NOTHING on PostgreSQL) and run slabs db seed after migrating:
slabs db migrate --database-url sqlite://myapp.db?mode=rwc
slabs db seed --database-url sqlite://myapp.db?mode=rwc
Pass --file <path> to execute a custom fixture file instead of seeds.sql.
Workspace crates and AppCtx fields
This reference lists all 16 crates in the Slabs v0.5.0 workspace, every field on AppCtx, and every symbol exported by slabs::prelude::*.
Workspace crates
| Crate | Responsibility |
|---|---|
slabs-framework (imported as slabs) | Top-level facade re-exporting all sub-crates, prelude::*, discover_slabs!(), SlabsApp::boot, SlabsApp::with_schedules, SlabsApp::serve, and init_tracing(). |
slabs-build | Build-script scanner (slabs_build::discover()) that scans slabs/<feature>/*.rs and jobs/*.rs and writes $OUT_DIR/discovered_slabs.rs. |
slabs-core | Prefixed ULIDs (id::new), URL slugs (slug::slugify), fractional list positions (position::between), SHA-256 digests (fingerprint), multi-field validator (Validate), #[non_exhaustive] SlabError and SlabResult, AppEnv, fail-closed AppConfig::validate(), and OpenAPI types (AppManifest, AppManifest::to_openapi_3_1, RouteMeta, JobMeta). |
slabs-db | Split SQLite WAL pools (Db), standalone PostgreSQL pool (PgDb), DbEngine, 12-table system schemas (including slabs_incidents), Incidents store, Db::explain_query_plan, QueryBuilder, fts5_query, cursor pagination (Pagination, CursorPage), transactional audit logging (AuditLog, AuditEntry), execute_sql_file, and dump_schema_sql. |
slabs-auth | Async Argon2id password hashing (hash_password, verify_password, verify_password_constant_time), __Host-slabs_session and slabs_session cookies, email/purpose-bound 6-character magic links with lockout, SHA-256 slb_ Bearer access tokens, expiring signed tokens (sign_token, verify_token), Auth::for_signing, and secret-redacting Debug. |
slabs-http | Axum 0.8 router builder (build_router), AppCtx, SlabDef (with input_schema and output_schema), JobDef, ScheduleDef, JobRegistry, RateLimiter, client_ip, Fetch Metadata and Origin CSRF middleware, /health/live, /health/ready, /_slabs/metrics, the four Bearer-protected /_slabs/incidents* endpoints, dev-only /_slabs/manifest, /_slabs/openapi.json, and /_slabs/mail, vendored UI assets, and Tower middleware stack. |
slabs-html | Maud html! macro re-export, document(...) HTML5 shell with PWA metadata and service-worker registration, safe render_markdown, safe json_script, htmx helpers (with relative-path guard on htmx::redirect and htmx::flash_redirect), redirect_external, signed flash cookies (Flash, FlashKind, flash_banner), escape, and HMAC CSRF helpers (csrf_token, verify_csrf). |
slabs-assets | Content-hashed in-memory static asset store (/assets/{hash}/{*path}) with stylesheet_urls() and behavior_urls(). |
slabs-jobs | SQLite-backed durable job queue (Jobs) with enqueue_in_tx, enqueue_with_options_in_tx, atomic claim_next, exponential backoff, and dead-lettering. |
slabs-mail | Transactional mailer (Mailer, Email, SentEmail) with Resend HTTP API, SMTP (lettre), and SQLite OutboxOnly transports. |
slabs-storage | Local disk storage (StorageBackend::Local), path-style AWS SigV4 S3 backend (StorageBackend::S3) backed by slabs_blobs, hardened BlobMeta::into_safe_response, and optional image resizing (features = ["images"], Storage::put_resized_image). |
slabs-cache | SQLite TTL key-value cache (Cache) supporting string and JSON entries (set, get, set_json, get_json, delete, purge_expired). |
slabs-realtime | In-process tokio::sync::broadcast topic hub (Realtime) with sse_stream, subscribe, publish_html, publish_json, publish_text, online presence (track_presence, list_presence, PresenceGuard, PresenceEntry), and validate_ws_origin. |
slabs-webhooks | Outbound HMAC-SHA256 signed webhooks (Webhooks) with register, dispatch_in_tx, deliver_http (with SSRF-safe DNS resolver blocking non-global IPv4/IPv6 addresses at connect time), and inbound verification (verify_incoming_hmac_sha256, verify_timestamp_window, claim_idempotency_in_tx). |
slabs-test | Isolated parallel test runner (TestApp::boot) with in-memory SQLite, temporary storage directory, cookie helpers (handling both slabs_session and __Host-slabs_session), drain_jobs, run_job_now, and sent_emails. |
slabs-cli | Command-line tool (slabs) for app/slab/bug-report/job creation, slabs doctor, slabs deploy init --db sqlite|postgres, slabs incidents, slabs check (including --changed, --slab, --explain, and --strict-explain), slabs manifest --diff, slabs dev --ephemeral, slabs fmt, Tailwind builds, database tasks, and route listing. |
AppCtx fields
Every HTTP slab handler receives State(ctx): State<AppCtx>, and every background job receives ctx: AppCtx. AppCtx is cheap to clone because every field wraps an Arc.
| Field | Type | Purpose |
|---|---|---|
ctx.config | slabs_core::AppConfig | Runtime configuration loaded from SLABS_* and DATABASE_URL or AppConfig::for_test. |
ctx.db | slabs_db::Db | Split SQLite WAL pools (reader() with 16 read-only connections, writer() / pool() with 1 writer connection, begin() running BEGIN IMMEDIATE, ping()). |
ctx.auth | slabs_auth::Auth | Async Argon2id (hash_password, verify_password, verify_password_constant_time), sessions (require_session, require_admin), magic links (issue_magic_link, consume_magic_link), Bearer tokens (issue_access_token, require_auth, require_write_auth), expiring tokens (sign_token, verify_token), and HMAC signing. |
ctx.jobs | slabs_jobs::Jobs | Durable SQLite job queue (enqueue_in_tx, enqueue_with_options_in_tx, enqueue, claim_next, mark_done, mark_failed). |
ctx.mail | slabs_mail::Mailer | Email delivery via Resend, SMTP, or SQLite outbox (send, list_sent). |
ctx.storage | slabs_storage::Storage | Blob storage on local disk or S3-compatible store (put, put_scoped, get, delete, plus put_resized_image when features = ["images"] is enabled). |
ctx.cache | slabs_cache::Cache | SQLite TTL cache (set, get, set_json, get_json, delete, purge_expired). |
ctx.realtime | slabs_realtime::Realtime | In-process broadcast and presence hub (sse_stream, subscribe, publish_html, publish_json, publish_text, track_presence, list_presence). |
ctx.webhooks | slabs_webhooks::Webhooks | Outbound signed webhooks with DNS-level SSRF blocking and inbound verification (register, dispatch_in_tx, deliver_http, mark_delivered, verify_incoming_hmac_sha256, verify_timestamp_window, claim_idempotency_in_tx). |
ctx.assets | slabs_assets::Assets | Content-hashed static assets (url, get, stylesheet_urls, behavior_urls). |
ctx.rate_limit | slabs_http::RateLimiter | Bounded fixed-window in-memory rate limiter (check(key, max_requests, window_secs) -> SlabResult<u64>). |
ctx.audit | slabs_db::AuditLog | Transactional audit log backed by slabs_audit_log (record_in_tx, list_for_target, list_recent). |
ctx.incidents | slabs_db::Incidents | Active failures inbox backed by slabs_incidents (open, resolved, reopened) with deterministic fingerprinting, stale auto-close, and signed slabs.incident.v1 webhooks. |
slabs::prelude::* exports
Import use slabs::prelude::*; at the top of slab and job files to bring these items into scope:
- Auth (
slabs_auth):Principal,Session,SESSION_COOKIE_NAME - Core (
slabs_core):fingerprint,id,position,slug,AppConfig,AppEnv,SlabError,SlabResult,Validate - Database (
slabs_db):AuditEntry,AuditLog,CursorPage,Pagination,QueryBuilder - HTML and HTMX (
slabs_html):html(theslabs_htmlmodule, includinghtml::document,html::flash_banner, andhtml::render_markdown),maud(themaud::html!macro),htmx,json_script,redirect_external,Flash,FlashKind,Markup - HTTP and jobs (
slabs_http):client_ip,AppCtx,JobDef,ScheduleDef,SlabDef - Mail and storage (
slabs_mail,slabs_storage):Email,BlobMeta - Realtime (
slabs_realtime):validate_ws_origin,PresenceEntry,PresenceGuard
PreEscaped is omitted from slabs::prelude::* on purpose so accidental raw HTML injection is harder to write. Import slabs::html::PreEscaped explicitly only when inserting trusted or sanitized markup.
Core helpers and safe rendering
| Helper | Signature | Behavior |
|---|---|---|
slug::slugify | fn(&str) -> String | Converts text into a lowercase, hyphen-separated ASCII slug. Collapses separator runs into one -, trims edge hyphens, and returns "-" if no ASCII alphanumeric characters remain. |
position::between | fn(Option<f64>, Option<f64>) -> f64 | Computes an f64 fractional sort score for O(1) single-row list reordering. |
fingerprint | fn(&[&str]) -> String | Computes a 64-character lowercase SHA-256 hex digest over NUL-separated string parts for content hashes, If-Match concurrency checks, and cache keys. |
html::render_markdown | fn(&str) -> Markup | Renders untrusted CommonMark and GitHub-flavored Markdown with pulldown-cmark. Drops raw HTML blocks and inline tags, and rewrites unsafe URL schemes (javascript:, vbscript:, data:) to "#". |
json_script | fn<T: Serialize>(&str, &T) -> SlabResult<Markup> | Embeds JSON inside <script type="application/json" id="..."> with <, >, &, U+2028, and U+2029 escaped. |
BlobMeta::into_safe_response | fn(&self, impl Into<Bytes>, bool) -> Response | Serves blob bytes with X-Content-Type-Options: nosniff, Content-Security-Policy: default-src 'none'; sandbox, and safe Content-Disposition (attachment for active types like SVG or HTML). |
client_ip | fn(&HeaderMap, Option<SocketAddr>, bool) -> String | Returns the peer IP when trust_proxy is false, or checks CF-Connecting-IP, Fly-Client-IP, and the rightmost valid IP in X-Forwarded-For when trust_proxy is true. |
#[non_exhaustive] SlabError and secret-redacting Debug
SlabError carries #[non_exhaustive] so new HTTP error variants never break downstream match expressions. Include a wildcard arm (_ => ...) whenever matching on SlabError outside slabs-core.
Custom fmt::Debug implementations on AppConfig, Auth, MailTransport, S3Config, and WebhookRecord redact sensitive values (secret_key, metrics_token, database passwords, Resend api_key, SMTP URLs, S3 secret_access_key, and signing_secret) so tracing spans and {:?} logs never leak credentials.
Optional Cargo features
Enable image decoding and thumbnail resizing by turning on the images feature on slabs-framework (forwarding to slabs-storage/images):
[dependencies]
slabs = { package = "slabs-framework", version = "0.5", features = ["images"] }
With images enabled, ctx.storage.put_resized_image(filename, data, max_width, max_height) decodes uploaded bytes on a blocking worker thread, scales the image to fit within max_width by max_height while keeping aspect ratio, re-encodes as PNG, normalizes the filename extension to .png, and saves it through Storage::put.
SlabDef, JobDef, and OpenAPI 3.1 export
SlabDef
SlabDef::get(path, handler)SlabDef::post(path, handler)SlabDef::put(path, handler)SlabDef::patch(path, handler)SlabDef::delete(path, handler)- Builder methods:
.name("feature.action"),.feature("feature"),.summary("..."),.input_schema(serde_json::Value),.output_schema(serde_json::Value)
Paths use Axum 0.8 syntax ({id}, {*path}). Multiple slabs may register different HTTP verbs on the same path, and build_router merges them into one MethodRouter.
Attaching JSON Schemas with .input_schema(...) and .output_schema(...) enriches the OpenAPI 3.1.0 document returned by AppManifest::to_openapi_3_1() and mounted at GET /_slabs/openapi.json in development and test:
#![allow(unused)]
fn main() {
use serde_json::json;
pub fn slab() -> SlabDef {
SlabDef::post("/api/orders", handle)
.name("orders.place_order")
.summary("Create an order")
.input_schema(json!({
"type": "object",
"required": ["sku", "quantity"],
"properties": {
"sku": { "type": "string" },
"quantity": { "type": "integer", "minimum": 1 }
}
}))
.output_schema(json!({
"type": "object",
"properties": {
"order_id": { "type": "string" }
}
}))
}
}
JobDef and ScheduleDef
JobDef::new(name, handler)wherehandlerhas signatureasync fn run(ctx: AppCtx, payload: serde_json::Value) -> SlabResult<()>- Builder methods:
.queue("default"),.max_attempts(5),.summary("...") ScheduleDef::every(Duration, job_name, payload)attached viaSlabsApp::with_schedules(vec![...])
CLI commands and environment variables
This reference documents every slabs CLI subcommand, flag, and runtime environment variable read by Slabs v0.5.0.
CLI global options
Pass --app-dir <PATH> before any subcommand to target an app directory outside the current working directory (defaults to .):
slabs --app-dir examples/campfire list
When running directly from the Slabs workspace without installing the binary, invoke it via Cargo:
mise exec -- cargo run -p slabs-cli -- --app-dir examples/campfire list
CLI subcommands
| Command | Flags | Action |
|---|---|---|
slabs new app <name> | --dir <path> | Create a standalone PWA-ready Slabs app (slabs-framework = "0.5", slabs-build = "0.5", #[cfg(test)] test_app(), starter and PWA slabs, cargo-chef + Litestream v0.3.13 Dockerfile, docker-entrypoint.sh, .dockerignore, litestream.yml, seeds.sql, bundled .claude/skills/, CLAUDE.md, and least-privilege CI). |
slabs new slab <feature> <name> | --method <verb> (default post), --path <route> (default /api/<feature>/<name>) | Validate identifiers and route syntax, then create slabs/<feature>/<name>.rs with a starter guard and co-located test without editing any existing file. |
slabs new bug-report | None | Scaffold slabs/support/report_bug.rs with a zero-JS HTML/HTMX multipart form (up to 3 image, video, or file attachments stored via ctx.storage.put_scoped("bug_report", ...)), server-side user_id, sanitized Referer path, User-Agent, ctx.incidents recording, and co-located tests. |
slabs new job <name> | None | Create jobs/<name>.rs without editing any existing file. |
slabs fmt | --check | Run cargo fmt on the crate and rustfmt --edition 2021 on every .rs file in slabs/ and jobs/. With --check, exits non-zero if any file needs formatting. |
slabs check | --workspace, --no-docs, --changed, --base <ref>, --slab <feature>/<action>, --explain, --strict-explain | Run the 6-step CI suite (formatting, [security] static analyzer, Clippy -D warnings, Rustdoc -D warnings, doctests, and cargo nextest or cargo test). --changed [--base <ref>] and --slab <feature>/<action> run targeted formatting, security scanning, and cargo-nextest on only the selected slab(s). --explain and --strict-explain run SQLite EXPLAIN QUERY PLAN over static SELECT/WITH queries in slabs/ and jobs/ and flag unintended full-table SCANs (// slabs:allow-scan: <reason> opts out). |
slabs manifest | --json, --write <path>, --diff <snapshot_or_git_ref> | Emit a deterministic route, auth guard, SQL table, job, and test contract summary for --app-dir. --write <path> saves a snapshot file. --diff <snapshot_or_git_ref> compares against a snapshot or git ref and flags removed routes and [SECURITY] auth guard downgrades. |
slabs doctor | None | Check the Rust toolchain, unsafe_code = "forbid", schema.sql, .dockerignore, SLABS_ENV and SLABS_SECRET_KEY rules, and the [security] static scan summary. |
slabs deploy init | --target <kamal|fly|vps>, --db <sqlite|postgres> (default sqlite) | Generate deployment templates (config/deploy.yml for Kamal 2, fly.toml for Fly.io, or deploy/Caddyfile plus a hardened systemd unit for a bare Linux VPS) tuned for single-writer SQLite (boot.limit: 1 with kamal-proxy buffering, or Fly immediate) or multi-replica PostgreSQL (rolling). |
slabs list | None | Print all compile-time discovered slabs and background jobs in --app-dir. |
slabs css | --watch | Compile assets/input.css to assets/styles/app.css with the standalone tailwindcss v4 binary (minified one-shot by default, or continuous with --watch). |
slabs dev | --package <name> / -p, --bind <addr>, --ephemeral | Compile Tailwind CSS, run tailwindcss --watch, and run cargo watch (or cargo run when cargo-watch is absent). With --ephemeral, boots a throwaway SQLite database seeded from seeds.sql on 127.0.0.1:0, prints SLABS_EPHEMERAL_URL, and cleans up temporary files on exit. |
slabs db migrate | --database-url <url> (env: DATABASE_URL) | Create all 12 system tables and apply SQL migrations from <app_dir>/migrations to SQLite or PostgreSQL. |
slabs db seed | --database-url <url> (env: DATABASE_URL), --file <path> (optional) | Run an idempotent SQL seed file (defaults to <app_dir>/seeds.sql) against SQLite or PostgreSQL. |
slabs db dump-schema | --database-url <url> (env: DATABASE_URL) | Write the live database schema snapshot to <app_dir>/schema.sql for SQLite or PostgreSQL. |
slabs db prepare | --database-url <url> (optional, env: DATABASE_URL), --package <name> / -p | Generate offline .sqlx/ metadata for compile-time sqlx::query! checks. Defaults to a temporary SQLite database migrated from <app_dir>/migrations. |
slabs incidents list | --url <url> (env: SLABS_URL), --token <token> (env: SLABS_METRICS_TOKEN), --status <active|open|reopened|resolved|all> (default active), --limit <n>, --json | List incidents from GET /_slabs/incidents, ordered by last_seen_at DESC. |
slabs incidents show <id> | --url <url> (env: SLABS_URL), --token <token> (env: SLABS_METRICS_TOKEN), --json | Fetch one incident from GET /_slabs/incidents/{id}, including source_file, repro_hint, recent_occurrences_json, attachment IDs, and a ready-to-paste repro_test Rust skeleton. |
slabs incidents resolve <id> | --sha <git_sha>, --url <url> (env: SLABS_URL), --token <token> (env: SLABS_METRICS_TOKEN) | Mark an incident resolved via POST /_slabs/incidents/{id}/resolve with an optional deployed commit SHA. |
slabs incidents perf | --url <url> (env: SLABS_URL), --token <token> (env: SLABS_METRICS_TOKEN), --json | Print per-route p50/p95/p99 latency percentiles, job queue stats, and active incident count from GET /_slabs/metrics. |
Harness engineering CLI contracts
The four zero-dependency Harness Engineering tools added in v0.5.0 operate directly on the local repository without external services:
slabs check --changed [--base <ref>]andslabs check --slab <feature>/<action>limit formatting,[security]scanning, andcargo-nextestexecution to modified or named slab files.slabs check --explain(warning mode) andslabs check --strict-explain(non-zero exit on violation) boot an in-memory SQLite database frommigrations/orschema.sql, runEXPLAIN QUERY PLANon staticSELECTandWITHqueries extracted fromslabs/andjobs/, and flag unintended full-tableSCANs. Add// slabs:allow-scan: <reason>immediately above an intentional scan to suppress the finding.slabs manifest [--json] [--write <path>] [--diff <snapshot_or_git_ref>]extracts a deterministic route, auth guard, table, job, and test manifest.--diffflags removed routes and marks auth guard downgrades with[SECURITY].slabs dev --ephemeralbinds127.0.0.1:0against a throwaway SQLite database seeded fromseeds.sql, printsSLABS_EPHEMERAL_URL=http://127.0.0.1:<port>to stdout, and removes temporary files on exit.
Runtime environment variables
Core (slabs-core::AppConfig::from_env and slabs::init_tracing)
| Variable | Default | Description |
|---|---|---|
SLABS_ENV | development | Deployment environment (development, test, staging, production). staging and production enforce fail-closed validation in AppConfig::validate(). |
SLABS_BIND | 127.0.0.1:3000 | Socket address passed to TcpListener::bind. |
DATABASE_URL | sqlite://{app_name}.db?mode=rwc | Database connection URL. sqlite::memory: uses a shared in-memory connection. |
SLABS_SECRET_KEY | Ephemeral random 32-byte key in dev/test; required in staging/prod | Signing key for cookies, magic links, tokens, and HMAC digests. In staging and production, boot fails if unset, shorter than 32 bytes, or equal to the legacy dev sentinel. |
SLABS_STORAGE_DIR | ./storage/{app_name} | Local filesystem root for StorageBackend::Local. |
SLABS_ASSETS_DIR | ./assets (or ./examples/{app_name}/assets) | Directory scanned at boot by Assets::from_dir. |
SLABS_JOB_POLL_MS | 500 | Background job worker poll interval in milliseconds (minimum 50). |
SLABS_JOB_CONCURRENCY | 4 | Maximum concurrent background job worker tasks (minimum 1). |
SLABS_COOKIE_SECURE | true in staging/production, false in development/test | Sets Secure on cookies, names the session cookie __Host-slabs_session, and enables the Strict-Transport-Security header. |
SLABS_CSRF_ENFORCE | true | Enables Fetch Metadata (Sec-Fetch-Site) and Origin CSRF checks on cookie-authenticated mutations. |
SLABS_CORS_ORIGINS | Unset (no CORS headers) | Comma-separated allowlist of browser origins permitted for cross-origin requests and WebSockets. |
SLABS_TRUST_PROXY | false | Allows client_ip to read CF-Connecting-IP, Fly-Client-IP, and the rightmost valid IP in X-Forwarded-For. Enable only behind a trusted reverse proxy. |
SLABS_METRICS_TOKEN | Unset | Bearer token protecting GET /_slabs/metrics and the four /_slabs/incidents* endpoints, and read by slabs incidents. In staging and production, these endpoints return 404 when unset. |
SLABS_MAX_BODY_BYTES | 4194304 (4 MiB) | Maximum HTTP request body size enforced by RequestBodyLimitLayer. |
SLABS_MAX_BLOB_BYTES | 10485760 (10 MiB) | Maximum blob upload size accepted by slabs-storage. |
SLABS_WEBHOOKS_LIVE | false | Sends live HTTP requests for outbound webhooks when "1" or "true". When false, marks deliveries 200 in the outbox without network I/O. |
SLABS_WEBHOOKS_ALLOW_LOCAL | false | Permits outbound webhooks to target loopback or private addresses when "1" or "true". Leave false in production. |
RUST_LOG | info,tower_http=info,sqlx=warn | Tracing filter read by slabs::init_tracing(). |
SLABS_LOG_FORMAT | Plain text | Set to json (case-insensitive) to emit newline-delimited JSON logs. |
Incidents and performance
| Variable | Default | Description |
|---|---|---|
SLABS_URL | http://127.0.0.1:3000 | Base URL read by slabs incidents subcommands. |
SLABS_GIT_SHA | Unset | Deployment commit SHA attached to recorded incidents and each recent_occurrences_json ring-buffer entry (seen_at, git_sha, request_id, latency_ms). |
SLABS_SLOW_REQUEST_MS | 500 | HTTP latency threshold in milliseconds for recording slow_request incidents. |
SLABS_SLOW_JOB_MS | 5000 | Background job latency threshold in milliseconds for recording slow_job incidents. |
SLABS_INCIDENT_STALE_DAYS | 30 | Auto-resolves open and reopened incidents with no new occurrences after this many days. Set to 0 to disable stale auto-close. |
SLABS_INCIDENT_WEBHOOK_URL | Unset | Outbound webhook URL notified on incident.opened, incident.reopened, and incident.resolved (slabs.incident.v1). |
SLABS_INCIDENT_WEBHOOK_SECRET | Unset | HMAC-SHA256 signing secret used to emit X-Slabs-Signature: sha256=<hex> on incident webhooks. |
Mail transport (slabs-mail::MailTransport::from_env)
Selection priority order is SLABS_RESEND_API_KEY, then SLABS_SMTP_URL, then OutboxOnly.
| Variable | Default | Description |
|---|---|---|
SLABS_RESEND_API_KEY | Unset | Enables Resend HTTP API delivery (MailTransport::Resend). |
SLABS_RESEND_URL | https://api.resend.com/emails | Overrides the Resend API endpoint URL. |
SLABS_SMTP_URL | Unset | Enables SMTP delivery via lettre (such as smtps://user:pass@smtp.host). |
S3 object storage (slabs-storage::S3Config::from_env)
When all three required variables are set, AppCtx::connect selects StorageBackend::S3. Otherwise it uses StorageBackend::Local.
| Variable | Default | Description |
|---|---|---|
SLABS_S3_BUCKET | Required for S3 | Target S3 bucket name (must be non-empty). |
SLABS_S3_ACCESS_KEY_ID | Required for S3 | AWS SigV4 access key ID. |
SLABS_S3_SECRET_ACCESS_KEY | Required for S3 | AWS SigV4 secret access key. |
SLABS_S3_REGION | us-east-1 | AWS SigV4 signing region (such as auto for Cloudflare R2). |
SLABS_S3_ENDPOINT | https://s3.<region>.amazonaws.com | Base endpoint URL without a trailing slash for AWS S3, R2, MinIO, Tigris, or Garage. |
System tables, built-in routes, middleware, and error codes
This reference lists the twelve framework-owned database tables, the built-in routes mounted by build_router, the Tower middleware stack order, and the HTTP responses produced by SlabError.
System database tables
Db::init_system_tables(), Db::migrate(), and Db::migrate_dir() create these twelve tables idempotently. PgDb creates PostgreSQL equivalents using TIMESTAMPTZ, JSONB, BIGINT, and BOOLEAN. Applications define their own users table in migrations/.
| Table | Primary key and key columns | Indexes | Owned by |
|---|---|---|---|
slabs_sessions | id (ses_...), user_id, role, token_hash (UNIQUE), expires_at, created_at | (user_id), (expires_at) | slabs-auth |
slabs_magic_links | id (mlk_...), email, purpose, code_hash (UNIQUE), expires_at, created_at | (expires_at) | slabs-auth |
slabs_access_tokens | id (pat_...), user_id, role, description, permission, token_hash (UNIQUE), last_used_at, expires_at, created_at | (user_id) | slabs-auth |
slabs_jobs | id (job_...), job_name, queue, payload_json, status, attempts, max_attempts, run_at, last_error, created_at, updated_at | (status, run_at, created_at) | slabs-jobs |
slabs_cache | cache_key (PRIMARY KEY), value_text, expires_at, updated_at | (expires_at) | slabs-cache |
slabs_mail_outbox | id (eml_...), from_addr, to_addr, subject, text_body, html_body, sent_at | Primary key | slabs-mail |
slabs_blobs | id (blb_...), filename, content_type, byte_size, checksum_sha256, storage_key (UNIQUE), created_at | Primary key, unique storage_key | slabs-storage |
slabs_webhooks | id (whk_...), scope_id, name, url, signing_secret, subscribed_actions_json, active, created_at | (scope_id, active) | slabs-webhooks |
slabs_webhook_deliveries | id, webhook_id (FK ON DELETE CASCADE), action, payload_json, signature, status, response_status, last_error, created_at, delivered_at | (webhook_id, created_at DESC) | slabs-webhooks |
slabs_idempotency_keys | (scope, key) (composite PRIMARY KEY), response_json, created_at | Primary key | slabs-db / slabs-webhooks |
slabs_audit_log | id (aud_...), actor_id, action, target_type, target_id, metadata_json, created_at | (target_type, target_id, created_at DESC) | slabs-db |
slabs_incidents | id (inc_...), fingerprint (UNIQUE), kind, status (open, reopened, resolved), source_file, route_pattern, title, detail, context_json, repro_hint, recent_occurrences_json, occurrences, git_sha, resolved_in_sha, first_seen_at, last_seen_at, resolved_at | (status, last_seen_at DESC) | slabs-db / slabs-http |
Built-in routes
slabs_http::build_router mounts these endpoints alongside your discovered slabs:
| Method | Path | Availability | Behavior |
|---|---|---|---|
GET | /health and /_slabs/health | Always | Runs SELECT 1 via ctx.db.ping() and returns {"status": "ok", "app": "<app_name>"}. |
GET | /health/live | Always | Liveness probe returning 200 OK JSON {"status": "ok"}. |
GET | /health/ready | Always | Readiness probe returning 503 Service Unavailable when draining after SIGTERM or when SELECT 1 fails, otherwise 200 OK. |
GET | /_slabs/metrics | Always (token-gated in staging/prod) | Returns Prometheus text (or JSON when Accept: application/json) covering per-route p50/p95/p99 latency histograms mapped to source_file, HTTP counts, job queue stats, active incident count, and active realtime topics. In staging and production, returns 404 unless SLABS_METRICS_TOKEN is set, and requires Authorization: Bearer <token> verified in constant time. |
GET | /_slabs/incidents | Always (token-gated in staging/prod) | Lists incidents filtered by status=active|open|reopened|resolved|all (default active) and limit, ordered by last_seen_at DESC. Protected by SLABS_METRICS_TOKEN. |
GET | /_slabs/incidents/{id} | Always (token-gated in staging/prod) | Returns one incident record with source_file, context_json, recent_occurrences_json, attachment blob IDs, and a ready-to-paste repro_test Rust skeleton. Protected by SLABS_METRICS_TOKEN. |
GET | /_slabs/incidents/{id}/attachments/{blob_id} | Always (token-gated in staging/prod) | Streams a scoped attachment blob belonging to the incident using safe download headers. Protected by SLABS_METRICS_TOKEN. |
POST | /_slabs/incidents/{id}/resolve | Always (token-gated in staging/prod) | Transitions an incident to resolved with an optional {"resolved_in_sha": "<sha>"} body and dispatches an incident.resolved webhook when configured. Protected by SLABS_METRICS_TOKEN. |
GET | /_slabs/manifest | development and test only | Returns the JSON AppManifest containing app_name, registered routes (RouteMeta), and registered jobs (JobMeta). |
GET | /_slabs/openapi.json | development and test only | Returns the OpenAPI 3.1.0 JSON document produced by AppManifest::to_openapi_3_1(). |
GET | /_slabs/mail | development and test only | Returns up to 50 recent messages from slabs_mail_outbox as {"emails": [...]}. |
GET | /_slabs/vendor/{*path} | Always | Serves embedded MIT assets (basecoat.min.css, basecoat.min.js, htmx.min.js, htmx-ext-sse.js, idiomorph-ext.min.js, alpine.min.js, sw-register.js) with ETag and Cache-Control: public, max-age=86400. |
GET | /assets/{hash}/{*path} | Always | Serves content-hashed static files from ctx.assets with Cache-Control: public, max-age=31536000, immutable and a sandbox CSP on SVG, HTML, and XHTML assets. Returns HTTP 404 when the path or 12-character SHA-256 hash does not match. |
Middleware stack order
build_router wraps every route in these Tower layers from outermost (first to run on incoming requests) to innermost:
sanitize_request_id_middlewarestrips malformed incomingX-Request-Idheaders longer than 64 bytes or containing characters outside[A-Za-z0-9_-].SetRequestIdLayergenerates a time-sortable ULIDX-Request-Id(req_<ulid>) when absent.TraceLayer::new_for_http()emits HTTP request and response tracing spans.PropagateRequestIdLayercopiesX-Request-Idonto the HTTP response.metrics_middlewarerecords per-route request counts, 5xx counts, latency histograms,slab_file-taggedtracinglogs, andhttp_5xx,panic, andslow_requestincidents inslabs_incidents.- Optional
CorsLayermounts only whenSLABS_CORS_ORIGINSis non-empty. It restricts cross-origin access to that allowlist withallow_credentials(true). - Optional
Strict-Transport-Security: max-age=31536000; includeSubDomainsmounts whencookie_secureistrue. Permissions-Policy: camera=(), microphone=(), geolocation=()is set if absent.Referrer-Policy: strict-origin-when-cross-originis set if absent.X-Frame-Options: SAMEORIGINis set if absent.X-Content-Type-Options: nosniffis set if absent.csrf_middlewareenforces Fetch Metadata (Sec-Fetch-Site: cross-site) andOriginchecks on cookie-authenticatedPOST,PUT,PATCH, andDELETErequests whenSLABS_CSRF_ENFORCE=true. Requests withAuthorization: Bearerheaders and/webhooks*or/api/webhooks*routes bypass this check.RequestBodyLimitLayerenforcesSLABS_MAX_BODY_BYTES(default 4 MiB).CompressionLayercompresses responses with gzip and brotli (br).
SlabError HTTP mapping
Every slab returns SlabResult<T> (Result<T, SlabError>). SlabError::into_response serializes a JSON object with error and message fields:
| Variant | HTTP status | JSON error field | Extra headers or fields |
|---|---|---|---|
SlabError::BadRequest(msg) | 400 | "bad_request" | Includes msg. |
SlabError::Unauthorized(msg) | 401 | "unauthorized" | Includes msg. |
SlabError::Forbidden(msg) | 403 | "forbidden" | Includes msg. |
SlabError::NotFound(msg) | 404 | "not_found" | Includes msg. |
SlabError::Database(sqlx::Error::RowNotFound) | 404 | "not_found" | Fixed message "record not found". |
SlabError::Conflict(msg) | 409 | "conflict" | Includes msg. |
SlabError::Validation { field, message } | 422 | "validation_error" | Includes "field": field and "message": message. |
SlabError::ValidationErrors(fields) | 422 | "validation_error" | Includes "fields": { "<field>": ["<message>", ...] } produced by Validate::finish. |
SlabError::TooManyRequests { retry_after_secs, message } | 429 | "too_many_requests" | Sets Retry-After: <secs> header and "retry_after_secs" JSON field. |
SlabError::Database(other) | 500 | "database_error" | Logs raw error via tracing::error!; returns "internal database error" without leaking SQL. |
SlabError::Internal(msg) | 500 | "internal_error" | Logs msg via tracing::error!; returns "internal server error". |
Built-in background job
JobRegistry::new registers "slabs.deliver_webhook" on the "webhooks" queue automatically unless your app defines a job with the same name. When SLABS_WEBHOOKS_LIVE is true, it calls ctx.webhooks.deliver_http(delivery_id, ctx.config.webhooks_allow_local). Otherwise it records HTTP 200 in slabs_webhook_deliveries without outbound network I/O.
The Slabs doctrine
Slabs rests on one observation. The abstractions that help a human browse an MVC codebase in an IDE are the same abstractions that stall parallel AI agents and trigger git merge conflicts.
When ten contributors add ten endpoints to a typical web app, every one of them edits routes.rs, models/mod.rs, services/mod.rs, and shared DTO files. Each contributor guesses which callbacks fire on save(), hunts across six directories to trace one HTTP request, and spends more time untangling conflicts than shipping code.
Slabs takes the opposite path. Eight rules govern the framework so every endpoint stays local, every write stays explicit, and twenty contributors can ship in parallel without touching each other’s files.
1. One use case is one self-contained slab
Every HTTP endpoint lives in its own file at slabs/<feature>/<action>.rs, such as slabs/cards/create_card.rs. Every background job lives in its own file at jobs/<name>.rs.
One file holds the entire vertical slice of a single Transaction Script:
- Route declaration (
pub fn slab() -> SlabDef) - Request
Inputand responseOutputstructs - Line-1 authentication, authorization, and rate-limit guards
- Input validation
- Raw SQL queries and explicit transaction boundary
- Transactional side effects (
enqueue_in_tx,dispatch_in_tx,audit.record_in_tx) - Co-located
#[cfg(test)] mod tests
Slabs forbids models/, controllers/, repositories/, and services/ directories. Repeating a five-line struct or a three-line SELECT in two slabs costs almost nothing and keeps both files independent. Coupling twenty endpoints through a shared helper trait saves ten lines once and produces merge conflicts forever.
When an agent opens slabs/cards/create_card.rs, it reads 100% of the code that runs when POST /api/boards/{board_id}/cards arrives.
2. Compile-time discovery replaces central registries
Slabs has no routes.rs and no manual job registry.
A three-line build.rs calls slabs_build::discover(). At build time, slabs-build walks slabs/<feature>/*.rs and jobs/*.rs and writes $OUT_DIR/discovered_slabs.rs. src/lib.rs includes that generated file once with slabs::discover_slabs!() and passes collect_slabs() and collect_jobs() to SlabsApp::boot(...).
- Creating a new endpoint touches zero existing files.
- Deleting an endpoint removes one file cleanly, with no dead route entries or orphaned helpers left behind.
- Helper modules inside
slabs/orjobs/start with_(such as_layout.rs), andslabs-buildskips them automatically. - Multiple slabs can register different HTTP verbs on the same path, and
slabs-httpmerges them into one Axum 0.8MethodRouter.
Twenty parallel agents can open twenty pull requests adding twenty slabs and merge all twenty with zero conflicts.
3. Raw SQL is the clearest query language for agents
ORMs invent a second query language with lazy-loading traps, N+1 queries, hidden JOIN rewrites, and version-specific macro quirks. SQL has been stable for forty years and every model knows it fluently.
Slabs keeps database access direct:
schema.sqlis the single-file ground truth for every table, column, constraint, and index in the application. Reading one file shows the complete data model.- Every query uses parameterized SQL through
sqlx::queryorsqlx::query_as. When you want compile-time SQL checks, runslabs db prepareand usesqlx::query!. - File-backed SQLite opens two pools in WAL mode.
ctx.db.reader()holds 16 read-only connections for concurrentSELECTtraffic, andctx.db.writer()holds 1 writer connection. - Multi-step writes open
let mut tx = ctx.db.begin().await?;, which executesBEGIN IMMEDIATEon the writer pool so concurrent transactions never hit aSQLITE_BUSY_SNAPSHOTwrite-upgrade deadlock. - Full-text search uses SQLite FTS5 sanitized through
slabs::db::fts5_query. - Applications that outgrow single-node SQLite move to PostgreSQL through
slabs_db::PgDband the sameslabs db migrateandslabs db dump-schemaworkflow.
Opt-in Optimistic Offline Lock for shared records
When multiple users edit the same record concurrently across separate HTTP requests, Slabs uses an explicit, opt-in SQL Optimistic Offline Lock rather than ORM magic or hidden row-version hooks:
- Add
version INTEGER NOT NULL DEFAULT 1to shared editable tables in your migration. - Update with
UPDATE ... SET ..., version = version + 1 WHERE id = ? AND version = ?. - Check
rows_affected() == 0and returnErr(SlabError::conflict("..."))(409 Conflict) so the caller reloads the latest version instead of silently overwriting another user’s edit.
Keep this convention opt-in. Do not put version locks on append-only rows (messages, events, audit logs), hot counters (use atomic SET count = count + 1), or CRDT real-time collaborative documents where concurrent edits merge at the operation level.
4. Explicit code beats hidden callbacks and replay magic
Hidden model callbacks (before_save, after_commit) trigger side effects far from the code that ran the write. Implicit durable-workflow replay engines go further. They demand deterministic replay across code versions, break in-flight executions when someone reorders a branch or updates a crate, trap ordinary clock or HTTP calls inside wrapper APIs, and bury live business state inside opaque event logs.
Slabs rejects both hidden model callbacks and implicit workflow replay engines.
- Every protected handler calls
ctx.auth.require_session(&jar).await?(orrequire_admin,require_auth,require_write_auth), checks resource ownership againstsession.user_id, and callsctx.rate_limit.check(...)directly on line 1. - Multi-step workflows store their current state in a normal SQL column (
status = 'pending' | 'charged' | 'shipped' | 'failed') updated insideBEGIN IMMEDIATEtransactions. - When step 1 finishes, it updates the row state and calls
ctx.jobs.enqueue_in_tx(&mut tx, "step_2", payload).await?inside the same SQL transaction. If the transaction rolls back, the job never entersslabs_jobs. If a worker crashes,slabs_jobsretries with exponential backoff and moves exhausted jobs to"dead". - Any operator or agent can inspect every in-flight workflow with one
SELECTagainst application tables andslabs_jobs. Deploying new code never corrupts an opaque replay log.
5. Make invalid states fail at compile time or boot time
Security and correctness belong in automated checks, not in tribal memory.
- Every crate and generated app sets
unsafe_code = "forbid". Core crates enforcemissing_docs,missing_debug_implementations,unreachable_pub,rust_2018_idioms, andclippy::pedantic. Maud compiles HTML templates at build time and escapes interpolated strings automatically. AppEnv(Development,Test,Staging,Production, set viaSLABS_ENV) blocks unsafe settings before the server binds a socket. Instagingandproduction,SLABS_SECRET_KEYmust be at least 32 random bytes and cannot match the development placeholder. Cross-origin CORS (SLABS_CORS_ORIGINS) and proxy header trust (SLABS_TRUST_PROXY) stay off unless explicitly configured.slabs checkruns six steps in one command. It checks formatting acrosssrc/,slabs/, andjobs/, runs the[security]static scanner (flagging interpolated SQL insqlx::query*, unannotatedPreEscaped(,unsafeblocks or missingunsafe_code = "forbid", hardcoded secrets,.unwrap()or.expect(inslabs/andjobs/, and slabs without co-located tests), runs Clippy with-D warnings, builds Rustdoc with-D warnings, runs doctests, and runs parallel tests. Use--changedor--slab <feature>/<action>for targeted sub-second loops,--explainor--strict-explainto catch unintended SQLite full-tableSCANs,slabs manifest --diffto flag removed routes and[SECURITY]auth guard downgrades in PRs, andslabs dev --ephemeralfor collision-free parallel verification.slabs doctorchecks the Rust toolchain,unsafe_code = "forbid",schema.sql,.dockerignore,SLABS_ENVandSLABS_SECRET_KEYrules, and the security scan summary before you deploy.
6. Every slab tests itself in isolation
Tests live in #[cfg(test)] mod tests at the bottom of the slab file they verify.
Calling crate::test_app().await (gated behind #[cfg(test)] in src/lib.rs) boots a complete application backed by an isolated in-memory SQLite database (sqlite::memory:) with all system and application migrations applied and a fresh temporary storage directory.
- Tests share zero mutable database state.
cargo nextest runexecutes hundreds of slab tests in parallel across every CPU core in a few seconds.- When an agent edits
slabs/cards/create_card.rs, the test suite for that endpoint is already open in the same file.
7. Standard web platform over JavaScript build chains
Most web applications do not need a 500-megabyte node_modules tree, a bundler, a client-side router, and a JSON serialization layer duplicating server state.
Slabs renders HTML on the server and ships zero Node.js or npm tooling:
maud!templates andhtml::document(...)render typed HTML5 in Rust. Untrusted Markdown passes throughhtml::render_markdown(&text), which strips raw HTML tags and unsafe URL schemes so user input cannot inject scripts or HTMX attributes./_slabs/vendor/embeds MIT-licensed browser libraries directly in the binary, including Basecoat UI, HTMX 2, HTMX SSE, Idiomorph (hx-ext="morph"), and Alpine.js 3.- Modals use native
<dialog>, menus usepopover, page transitions use@view-transition { navigation: auto; }, and live updates stream over Server-Sent Events and WebSockets (slabs-realtimewithPresencetracking). slabs cssandslabs devrun the standalonetailwindcssv4 binary against@source "../slabs"with zero npm packages.
8. Single binary, boring infrastructure, zero-downtime deploys, and fast rollbacks
A Slabs application compiles to one native binary. Static assets are content-hashed under /assets/{hash}/{*path}, and SQL migrations compile into the binary through sqlx::migrate!("./migrations").
slabs new appgenerates a multi-stagecargo-chefDockerfile(cargo build --release --locked), a.dockerignore, a non-rootslabsuser (UID10001), read-only/app/assets,docker-entrypoint.sh, and pinned Litestreamv0.3.13continuous SQLite WAL replication to S3-compatible storage.GET /health/liveconfirms the process is alive,GET /health/readyverifies database connectivity and returns503while draining,GET /_slabs/metricsexposes operational counters behindSLABS_METRICS_TOKEN,SLABS_LOG_FORMAT=jsonemits structured logs, andSIGINTandSIGTERMdrain active HTTP requests, stop background workers, and runPRAGMA wal_checkpoint(TRUNCATE)on SQLite cleanly.slabs deploy init --target kamal|fly|vps --db sqlite|postgreswrites ready-to-edit configs for Kamal 2, Fly.io, and bare Linux VPS hosts running Caddy and hardenedsystemdunits.- PostgreSQL supports multi-replica rolling deploys. Single-volume SQLite runs one writer at a time (
boot.limit = 1withkamal-proxybuffering on Kamal 2, orstrategy = "immediate"on Fly.io) with a 20-secondSIGTERMdrain. - Pair expand-and-contract migrations with immutable git-SHA image tags so rolling back takes one command (
kamal rollback <sha>,fly releases rollback, or flipping asystemdsymlink) and finishes in seconds.
Why Transaction Scripts work for parallel AI agents
Slabs organizes every application around Martin Fowler’s Transaction Script pattern. Every HTTP endpoint lives in one file (slabs/<feature>/<action>.rs) and every background job lives in one file (jobs/<name>.rs). That layout removes the shared files and indirection layers that stall parallel work by both human teams and AI coding agents. See The Slabs doctrine for all eight architectural rules behind the framework.
The cost of layered MVC architectures
Traditional web frameworks split one user action across five or more directories, including a route table, a controller, a service class, a repository or ORM model, a serializer, and a separate test directory. That layout creates three concrete problems when multiple engineers or AI agents work at the same time:
- Every new endpoint edits the central router,
models/mod.rs, or a shared service file. Running ten agents in parallel guarantees rebase collisions on those shared files. - To verify a single write, an agent must open six files and trace implicit ORM callbacks, before-action filters, and dependency injection graphs. Hidden hooks (
before_save,after_commit) bury side effects far from the handler. - Shared DTO structs and generic repository traits break unrelated endpoints whenever one feature adds a field or changes a query shape.
How Slabs eliminates shared hotspots
Slabs replaces those layers with four concrete mechanisms:
slabs-buildruns from a one-linebuild.rs, scansslabs/<feature>/*.rsandjobs/*.rs, and writes$OUT_DIR/discovered_slabs.rs. Adding an endpoint touches zero existing files. Twenty agents can write twenty slabs in parallel with zero git merge conflicts.- One slab file holds the route definition (
pub fn slab() -> SlabDef), request and response types, explicit line-1 auth and rate-limit guards, parameterized SQL, explicitBEGIN IMMEDIATEtransaction boundaries, side-effect enqueues, HTML markup, and co-located#[cfg(test)] mod tests. An agent reads one file plusschema.sqland sees the full behavior. - Repeating a four-field
FromRowstruct or a five-lineSELECTquery in two slabs costs almost nothing and keeps features independent. You can delete or rewrite any slab without breaking another slab. schema.sqlholds every table, column, and index in one file, andGET /_slabs/manifest(in development) orslabs listprints every route and background job as structured metadata.
When to extract shared code
Slabs does not ban all shared code. It raises the bar for adding it. Put code in a library crate or a _-prefixed helper (_helpers.rs, which slabs-build skips) only when both conditions hold:
- The logic implements a stable, security-sensitive protocol or invariant (such as Argon2id hashing, HMAC webhook signing, FTS5 escaping, or CSRF verification).
- Divergent copies would create a correctness or security bug.
Everything else, including query projections, form structs, validation rules, and HTML fragments, belongs directly inside each slab.
Trade-offs to expect
- You write explicit SQL and local
FromRowstructs instead of callingUser::find(id). In return, every query is visible, tunable, and verified by co-located tests. - Because
cargo fmtskips files included fromOUT_DIR, teams and CI pipelines must runslabs fmt(orslabs check) alongsidecargo fmt. - Because slabs query tables directly, update
schema.sqlwithslabs db dump-schemaafter every migration so every contributor reads accurate column names.
SQLite WAL split pools and BEGIN IMMEDIATE
SQLite runs inside the same process as your Axum server, so queries pay zero network latency. Out of the box, however, default SQLite settings trigger SQLITE_BUSY and SQLITE_BUSY_SNAPSHOT errors under concurrent web traffic. slabs-db avoids both failure modes with split connection pools, tuned pragmas, and BEGIN IMMEDIATE write transactions.
Why single-pool SQLite fails under web concurrency
SQLite allows many concurrent readers alongside one active writer in Write-Ahead Logging (WAL) mode. When an application puts both reads and writes onto one general-purpose SqlitePool and opens default DEFERRED transactions (BEGIN), two bugs appear under load:
- Connection A starts a deferred
BEGIN, runs aSELECT, and holds a read snapshot. Connection B writes and commits. When Connection A later runs anINSERTorUPDATEinside the same transaction, SQLite cannot upgrade its stale read snapshot to a write lock and fails immediately withSQLITE_BUSY_SNAPSHOT, even with a 10-secondbusy_timeout. - Multiple connections competing for the write lock inside SQLite trigger retry loops and busy waits instead of queueing cleanly in Tokio.
How slabs_db::Db solves it
For every file-backed SQLite database, Db::connect creates two distinct SqlitePool instances:
ctx.db.reader()holds up to 16 connections opened withread_only(true)and a 5-secondbusy_timeout. Concurrent HTTP requests executeSELECTqueries in parallel without blocking writers or each other.ctx.db.writer()(aliased asctx.db.pool()) holds a single connection (max_connections(1)) with a 10-secondbusy_timeout. Tokio queues concurrent writers in memory on the pool semaphore instead of letting multiple SQLite connections collide on the file lock.
When you call ctx.db.begin().await?, slabs-db runs BEGIN IMMEDIATE on the single writer connection (begin_with("BEGIN IMMEDIATE")). SQLite acquires the write lock up front before any read runs inside the transaction, so a write-upgrade deadlock cannot happen.
Pragmas applied automatically
Db::connect sets these SQLite pragmas on startup:
| Pragma | Value | Effect |
|---|---|---|
journal_mode | WAL (file-backed only) | Readers do not block writers, and writers do not block readers. |
synchronous | NORMAL | Safe durability in WAL mode without an fsync on every transaction commit. |
foreign_keys | ON | Enforces REFERENCES and ON DELETE CASCADE constraints on every connection. |
cache_size | -64000 | Allocates roughly 64 MiB of page cache per connection. |
temp_store | MEMORY | Keeps temporary B-trees and sort buffers in RAM. |
mmap_size | 268435456 (file-backed only) | Memory-maps up to 256 MiB of the database file for fast read access. |
busy_timeout | 10s writer, 5s reader | Waits cleanly during brief checkpoints or external CLI migrations. |
In-memory databases during parallel tests
SQLite isolates :memory: databases per connection, so opening a second connection creates a separate empty database. When database_url is "sqlite::memory:" or contains "mode=memory", Db::connect clones the single writer pool for reader(). Your slabs still call ctx.db.reader() and ctx.db.begin() identically in production and in cargo nextest run.
Choosing between SQLite and PostgreSQL
SQLite with split WAL pools handles single-node web applications with thousands of reads per second and zero external database operations, and Litestream replicates WAL frames continuously to S3-compatible storage. Move to slabs_db::PgDb (DATABASE_URL=postgres://...) when you need multi-replica rolling deploys, horizontal write scaling, or PostgreSQL extensions.
HTML over the wire with Maud, Tailwind v4, Basecoat, HTMX, and Alpine
Slabs renders HTML directly in Rust without Node.js, npm, webpack, Vite, or a separate client-side single-page application layer. Every browser library in the stack is MIT-licensed and embedded directly into the slabs-http binary.
Why zero Node and zero JSON state duplication
Splitting a web app into a Rust JSON backend plus a React or TypeScript frontend doubles every change. You maintain duplicate types, duplicate validation, client-side routing, cache invalidation, and a Node build pipeline.
In Slabs, the server owns the database, validation, authorization, and HTML rendering in one file. When an agent writes a slab, rustc type-checks the SQL parameters, Rust variables, and Maud HTML markup in the same compilation unit.
How the five frontend pieces fit together
- Maud (
maud!macro inslabs-html) compiles HTML templates directly into Rust code that appends to aString. Every interpolated value is HTML-escaped at compile time.PreEscapedis omitted fromslabs::prelude::*on purpose so raw HTML requires an explicitslabs::html::PreEscapedimport, and untrusted Markdown runs throughhtml::render_markdown(&text). - Tailwind CSS v4 runs as a single standalone native binary via
misewith zeronode_modules.assets/input.csscontains@import "tailwindcss";and@source "../slabs";, soslabs cssscans every slab file and outputs a minifiedassets/styles/app.cssserved at a content-hashed/assets/{hash}/styles/app.cssURL withCache-Control: public, max-age=31536000, immutable. - Basecoat UI (
/_slabs/vendor/basecoat.min.cssandbasecoat.min.js) ships shadcn-style CSS tokens (--background,--foreground,--card,--border,--muted,--primary) and semantic HTML classes (.btn,.card,.input,.badge) with no React or Radix dependency. - HTMX 2, SSE, and Idiomorph (
/_slabs/vendor/htmx.min.js,htmx-ext-sse.js,idiomorph-ext.min.js) drive partial page updates (hx-get,hx-post,hx-target,hx-push-url), out-of-band updates (htmx::oob,htmx::oob_replace,htmx::oob_delete), live server pushes (sse-connect,sse-swap), and DOM diffing (hx-swap="morph:innerHTML").html::documentenableshx-ext="morph"on<body>and@view-transition { navigation: auto; }in<head>. - Alpine.js 3 (
/_slabs/vendor/alpine.min.js) and native HTML elements handle transient browser-only state such as keyboard shortcuts (@keydown.window), dropdown toggles, and copy buttons. Modals and popovers use native<dialog>and the HTMLpopoverattribute instead of custom focus-trap libraries.
Safe JSON embedding and guarded redirects
Two slabs-html helpers prevent common frontend injection and redirect bugs:
json_script("boot-data", &payload)?serializes structured data into<script type="application/json" id="boot-data">and escapes<,>,&, U+2028, and U+2029 so user strings cannot break out of the script tag.htmx::redirect(path)andhtmx::flash_redirect(...)verify thatpathis a safe relative path and fall back to"/"on open-redirect inputs such as//evil.com. Callredirect_external(url)when an endpoint intentionally redirects to another origin.
Progressive rendering with htmx::is_htmx
A single slab can serve both full browser navigations and partial HTMX swaps by checking htmx::is_htmx(&headers):
- On a normal browser request, return the full
html::document(...)shell with sidebar, navigation bar, and article content. - On an HTMX click (
HX-Request: truewithhx-target="#doc-article"andhx-push-url="true"), return only the<article>fragment plus anhtmx::oob_replacefor the sidebar active link or document<title>.
Direct URLs, browser back/forward buttons, and search engine crawlers work cleanly because every link is a standard <a href="..."> upgraded with hx-get.
Serving AI agents alongside browsers
Because routes return typed responses from self-contained slabs, exposing plain Markdown (/raw/{section}/{slug}) or /llms.txt alongside HTML pages takes a small sibling slab reading the same SQLite tables with zero client-side JavaScript overhead.
Glossary and architecture decision records
This page defines core Slabs terms and records the architecture decisions behind the framework.
Glossary
| Term | Definition |
|---|---|
AppCtx | Cheap-to-clone runtime state struct passed to every HTTP slab (State<AppCtx>) and background job (AppCtx). Holds handles to config, db, auth, jobs, mail, storage, cache, realtime, webhooks, assets, rate_limit, and audit. |
AppEnv | Deployment environment enum (Development, Test, Staging, Production) parsed from SLABS_ENV. Controls fail-closed validation, cookie_secure defaults, and dev-only routes. |
| Basecoat UI | MIT-licensed CSS and minimal JS library implementing shadcn visual tokens and component classes for plain server-rendered HTML. |
Discovery (slabs-build) | Compile-time scan of slabs/<feature>/*.rs and jobs/*.rs run from build.rs that writes $OUT_DIR/discovered_slabs.rs (collect_slabs() and collect_jobs()). |
__Host-slabs_session | Hardened session cookie name used whenever cookie_secure is true (Path=/, Secure, HttpOnly, SameSite=Lax, no Domain). |
| Idiomorph | DOM morphing extension for HTMX (hx-ext="morph", hx-swap="morph:innerHTML") that diffs incoming server HTML against the live DOM without losing input focus or scroll state. |
| Job | Background transaction script at jobs/<name>.rs that exports pub fn job() -> JobDef, queues in slabs_jobs, and runs on JobRegistry workers. |
| Magic link | Passwordless 6-character alphanumeric sign-in code stored as a keyed HMAC bound to (email, purpose) in slabs_magic_links, locked out after 5 failed attempts in 15 minutes, and consumed atomically with DELETE ... RETURNING. |
| Manifest | JSON document listing every registered route (RouteMeta) and job (JobMeta), mounted at GET /_slabs/manifest in development and test and printed by slabs list. |
| Outbox | The slabs_mail_outbox and slabs_webhook_deliveries SQLite tables that record emails and signed webhooks for inspection in development (GET /_slabs/mail) and isolated tests (TestApp::sent_emails). |
| Prefixed ULID | Lowercase 26-character Crockford Base32 ULID prefixed with a short entity tag (such as usr_01j..., job_01j..., req_01j...) generated by slabs::id::new(prefix). |
| Presence | In-memory tracking of online participants per realtime topic via ctx.realtime.track_presence and ctx.realtime.list_presence, backed by automatic cleanup on PresenceGuard drop. |
| Slab | Self-contained HTTP Transaction Script at slabs/<feature>/<action>.rs that exports pub fn slab() -> SlabDef and holds its own input/output structs, guards, SQL, HTML/JSON response, and co-located tests. |
Architecture decision records
ADR-001. Compile-time file discovery over a central router
Status is accepted. Parallel contributors and AI agents frequently collide on routes.rs and mod.rs files. Slabs scans slabs/<feature>/*.rs and jobs/*.rs in build.rs via slabs_build::discover(), skips mod.rs, _-prefixed files, and ./_-prefixed directories, and includes the generated file once in src/lib.rs via slabs::discover_slabs!(). Adding endpoints touches zero shared files. Because cargo fmt does not traverse OUT_DIR includes, slabs fmt formats both src/ and discovered files.
ADR-002. Raw parameterized SQL over an ORM
Status is accepted. ORMs hide N+1 queries, implicit callbacks, and schema drift behind generated structs and traits. Slabs requires raw parameterized SQL via sqlx::query and sqlx::query_as (with optional compile-time sqlx::query! via slabs db prepare) and treats schema.sql as the single-file schema reference. Every SQL query stays readable inline inside its slab. Contributors bind parameters explicitly and pass FTS5 input through slabs::db::fts5_query.
ADR-003. Split SQLite WAL pools and BEGIN IMMEDIATE
Status is accepted. Shared read/write SQLite pools with deferred transactions fail with SQLITE_BUSY_SNAPSHOT under concurrent HTTP load. Slabs opens a 16-connection read-only pool (reader()) and a 1-connection writer pool (writer()) on file-backed SQLite databases, and runs BEGIN IMMEDIATE in Db::begin(). For sqlite::memory: test databases, Db::connect shares one connection so in-memory tables remain visible across calls.
ADR-004. Explicit line-1 guards over implicit auth middleware
Status is accepted. Route-group middleware makes it hard to verify authorization rules when reading a single endpoint file in isolation. Slabs exposes explicit methods on ctx.auth (require_session, require_admin, require_auth, require_write_auth) and ctx.rate_limit.check(...) to call directly at the top of each handler. Reading line 1 of handle proves who can call the endpoint and what rate limit applies.
ADR-005. Two-tier Clippy policy and static security scanning
Status is accepted. Strict pedantic lints catch bugs and missing docs in shared framework crates, while creating friction inside rapidly authored app endpoints. Slabs enforces unsafe_code = "forbid", missing_docs = "warn", and clippy::pedantic on crates/*, applies focused guardrails on generated apps, and runs a built-in [security] static analyzer inside slabs check and slabs doctor.
ADR-006. Vendored MIT browser assets with zero Node runtime
Status is accepted. JavaScript bundlers, CDN links, and node_modules increase build latency and break offline work. Slabs embeds Basecoat UI, HTMX 2, SSE, Idiomorph, Alpine.js 3, and sw-register.js inside slabs-http under /_slabs/vendor/ and compiles Tailwind CSS v4 with the standalone binary via mise. Every Slabs app compiles and runs offline as one Rust binary plus static CSS.
ADR-007. Fail-closed production boot validation
Status is accepted. Silent development defaults (such as hardcoded signing keys, open CORS, unauthenticated metrics, and exposed /_slabs/mail routes) cause security incidents when copied to production. Slabs introduces AppEnv (SLABS_ENV) and runs AppConfig::validate() inside SlabsApp::boot. In staging and production, boot fails if SLABS_SECRET_KEY is missing or shorter than 32 bytes. Dev routes mount only in development and test, /_slabs/metrics requires SLABS_METRICS_TOKEN, and SLABS_CORS_ORIGINS and SLABS_TRUST_PROXY stay off unless configured.