slabs-framework 0.3.0

Batteries-included, agent-first Transaction Script web framework in Rust
Documentation

Slabs

A batteries-included Rust web framework built for parallel AI agents and humans. Every HTTP endpoint is a self-contained Transaction Script with raw SQL, explicit transactions, and compile-time discovery, so multiple contributors can ship features in parallel with zero merge conflicts.

Quickstart

Install the pinned toolchain (rust, standalone tailwindcss v4, and cargo-nextest) with mise, then run the workspace verification suite or generate a new application:

mise install

# Run all core crate tests and doctests
mise exec -- cargo test --doc --workspace
mise exec -- cargo nextest run --workspace

# Install the slabs CLI locally
mise exec -- cargo install --path crates/slabs-cli

# Generate a new standalone Slabs app with cargo-chef Dockerfile, Litestream, bundled skills, and CI
slabs new app my_app

What a slab looks like

Each endpoint lives in its own file under slabs/<feature>/<action>.rs. There is no central routes.rs, no ORM, and no models/ or controllers/ hierarchy. slabs-build discovers every file at compile time and registers its route automatically.

// slabs/cards/create_card.rs
use axum::{extract::State, http::StatusCode, Json};
use axum_extra::extract::CookieJar;
use serde::{Deserialize, Serialize};
use slabs::prelude::*;

pub fn slab() -> SlabDef {
    SlabDef::post("/api/boards/{board_id}/cards", handle)
        .name("cards.create_card")
        .summary("Create a card and enqueue watcher notifications atomically")
}

#[derive(Debug, Deserialize)]
pub struct Input {
    pub title: String,
}

#[derive(Debug, Serialize)]
pub struct Output {
    pub id: String,
    pub title: String,
}

async fn handle(
    State(ctx): State<AppCtx>,
    jar: CookieJar,
    axum::extract::Path(board_id): axum::extract::Path<String>,
    Json(input): Json<Input>,
) -> SlabResult<(StatusCode, Json<Output>)> {
    let session = ctx.auth.require_session(&jar).await?;
    ctx.rate_limit
        .check(&format!("cards:create:{}", session.user_id), 60, 60)?;

    let title = input.title.trim().to_string();
    if title.is_empty() {
        return Err(SlabError::bad_request("title is required"));
    }

    let card_id = id::new("crd");
    let mut tx = ctx.db.begin().await?;

    sqlx::query("INSERT INTO cards (id, board_id, creator_id, title) VALUES (?, ?, ?, ?)")
        .bind(&card_id)
        .bind(&board_id)
        .bind(&session.user_id)
        .bind(&title)
        .execute(&mut *tx)
        .await?;

    ctx.jobs
        .enqueue_in_tx(
            &mut tx,
            "notify_watchers",
            serde_json::json!({ "card_id": card_id }),
        )
        .await?;

    tx.commit().await?;
    Ok((StatusCode::CREATED, Json(Output { id: card_id, title })))
}

Architecture

Read DOCTRINE.md for the eight pillars behind Slabs. At the crate level, Slabs combines Axum 0.8 and SQLx 0.8 with explicit, low-level libraries attached to AppCtx:

  • Compile-time file discovery. A one-line build.rs calls slabs_build::discover(), generating $OUT_DIR/discovered_slabs.rs from slabs/<feature>/*.rs and jobs/*.rs. src/lib.rs includes it with slabs::discover_slabs!() and passes collect_slabs(), collect_jobs(), and sqlx::migrate!("./migrations") into SlabsApp::boot(...).
  • Split SQLite WAL pools and PostgreSQL support. AppCtx.db opens a 16-connection read-only pool (ctx.db.reader()) and a dedicated 1-connection writer pool (ctx.db.writer(), where ctx.db.begin() runs BEGIN IMMEDIATE). slabs_db::PgDb and slabs db migrate / dump-schema also support standalone PostgreSQL connections (DATABASE_URL=postgres://...).
  • Optional compile-time SQL checks. Write raw sqlx::query statements immediately, or run slabs db prepare to generate offline .sqlx/ metadata for compile-time checked sqlx::query! and sqlx::query_as!.
  • MIT-licensed HTML frontend with zero Node. Render typed HTML in Rust with maud! and html::document(title, &ctx.assets.stylesheet_urls(), &ctx.assets.behavior_urls(), body), render untrusted Markdown safely with html::render_markdown(&text), style with standalone Tailwind CSS v4 and vendored Basecoat UI (shadcn tokens for plain HTML), update pages with HTMX 2, SSE, and Idiomorph (hx-ext="morph"), and handle local state with Alpine.js 3, native <dialog>, and @view-transition { navigation: auto; }.
  • Fail-closed security and production defaults. AppEnv (SLABS_ENV=development|staging|production) enforces a 32-byte random SLABS_SECRET_KEY in staging and production. Axum serves gzip and brotli compression, ULID X-Request-Id headers, Fetch Metadata CSRF protection, opt-in CORS (SLABS_CORS_ORIGINS), gated proxy trust (SLABS_TRUST_PROXY), X-Frame-Options: SAMEORIGIN, X-Content-Type-Options: nosniff, 25 MiB body limits, GET /health/ready, GET /_slabs/metrics, explicit in-memory rate limiting (ctx.rate_limit.check), JSON logging (SLABS_LOG_FORMAT=json), and graceful SIGINT/SIGTERM shutdown for HTTP and background workers.
  • Built-in incident tracking and per-route latency telemetry. Every Slabs app records deduplicated runtime errors (http_5xx, panic, job_dead, client_error) and slow operations (slow_request, slow_job) in the slabs_incidents system table, exposes GET /_slabs/incidents, GET /_slabs/incidents/{id}, POST /_slabs/incidents/{id}/resolve, and POST /_slabs/client-errors, tracks per-route latency histograms (p50/p95/p99/max, slow counts, 5xx counts) in GET /_slabs/metrics, and ships Db::explain_query_plan for indexed query verification in tests.

Agent skills

Slabs ships five procedural skills in skills/ for AI coding agents working on Slabs applications (and slabs new app bundles all five into .claude/skills/):

Skill Purpose
skills/add-slab/SKILL.md End-to-end procedure for authoring, guarding, testing, and formatting a new Transaction Script.
skills/add-migration/SKILL.md Expand-and-contract schema migration, schema.sql refresh, and .sqlx/ preparation workflow.
skills/review-slab/SKILL.md Audit checklist for Slabs-specific transaction, security, HTML, and formatting pitfalls.
skills/deploy-app/SKILL.md Production pre-flight checks, zero-downtime deployment, and rollback checklist for Kamal 2, Fly.io, and VPS hosts.
skills/fix-incident/SKILL.md Closed-loop triage, reproduction, query-plan inspection, and fix workflow for runtime incidents and slow routes.

Workspace crates

Crate Responsibility
slabs-framework (use slabs::...) Top-level facade, prelude::*, discover_slabs!(), SlabsApp::boot, SlabsApp::serve, and init_tracing().
slabs-build Build-script scanner that generates $OUT_DIR/discovered_slabs.rs from slabs/ and jobs/.
slabs-core Prefixed ULIDs (id::new), URL slugs (slug::slugify), fractional positions (position::between), SHA-256 fingerprint, SlabError HTTP mapping, AppEnv, AppConfig, and AppManifest.
slabs-db Split SQLite WAL pools, PgDb PostgreSQL pool, system migrations (including slabs_incidents), QueryBuilder, explain_query_plan, fts5_query, AuditLog, cursor pagination, and dump_schema_sql.
slabs-auth Async Argon2id password hashing, cookie sessions, single-use 6-character magic links, signed expiring tokens, and SHA-256 Bearer access tokens.
slabs-http Axum 0.8 router builder, AppCtx, SlabDef, JobDef, ScheduleDef, RateLimiter, Fetch Metadata CSRF, /health/ready, /_slabs/metrics with per-route histograms, /_slabs/incidents, /_slabs/client-errors, vendored UI assets, and middleware.
slabs-html Maud re-exports, HTML document shell, safe render_markdown, signed flash cookies, HTMX HX-* and hx-swap-oob helpers, and CSRF helpers.
slabs-assets Content-hashed static asset loader (/assets/{hash}/{*path}) with immutable cache headers.
slabs-jobs SQLite-backed durable job queue with transactional enqueue_in_tx, exponential backoff, and dead-lettering.
slabs-mail Outbox mailer with Resend HTTP API (SLABS_RESEND_API_KEY) and SMTP (SLABS_SMTP_URL) transports.
slabs-storage Local disk storage and path-style AWS SigV4 S3 backend (AWS S3, Cloudflare R2, MinIO, Tigris) with safe blob serving and opt-in image resizing.
slabs-cache SQLite TTL key-value cache with RFC 3339 expiration and lazy purging.
slabs-realtime In-process broadcast hub for SSE streams (publish_html, publish_json), WebSockets, and Presence tracking.
slabs-webhooks HMAC-SHA256 signed outbound and inbound webhooks with transactional dispatch and DNS-resolving SSRF blocking.
slabs-test Ephemeral in-memory TestApp::boot helper for isolated parallel slab tests.
slabs-cli slabs CLI for app and slab generation, [security] static analysis, doctor, deploy init, incidents, formatting, database tasks, Tailwind builds, and live dev.

CLI commands

Run the CLI from this workspace with mise exec -- cargo run -p slabs-cli -- [--app-dir <dir>] <command>, or install the slabs binary locally with cargo install --path crates/slabs-cli.

Command Action
slabs new app <name> Create a standalone PWA-ready Slabs app with cargo-chef + Litestream Dockerfile, docker-entrypoint.sh, .dockerignore, bundled .claude/skills/, seeds.sql, gentle Clippy defaults, CLAUDE.md, and GitHub Actions CI.
slabs new slab <feature> <name> [--method <verb>] [--path <route>] Create slabs/<feature>/<name>.rs with validated identifiers, starter guard, and co-located test without editing any existing file.
slabs new job <name> Create jobs/<name>.rs without editing any existing file.
slabs fmt [--check] Format the crate and all auto-discovered files under slabs/ and jobs/.
slabs check [--workspace] [--no-docs] Run the 6-step CI suite (formatting, [security] static scan, Clippy -D warnings, Rustdoc -D warnings, doctests, and cargo nextest or cargo test).
slabs doctor Verify Rust toolchain, unsafe_code = "forbid", schema.sql, .dockerignore, SLABS_ENV/SLABS_SECRET_KEY, and security scan summary.
slabs deploy init --target <kamal|fly|vps> Generate zero-downtime deployment templates (config/deploy.yml, fly.toml, or deploy/Caddyfile + hardened systemd unit).
slabs incidents <list|show|resolve|perf> Inspect open or resolved incidents from /_slabs/incidents, view full incident detail, mark incidents resolved with a commit SHA, or print per-route latency percentiles (p50/p95/p99/max) ranked slowest first from /_slabs/metrics.
slabs dev Run standalone Tailwind CSS v4 --watch alongside cargo watch (or cargo run).
slabs css [--watch] Compile assets/input.css to assets/styles/app.css with Tailwind CSS v4.
slabs db migrate Apply SQL migrations from migrations/ to SQLite or PostgreSQL.
slabs db dump-schema Write the live database schema snapshot to schema.sql.
slabs db seed Apply an idempotent SQL seed script (seeds.sql) to SQLite or PostgreSQL.
slabs db prepare Generate offline .sqlx/ metadata for compile-time checked sqlx::query!.
slabs list Print all discovered slabs and jobs in an app directory.

Reference applications

Three full-stack applications rebuilt from Ruby on Rails live in sogamoso/slabs-examples:

  • Campfire (rebuilt from basecamp/once-campfire): group chat with 27 slabs, 2 jobs, FTS5 message search, SSE live rooms, boosts, file uploads, and webhook bots.
  • Fizzy (rebuilt from basecamp/fizzy): Kanban tracker with 28 slabs, 2 jobs, passwordless magic links, Bearer API tokens, multi-filter board views, native <dialog> card modals with Idiomorph, signed webhooks, and an entropy cron job.
  • Writebook (rebuilt from basecamp/writebook): book publishing app with 25 slabs, 1 job, Markdown pages, section dividers, multipart picture uploads, SHA-256 fingerprint conflict detection, O(1) fractional leaf reordering, revision history, and FTS5 porter search.

Formatting, linting, and CI

Core crates enforce default rustfmt, unsafe_code = "forbid", missing_docs, missing_debug_implementations, unreachable_pub, rust_2018_idioms, clippy::pedantic, and permissive OSS licenses (deny.toml). User apps generated by slabs new app enforce gentle guardrails (unsafe_code = "forbid", dbg_macro, todo, unimplemented, await_holding_lock, await_holding_refcell_ref).

Run the full CI check locally in one command:

mise exec -- cargo run -q -p slabs-cli -- check

Or run each step individually:

mise exec -- cargo fmt --all -- --check
mise exec -- cargo clippy --workspace --all-targets -- -D warnings
RUSTDOCFLAGS="-D warnings" mise exec -- cargo doc --workspace --no-deps
mise exec -- cargo test --doc --workspace
mise exec -- cargo nextest run --workspace

Contributing, releasing, and security

License

MIT. See LICENSE.