Expand description
HTTP router assembly, shared application context, background job dispatch, rate limiting, and built-in endpoints for Slabs.
§What this crate owns
- Types:
AppCtx,ClientIp,SlabDef,JobDef,JobHandlerFn,ScheduleDef,JobRegistry, andRateLimiter. - Helpers:
client_ipfor proxy-aware IP extraction, andbuild_router, which combines discovered slabs, built-in endpoints, and the Tower middleware stack into anaxum::Router. - Built-in routes mounted automatically by
build_router:GET /healthandGET /_slabs/health: pings the database withSELECT 1and returns{"status": "ok", "app": "<app_name>"}.GET /health/live: liveness probe returning200 OKJSON{"status": "ok"}.GET /health/ready: readiness probe returning503 Service Unavailablewhen draining or whenSELECT 1on the read pool fails, otherwise200 OK.GET /_slabs/metrics: Prometheus text (or JSON whenAccept: application/json) metrics covering HTTP counts, per-route latency histograms (p50/p95/p99), open incident count, job queue stats, and active realtime topics. In staging/production, returns404unlessmetrics_tokenis set, and requiresAuthorization: Bearer <token>in constant time.GET /_slabs/incidents,GET /_slabs/incidents/ui,GET /_slabs/incidents/{id},GET /_slabs/incidents/{id}/attachments/{blob_id},POST /_slabs/incidents/{id}/claim,POST /_slabs/incidents/{id}/link,POST /_slabs/incidents/{id}/ignore, andPOST /_slabs/incidents/{id}/resolve: operator dashboard, attachment download, and agent-oriented runtime incident endpoints guarded by dev/test mode, constant-timeSLABS_METRICS_TOKEN, or an authenticated admin session.POST /_slabs/client-errors: rate-limited (20 req/60s per IP, 4 KiB cap) browser/HTMX error beacon recordingclient_errorincidents with query strings stripped.POST /_slabs/bug-reports: feature-gated (SLABS_BUG_REPORTER), rate-limited (10 req/300s) multipart user bug reporter storing optional screenshots and attachments inctx.storageand recordinguser_bug_reportincidents.- Dev/test only (
env.is_dev_or_test()):GET /_slabs/manifest,GET /_slabs/openapi.json, andGET /_slabs/mail. GET /_slabs/vendor/{*path}: serves embeddedbasecoat.min.css(with@view-transition { navigation: auto; }),basecoat.min.js,htmx.min.js,htmx-ext-sse.js,idiomorph-ext.min.js,alpine.min.js,sw-register.js,slabs-telemetry.js, andslabs-bug-report.jswithETagandCache-Control: public, max-age=86400.GET /assets/{hash}/{*path}: serves content-hashed static files fromctx.assetswithCache-Control: public, max-age=31536000, immutableand a sandbox CSP on SVG/HTML/XHTML assets.
§Agent invariants
- Use Axum 0.8
{param}and{*wildcard}path syntax inSlabDefconstructors. Do not use:paramor*wildcard. - Multiple slabs may register the same path with different HTTP verbs (for example
GET /api/roomsandPOST /api/rooms).build_routergroups slabs by path and merges eachaxum::routing::MethodRouterautomatically. - Call
ctx.rate_limit.check(key, max_requests, window_secs)?explicitly in auth or sensitive slabs.RateLimiteris bounded in memory (50,000 entries max) and returns HTTP 429 (SlabError::TooManyRequests) with aRetry-Afterheader. - Pass a
tokio::sync::watch::Receiver<bool>toJobRegistry::spawn_workers_with_shutdownandJobRegistry::spawn_schedules_with_shutdownso workers and schedules stop cleanly during shutdown. JobRegistry::newalways registers the built-inslabs.deliver_webhookhandler unless an application job overrides that name.
§Example
use axum::{extract::{Path, State}, Json};
use serde_json::{json, Value};
use slabs_core::SlabResult;
use slabs_http::{build_router, AppCtx, SlabDef};
pub fn slab() -> SlabDef {
SlabDef::post("/api/rooms/{room_id}/messages", handle)
.name("messages.create")
.summary("Post a message to a room")
}
async fn handle(
State(ctx): State<AppCtx>,
Path(room_id): Path<String>,
) -> SlabResult<Json<Value>> {
ctx.rate_limit.check(&format!("room_msg:{room_id}"), 30, 60)?;
Ok(Json(json!({ "room_id": room_id })))
}
fn assemble(ctx: AppCtx) -> axum::Router {
build_router(ctx, vec![slab()], &[])
}Structs§
- AppCtx
- Shared runtime context passed to every HTTP slab handler and background job.
- Client
Ip - Axum request-parts extractor resolving the client’s IP address via
client_ip. - JobDef
- Self-contained Background Job Transaction Script definition returned by
pub fn job() -> JobDef. - JobRegistry
- Dispatches
SQLite-queued jobs to discoveredJobDefhandlers. - Rate
Limiter - Explicit in-memory fixed-window rate limiter for auth and sensitive slabs.
- Schedule
Def - Recurring maintenance schedule that enqueues a registered job on a fixed interval.
- SlabDef
- Self-contained HTTP Transaction Script definition returned by
pub fn slab() -> SlabDef.
Functions§
- build_
router - Assemble the full
axum::Routerfrom discovered slabs, built-in endpoints, and middleware. - client_
ip - Resolve the client’s IP address for logging and rate-limit keys.
Type Aliases§
- JobHandler
Fn - Type-erased async handler function stored in a
JobDef.