Skip to main content

Crate slabs_http

Crate slabs_http 

Source
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, and RateLimiter.
  • Helpers: client_ip for proxy-aware IP extraction, and build_router, which combines discovered slabs, built-in endpoints, and the Tower middleware stack into an axum::Router.
  • Built-in routes mounted automatically by build_router:
    • GET /health and GET /_slabs/health: pings the database with SELECT 1 and returns {"status": "ok", "app": "<app_name>"}.
    • GET /health/live: liveness probe returning 200 OK JSON {"status": "ok"}.
    • GET /health/ready: readiness probe returning 503 Service Unavailable when draining or when SELECT 1 on the read pool fails, otherwise 200 OK.
    • GET /_slabs/metrics: Prometheus text (or JSON when Accept: 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, returns 404 unless metrics_token is set, and requires Authorization: Bearer <token> in constant time.
    • GET /_slabs/incidents, GET /_slabs/incidents/{id}, GET /_slabs/incidents/{id}/attachments/{blob_id}, and POST /_slabs/incidents/{id}/resolve: agent-oriented runtime incident inbox guarded by dev/test mode or constant-time SLABS_METRICS_TOKEN (Authorization: Bearer <token>).
    • Dev/test only (env.is_dev_or_test()): GET /_slabs/manifest, GET /_slabs/openapi.json, and GET /_slabs/mail.
    • GET /_slabs/vendor/{*path}: serves embedded basecoat.min.css (with @view-transition { navigation: auto; }), basecoat.min.js, htmx.min.js, htmx-ext-sse.js, idiomorph-ext.min.js, alpine.min.js, and sw-register.js with ETag and Cache-Control: public, max-age=86400.
    • GET /assets/{hash}/{*path}: serves content-hashed static files from ctx.assets with Cache-Control: public, max-age=31536000, immutable and a sandbox CSP on SVG/HTML/XHTML assets.

§Agent invariants

§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.
ClientIp
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 discovered JobDef handlers.
RateLimiter
Explicit in-memory fixed-window rate limiter for auth and sensitive slabs.
ScheduleDef
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::Router from discovered slabs, built-in endpoints, and middleware.
client_ip
Resolve the client’s IP address for logging and rate-limit keys.

Type Aliases§

JobHandlerFn
Type-erased async handler function stored in a JobDef.