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,SlabDef,JobDef,JobHandlerFn,ScheduleDef,JobRegistry, andRateLimiter. - Router builder:
build_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 /_slabs/health: pings the database withSELECT 1and returns{"status": "ok", "app": "<app_name>"}.GET /_slabs/manifest: returns the JSONslabs_core::AppManifestlisting all registered routes and jobs.GET /_slabs/openapi.json: returns anOpenAPI3.1.0 JSON document generated from the application manifest and optional slab JSON schemas.GET /_slabs/mail: returns up to 50 recent emails from the development outbox ({"emails": [...]}).GET /_slabs/vendor/{*path}: serves embeddedbasecoat.min.css,basecoat.min.js,htmx.min.js,htmx-ext-sse.js,idiomorph-ext.min.js, andalpine.min.jswithCache-Control: public, max-age=86400.GET /assets/{hash}/{*path}: serves content-hashed static files fromctx.assetswithCache-Control: public, max-age=31536000, immutable.
- Middleware stack order in
build_router(outermost to innermost on incoming requests):SetRequestIdLayer: assigns a time-sortable ULIDX-Request-Id(req_<ulid>) when absent.TraceLayer: records HTTP request and response tracing spans.PropagateRequestIdLayer: copiesX-Request-Idonto the response.CorsLayer::permissive(): sets permissive CORS headers.SetResponseHeaderLayer: setsX-Frame-Options: SAMEORIGINif absent.SetResponseHeaderLayer: setsX-Content-Type-Options: nosniffif absent.RequestBodyLimitLayer: limits request bodies to 25 MiB.CompressionLayer: compresses responses with gzip and brotli (br).
§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 in-memory per process 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.
- 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.
Type Aliases§
- JobHandler
Fn - Type-erased async handler function stored in a
JobDef.