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![...])