Skip to main content

slabs_http/
lib.rs

1//! HTTP router assembly, shared application context, background job dispatch, rate limiting, and built-in endpoints for Slabs.
2//!
3//! # What this crate owns
4//!
5//! - Types: [`AppCtx`], [`SlabDef`], [`JobDef`], [`JobHandlerFn`], [`ScheduleDef`], [`JobRegistry`], and [`RateLimiter`].
6//! - Router builder: [`build_router`], which combines discovered slabs, built-in endpoints, and the Tower middleware stack into an [`axum::Router`].
7//! - Built-in routes mounted automatically by [`build_router`]:
8//!   - `GET /_slabs/health`: pings the database with `SELECT 1` and returns `{"status": "ok", "app": "<app_name>"}`.
9//!   - `GET /_slabs/manifest`: returns the JSON [`slabs_core::AppManifest`] listing all registered routes and jobs.
10//!   - `GET /_slabs/openapi.json`: returns an `OpenAPI` 3.1.0 JSON document generated from the application manifest and optional slab JSON schemas.
11//!   - `GET /_slabs/mail`: returns up to 50 recent emails from the development outbox (`{"emails": [...]}`).
12//!   - `GET /_slabs/vendor/{*path}`: serves embedded `basecoat.min.css`, `basecoat.min.js`, `htmx.min.js`, `htmx-ext-sse.js`, `idiomorph-ext.min.js`, and `alpine.min.js` with `Cache-Control: public, max-age=86400`.
13//!   - `GET /assets/{hash}/{*path}`: serves content-hashed static files from `ctx.assets` with `Cache-Control: public, max-age=31536000, immutable`.
14//! - Middleware stack order in [`build_router`] (outermost to innermost on incoming requests):
15//!   1. `SetRequestIdLayer`: assigns a time-sortable ULID `X-Request-Id` (`req_<ulid>`) when absent.
16//!   2. `TraceLayer`: records HTTP request and response tracing spans.
17//!   3. `PropagateRequestIdLayer`: copies `X-Request-Id` onto the response.
18//!   4. `CorsLayer::permissive()`: sets permissive CORS headers.
19//!   5. `SetResponseHeaderLayer`: sets `X-Frame-Options: SAMEORIGIN` if absent.
20//!   6. `SetResponseHeaderLayer`: sets `X-Content-Type-Options: nosniff` if absent.
21//!   7. `RequestBodyLimitLayer`: limits request bodies to 25 MiB.
22//!   8. `CompressionLayer`: compresses responses with gzip and brotli (`br`).
23//!
24//! # Agent invariants
25//!
26//! - Use Axum 0.8 `{param}` and `{*wildcard}` path syntax in [`SlabDef`] constructors. Do not use `:param` or `*wildcard`.
27//! - Multiple slabs may register the same path with different HTTP verbs (for example `GET /api/rooms` and `POST /api/rooms`). [`build_router`] groups slabs by path and merges each [`axum::routing::MethodRouter`] automatically.
28//! - Call `ctx.rate_limit.check(key, max_requests, window_secs)?` explicitly in auth or sensitive slabs. `RateLimiter` is in-memory per process and returns HTTP 429 (`SlabError::TooManyRequests`) with a `Retry-After` header.
29//! - Pass a [`tokio::sync::watch::Receiver<bool>`] to [`JobRegistry::spawn_workers_with_shutdown`] and [`JobRegistry::spawn_schedules_with_shutdown`] so workers and schedules stop cleanly during shutdown.
30//! - [`JobRegistry::new`] always registers the built-in `slabs.deliver_webhook` handler unless an application job overrides that name.
31//!
32//! # Example
33//!
34//! ```rust,no_run
35//! use axum::{extract::{Path, State}, Json};
36//! use serde_json::{json, Value};
37//! use slabs_core::SlabResult;
38//! use slabs_http::{build_router, AppCtx, SlabDef};
39//!
40//! pub fn slab() -> SlabDef {
41//!     SlabDef::post("/api/rooms/{room_id}/messages", handle)
42//!         .name("messages.create")
43//!         .summary("Post a message to a room")
44//! }
45//!
46//! async fn handle(
47//!     State(ctx): State<AppCtx>,
48//!     Path(room_id): Path<String>,
49//! ) -> SlabResult<Json<Value>> {
50//!     ctx.rate_limit.check(&format!("room_msg:{room_id}"), 30, 60)?;
51//!     Ok(Json(json!({ "room_id": room_id })))
52//! }
53//!
54//! fn assemble(ctx: AppCtx) -> axum::Router {
55//!     build_router(ctx, vec![slab()], &[])
56//! }
57//! ```
58
59use axum::{
60    extract::{Path, State},
61    handler::Handler,
62    http::{header, HeaderValue, StatusCode},
63    response::{IntoResponse, Response},
64    routing::{delete, get, patch, post, put, MethodRouter},
65    Json, Router,
66};
67use futures_util::future::BoxFuture;
68use serde_json::{json, Value};
69use slabs_assets::Assets;
70use slabs_auth::Auth;
71use slabs_cache::Cache;
72use slabs_core::{AppConfig, AppManifest, JobMeta, RouteMeta, SlabError, SlabResult};
73use slabs_db::{AuditLog, Db};
74use slabs_jobs::Jobs;
75use slabs_mail::{MailTransport, Mailer};
76use slabs_realtime::Realtime;
77use slabs_storage::{S3Config, Storage, StorageBackend};
78use slabs_webhooks::Webhooks;
79use std::collections::{btree_map::Entry, BTreeMap, HashMap};
80use std::fmt;
81use std::future::Future;
82use std::sync::{Arc, Mutex};
83use std::time::{Duration, Instant};
84use tokio::sync::watch;
85use tower_http::{
86    compression::CompressionLayer,
87    cors::CorsLayer,
88    limit::RequestBodyLimitLayer,
89    request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer},
90    set_header::SetResponseHeaderLayer,
91    trace::TraceLayer,
92};
93
94/// Generates time-sortable prefixed ULID `X-Request-Id` headers (`req_01j...`).
95#[derive(Clone, Default)]
96struct MakeUlidRequestId;
97
98impl MakeRequestId for MakeUlidRequestId {
99    fn make_request_id<B>(&mut self, _request: &http::Request<B>) -> Option<RequestId> {
100        let id = slabs_core::id::new("req");
101        HeaderValue::from_str(&id).ok().map(RequestId::new)
102    }
103}
104
105/// Explicit in-memory fixed-window rate limiter for auth and sensitive slabs.
106#[derive(Debug, Clone, Default)]
107pub struct RateLimiter {
108    buckets: Arc<Mutex<HashMap<String, (u64, Instant)>>>,
109}
110
111impl RateLimiter {
112    /// Create a new empty in-memory rate limiter.
113    #[must_use]
114    pub fn new() -> Self {
115        Self::default()
116    }
117
118    /// Increment the counter for `key` and return the remaining quota for the current window.
119    ///
120    /// Returns HTTP 429 (`SlabError::TooManyRequests`) with a `Retry-After` duration when `key`
121    /// reaches `max_requests` within `window_secs`.
122    pub fn check(&self, key: &str, max_requests: u64, window_secs: u64) -> SlabResult<u64> {
123        let now = Instant::now();
124        let window = Duration::from_secs(window_secs.max(1));
125        let mut guard = self.buckets.lock().expect("rate limiter mutex poisoned");
126
127        // Opportunistically prune expired entries if map grows large
128        if guard.len() > 10_000 {
129            guard.retain(|_, (_, expires_at)| *expires_at > now);
130        }
131
132        let entry = guard.entry(key.to_string()).or_insert((0, now + window));
133
134        if entry.1 <= now {
135            entry.0 = 0;
136            entry.1 = now + window;
137        }
138
139        if entry.0 >= max_requests {
140            let retry_after = entry.1.saturating_duration_since(now).as_secs().max(1);
141            return Err(SlabError::too_many_requests(
142                retry_after,
143                "rate limit exceeded, please try again shortly",
144            ));
145        }
146
147        entry.0 += 1;
148        Ok(max_requests - entry.0)
149    }
150}
151
152/// Shared runtime context passed to every HTTP slab handler and background job.
153///
154/// Every field is an explicit subsystem handle backed by `SQLite` or in-process state, with no ORM
155/// or hidden middleware state.
156#[derive(Debug, Clone)]
157pub struct AppCtx {
158    /// Runtime application configuration loaded from environment variables or defaults.
159    pub config: AppConfig,
160    /// Shared database connection pool.
161    pub db: Db,
162    /// Authentication, session, magic-link, and access-token helper.
163    pub auth: Auth,
164    /// Durable SQLite-backed background job queue.
165    pub jobs: Jobs,
166    /// Outbound email delivery and development outbox mailer.
167    pub mail: Mailer,
168    /// Local or S3-compatible blob storage handle.
169    pub storage: Storage,
170    /// SQLite-backed key/value cache.
171    pub cache: Cache,
172    /// In-process topic broadcast hub for SSE and `WebSocket` updates.
173    pub realtime: Realtime,
174    /// Outbound signed webhook subscription and delivery manager.
175    pub webhooks: Webhooks,
176    /// Content-hashed static asset registry.
177    pub assets: Assets,
178    /// In-memory fixed-window rate limiter.
179    pub rate_limit: RateLimiter,
180    /// Transactional SQLite-backed audit log.
181    pub audit: AuditLog,
182}
183
184impl AppCtx {
185    /// Initialize database connections and all framework subsystems from `config`.
186    pub async fn connect(config: AppConfig) -> SlabResult<Self> {
187        let db = Db::connect(&config.database_url).await?;
188        let auth = Auth::new(db.clone(), config.secret_key.clone(), config.cookie_secure);
189        let jobs = Jobs::new(db.clone());
190        let mail = Mailer::with_transport(
191            db.clone(),
192            format!("noreply@{}.local", config.app_name),
193            MailTransport::from_env(),
194        );
195        let storage_backend = match S3Config::from_env() {
196            Some(s3) => StorageBackend::S3(s3),
197            None => StorageBackend::Local {
198                root_dir: config.storage_dir.clone(),
199            },
200        };
201        let storage = Storage::with_backend(db.clone(), storage_backend);
202        let cache = Cache::new(db.clone());
203        let realtime = Realtime::new();
204        let webhooks = Webhooks::new(db.clone(), jobs.clone());
205        let assets = Assets::from_dir(&config.assets_dir);
206        let rate_limit = RateLimiter::new();
207        let audit = AuditLog::new(db.clone());
208
209        Ok(Self {
210            config,
211            db,
212            auth,
213            jobs,
214            mail,
215            storage,
216            cache,
217            realtime,
218            webhooks,
219            assets,
220            rate_limit,
221            audit,
222        })
223    }
224}
225
226/// Self-contained HTTP Transaction Script definition returned by `pub fn slab() -> SlabDef`.
227///
228/// Route paths use Axum 0.8 `{param}` and `{*wildcard}` syntax.
229#[derive(Debug)]
230pub struct SlabDef {
231    /// HTTP method handled by this slab (e.g. `"GET"`, `"POST"`).
232    pub method: String,
233    /// Route path pattern registered on the Axum router.
234    pub path: String,
235    /// Logical slab name (commonly `<feature>.<action>`).
236    pub name: String,
237    /// Feature grouping label for manifest inspection.
238    pub feature: String,
239    /// Short human-readable description of the endpoint.
240    pub summary: String,
241    /// Optional JSON Schema describing the expected request body for `OpenAPI` export.
242    pub input_schema: Option<Value>,
243    /// Optional JSON Schema describing the response body for `OpenAPI` export.
244    pub output_schema: Option<Value>,
245    /// Axum method router wrapping the slab's handler.
246    pub router: MethodRouter<AppCtx>,
247}
248
249impl SlabDef {
250    /// Define a `GET` slab at `path`.
251    pub fn get<H, T>(path: impl Into<String>, handler: H) -> Self
252    where
253        H: Handler<T, AppCtx>,
254        T: 'static,
255    {
256        Self::new("GET", path, get(handler))
257    }
258
259    /// Define a `POST` slab at `path`.
260    pub fn post<H, T>(path: impl Into<String>, handler: H) -> Self
261    where
262        H: Handler<T, AppCtx>,
263        T: 'static,
264    {
265        Self::new("POST", path, post(handler))
266    }
267
268    /// Define a `PUT` slab at `path`.
269    pub fn put<H, T>(path: impl Into<String>, handler: H) -> Self
270    where
271        H: Handler<T, AppCtx>,
272        T: 'static,
273    {
274        Self::new("PUT", path, put(handler))
275    }
276
277    /// Define a `PATCH` slab at `path`.
278    pub fn patch<H, T>(path: impl Into<String>, handler: H) -> Self
279    where
280        H: Handler<T, AppCtx>,
281        T: 'static,
282    {
283        Self::new("PATCH", path, patch(handler))
284    }
285
286    /// Define a `DELETE` slab at `path`.
287    pub fn delete<H, T>(path: impl Into<String>, handler: H) -> Self
288    where
289        H: Handler<T, AppCtx>,
290        T: 'static,
291    {
292        Self::new("DELETE", path, delete(handler))
293    }
294
295    fn new(method: &str, path: impl Into<String>, router: MethodRouter<AppCtx>) -> Self {
296        let path = path.into();
297        Self {
298            method: method.to_string(),
299            name: format!("{method} {path}"),
300            feature: "default".to_string(),
301            summary: String::new(),
302            input_schema: None,
303            output_schema: None,
304            path,
305            router,
306        }
307    }
308
309    /// Set the slab's logical name, automatically deriving `feature` from a `<feature>.<action>` prefix.
310    #[must_use]
311    pub fn name(mut self, name: impl Into<String>) -> Self {
312        let n = name.into();
313        if let Some((feat, _)) = n.split_once('.') {
314            self.feature = feat.to_string();
315        }
316        self.name = n;
317        self
318    }
319
320    /// Explicitly set the slab's feature group name.
321    #[must_use]
322    pub fn feature(mut self, feature: impl Into<String>) -> Self {
323        self.feature = feature.into();
324        self
325    }
326
327    /// Set a short human-readable summary for the route manifest.
328    #[must_use]
329    pub fn summary(mut self, summary: impl Into<String>) -> Self {
330        self.summary = summary.into();
331        self
332    }
333
334    /// Attach a JSON Schema describing the expected request body for `/_slabs/openapi.json`.
335    #[must_use]
336    pub fn input_schema(mut self, schema: Value) -> Self {
337        self.input_schema = Some(schema);
338        self
339    }
340
341    /// Attach a JSON Schema describing the response body for `/_slabs/openapi.json`.
342    #[must_use]
343    pub fn output_schema(mut self, schema: Value) -> Self {
344        self.output_schema = Some(schema);
345        self
346    }
347
348    /// Extract serializable route metadata for the application manifest.
349    pub fn meta(&self) -> RouteMeta {
350        RouteMeta {
351            name: self.name.clone(),
352            method: self.method.clone(),
353            path: self.path.clone(),
354            summary: self.summary.clone(),
355            feature: self.feature.clone(),
356            input_schema: self.input_schema.clone(),
357            output_schema: self.output_schema.clone(),
358        }
359    }
360}
361
362/// Type-erased async handler function stored in a [`JobDef`].
363pub type JobHandlerFn =
364    Arc<dyn Fn(AppCtx, Value) -> BoxFuture<'static, SlabResult<()>> + Send + Sync>;
365
366/// Self-contained Background Job Transaction Script definition returned by `pub fn job() -> JobDef`.
367#[derive(Clone)]
368pub struct JobDef {
369    /// Unique job identifier used when enqueueing and dispatching.
370    pub name: String,
371    /// Queue name this job belongs to (defaults to `"default"`).
372    pub queue: String,
373    /// Maximum execution attempts before marking the job dead.
374    pub max_attempts: i64,
375    /// Short human-readable summary of the job.
376    pub summary: String,
377    /// Async handler invoked with [`AppCtx`] and the JSON payload.
378    pub handler: JobHandlerFn,
379}
380
381impl fmt::Debug for JobDef {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        f.debug_struct("JobDef")
384            .field("name", &self.name)
385            .field("queue", &self.queue)
386            .field("max_attempts", &self.max_attempts)
387            .field("summary", &self.summary)
388            .field("handler", &"<fn>")
389            .finish()
390    }
391}
392
393impl JobDef {
394    /// Create a new [`JobDef`] with the given `name` and async `handler`.
395    #[must_use]
396    pub fn new<F, Fut>(name: impl Into<String>, handler: F) -> Self
397    where
398        F: Fn(AppCtx, Value) -> Fut + Send + Sync + 'static,
399        Fut: Future<Output = SlabResult<()>> + Send + 'static,
400    {
401        Self {
402            name: name.into(),
403            queue: "default".to_string(),
404            max_attempts: 5,
405            summary: String::new(),
406            handler: Arc::new(move |ctx, payload| Box::pin(handler(ctx, payload))),
407        }
408    }
409
410    /// Override the queue name for this job.
411    #[must_use]
412    pub fn queue(mut self, queue: impl Into<String>) -> Self {
413        self.queue = queue.into();
414        self
415    }
416
417    /// Override the maximum number of retry attempts for this job.
418    #[must_use]
419    pub fn max_attempts(mut self, attempts: i64) -> Self {
420        self.max_attempts = attempts;
421        self
422    }
423
424    /// Set a short human-readable summary for the job manifest.
425    #[must_use]
426    pub fn summary(mut self, summary: impl Into<String>) -> Self {
427        self.summary = summary.into();
428        self
429    }
430
431    /// Extract serializable job metadata for the application manifest.
432    pub fn meta(&self) -> JobMeta {
433        JobMeta {
434            name: self.name.clone(),
435            queue: self.queue.clone(),
436            max_attempts: self.max_attempts,
437            summary: self.summary.clone(),
438        }
439    }
440}
441
442/// Recurring maintenance schedule that enqueues a registered job on a fixed interval.
443#[derive(Debug, Clone)]
444pub struct ScheduleDef {
445    /// Registered job name to enqueue on each tick.
446    pub job_name: String,
447    /// Interval between scheduled enqueues.
448    pub every: Duration,
449    /// JSON payload enqueued on each scheduled run.
450    pub payload: Value,
451}
452
453impl ScheduleDef {
454    /// Create a recurring schedule that enqueues `job_name` with `payload` on every `every` interval.
455    #[must_use]
456    pub fn every(every: Duration, job_name: impl Into<String>, payload: Value) -> Self {
457        Self {
458            job_name: job_name.into(),
459            every,
460            payload,
461        }
462    }
463}
464
465/// Dispatches `SQLite`-queued jobs to discovered [`JobDef`] handlers.
466#[derive(Debug, Clone)]
467pub struct JobRegistry {
468    handlers: Arc<HashMap<String, JobDef>>,
469}
470
471impl JobRegistry {
472    /// Build a registry from discovered `jobs`, including the built-in `slabs.deliver_webhook` handler.
473    #[must_use]
474    pub fn new(jobs: Vec<JobDef>) -> Self {
475        let mut map = HashMap::new();
476        // Built-in dev-safe webhook delivery job (records delivery as 200 in outbox unless overridden)
477        map.insert(
478            "slabs.deliver_webhook".to_string(),
479            JobDef::new("slabs.deliver_webhook", default_deliver_webhook)
480                .queue("webhooks")
481                .summary("Built-in webhook delivery handler"),
482        );
483        for job in jobs {
484            map.insert(job.name.clone(), job);
485        }
486        Self {
487            handlers: Arc::new(map),
488        }
489    }
490
491    /// Execute a registered job directly by name (ideal for testing scheduled/maintenance jobs).
492    pub async fn run_now(&self, ctx: &AppCtx, job_name: &str, payload: Value) -> SlabResult<()> {
493        let def = self
494            .handlers
495            .get(job_name)
496            .ok_or_else(|| SlabError::not_found(format!("no job handler `{job_name}`")))?;
497        (def.handler)(ctx.clone(), payload).await
498    }
499
500    /// Claim and execute the next ready job from the queue, returning `Ok(true)` if a job was processed.
501    pub async fn run_next(&self, ctx: &AppCtx) -> SlabResult<bool> {
502        let Some(record) = ctx.jobs.claim_next().await? else {
503            return Ok(false);
504        };
505
506        let Some(def) = self.handlers.get(&record.job_name) else {
507            let msg = format!("no job handler registered for `{}`", record.job_name);
508            ctx.jobs.mark_failed(&record, &msg).await?;
509            return Ok(true);
510        };
511
512        let payload: Value = serde_json::from_str(&record.payload_json)
513            .map_err(|e| SlabError::internal(format!("invalid job json: {e}")))?;
514
515        match (def.handler)(ctx.clone(), payload).await {
516            Ok(()) => {
517                ctx.jobs.mark_done(&record.id).await?;
518            }
519            Err(err) => {
520                tracing::warn!(job_id = %record.id, job_name = %record.job_name, error = %err, "job execution failed");
521                ctx.jobs.mark_failed(&record, &err.to_string()).await?;
522            }
523        }
524
525        Ok(true)
526    }
527
528    /// Repeatedly run ready jobs until the queue is empty, returning the number of jobs processed.
529    pub async fn drain_ready(&self, ctx: &AppCtx) -> SlabResult<usize> {
530        let mut processed = 0;
531        while self.run_next(ctx).await? {
532            processed += 1;
533        }
534        Ok(processed)
535    }
536
537    /// Spawn background job worker tasks without an external shutdown signal.
538    pub fn spawn_workers(&self, ctx: &AppCtx) {
539        let (_tx, rx) = watch::channel(false);
540        self.spawn_workers_with_shutdown(ctx, &rx);
541    }
542
543    /// Spawn background job worker tasks that stop cleanly when `shutdown` is signaled.
544    pub fn spawn_workers_with_shutdown(&self, ctx: &AppCtx, shutdown: &watch::Receiver<bool>) {
545        let concurrency = ctx.config.job_concurrency.max(1);
546        let poll_ms = ctx.config.job_poll_interval_ms.max(50);
547
548        for worker_idx in 0..concurrency {
549            let registry = self.clone();
550            let worker_ctx = ctx.clone();
551            let mut rx = shutdown.clone();
552            tokio::spawn(async move {
553                loop {
554                    if *rx.borrow() {
555                        break;
556                    }
557                    match registry.run_next(&worker_ctx).await {
558                        Ok(true) => {}
559                        Ok(false) => {
560                            tokio::select! {
561                                () = tokio::time::sleep(Duration::from_millis(poll_ms)) => {},
562                                _ = rx.changed() => { break; }
563                            }
564                        }
565                        Err(err) => {
566                            tracing::error!(worker = worker_idx, error = %err, "job worker error");
567                            tokio::select! {
568                                () = tokio::time::sleep(Duration::from_secs(1)) => {},
569                                _ = rx.changed() => { break; }
570                            }
571                        }
572                    }
573                }
574                tracing::debug!(worker = worker_idx, "job worker shut down cleanly");
575            });
576        }
577    }
578
579    /// Spawn recurring schedule tasks without an external shutdown signal.
580    pub fn spawn_schedules(&self, ctx: &AppCtx, schedules: Vec<ScheduleDef>) {
581        let (_tx, rx) = watch::channel(false);
582        self.spawn_schedules_with_shutdown(ctx, schedules, &rx);
583    }
584
585    /// Spawn recurring schedule tasks that stop cleanly when `shutdown` is signaled.
586    pub fn spawn_schedules_with_shutdown(
587        &self,
588        ctx: &AppCtx,
589        schedules: Vec<ScheduleDef>,
590        shutdown: &watch::Receiver<bool>,
591    ) {
592        for schedule in schedules {
593            let sched_ctx = ctx.clone();
594            let mut rx = shutdown.clone();
595            tokio::spawn(async move {
596                let mut ticker = tokio::time::interval(schedule.every);
597                ticker.tick().await;
598                loop {
599                    tokio::select! {
600                        _ = ticker.tick() => {
601                            if let Err(err) = sched_ctx
602                                .jobs
603                                .enqueue(&schedule.job_name, schedule.payload.clone())
604                                .await
605                            {
606                                tracing::error!(
607                                    job = %schedule.job_name,
608                                    error = %err,
609                                    "failed to enqueue scheduled job"
610                                );
611                            }
612                        }
613                        _ = rx.changed() => {
614                            break;
615                        }
616                    }
617                }
618            });
619        }
620    }
621}
622
623async fn default_deliver_webhook(ctx: AppCtx, payload: Value) -> SlabResult<()> {
624    let delivery_id = payload
625        .get("delivery_id")
626        .and_then(|v| v.as_str())
627        .ok_or_else(|| SlabError::bad_request("missing delivery_id"))?;
628    if ctx.config.webhooks_live {
629        ctx.webhooks
630            .deliver_http(delivery_id, ctx.config.webhooks_allow_local)
631            .await?;
632    } else {
633        // Dev/test safe mode: marks signed delivery recorded in outbox without external HTTP calls.
634        ctx.webhooks.mark_delivered(delivery_id, 200).await?;
635    }
636    Ok(())
637}
638
639/// Assemble the full [`axum::Router`] from discovered slabs, built-in endpoints, and middleware.
640///
641/// Slabs registered on the same path with different HTTP methods are merged into one
642/// [`MethodRouter`]. Mounts `/_slabs/health`, `/_slabs/manifest`, `/_slabs/mail`,
643/// `/_slabs/vendor/*`, and `/assets/{hash}/{*path}`, then applies the default Tower middleware stack.
644pub fn build_router(ctx: AppCtx, slabs: Vec<SlabDef>, jobs: &[JobDef]) -> Router {
645    let manifest = Arc::new(AppManifest {
646        app_name: ctx.config.app_name.clone(),
647        routes: slabs.iter().map(SlabDef::meta).collect(),
648        jobs: jobs.iter().map(JobDef::meta).collect(),
649    });
650
651    let mut grouped: BTreeMap<String, MethodRouter<AppCtx>> = BTreeMap::new();
652    for slab in slabs {
653        match grouped.entry(slab.path) {
654            Entry::Occupied(mut existing) => {
655                let taken = std::mem::take(existing.get_mut());
656                *existing.get_mut() = taken.merge(slab.router);
657            }
658            Entry::Vacant(slot) => {
659                slot.insert(slab.router);
660            }
661        }
662    }
663
664    let mut router: Router<AppCtx> = Router::new();
665    for (path, method_router) in grouped {
666        router = router.route(&path, method_router);
667    }
668
669    let openapi_manifest = manifest.clone();
670    router = router
671        .route("/_slabs/health", get(health_handler))
672        .route(
673            "/_slabs/manifest",
674            get(move || {
675                let m = manifest.clone();
676                async move { Json((*m).clone()) }
677            }),
678        )
679        .route(
680            "/_slabs/openapi.json",
681            get(move || {
682                let m = openapi_manifest.clone();
683                async move { Json(m.to_openapi_3_1()) }
684            }),
685        )
686        .route("/_slabs/mail", get(dev_mail_outbox_handler))
687        .route("/_slabs/vendor/basecoat.min.css", get(vendor_basecoat_css))
688        .route("/_slabs/vendor/basecoat.min.js", get(vendor_basecoat_js))
689        .route("/_slabs/vendor/htmx.min.js", get(vendor_htmx_js))
690        .route("/_slabs/vendor/htmx-ext-sse.js", get(vendor_htmx_sse_js))
691        .route(
692            "/_slabs/vendor/idiomorph-ext.min.js",
693            get(vendor_idiomorph_js),
694        )
695        .route("/_slabs/vendor/alpine.min.js", get(vendor_alpine_js))
696        .route("/assets/{hash}/{*path}", get(serve_asset_handler));
697
698    let x_request_id = header::HeaderName::from_static("x-request-id");
699    router
700        .with_state(ctx)
701        .layer(CompressionLayer::new())
702        .layer(RequestBodyLimitLayer::new(25 * 1024 * 1024))
703        .layer(SetResponseHeaderLayer::if_not_present(
704            header::X_CONTENT_TYPE_OPTIONS,
705            HeaderValue::from_static("nosniff"),
706        ))
707        .layer(SetResponseHeaderLayer::if_not_present(
708            header::X_FRAME_OPTIONS,
709            HeaderValue::from_static("SAMEORIGIN"),
710        ))
711        .layer(CorsLayer::permissive())
712        .layer(PropagateRequestIdLayer::new(x_request_id.clone()))
713        .layer(TraceLayer::new_for_http())
714        .layer(SetRequestIdLayer::new(x_request_id, MakeUlidRequestId))
715}
716
717async fn health_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
718    ctx.db.ping().await?;
719    Ok(Json(json!({
720        "status": "ok",
721        "app": ctx.config.app_name,
722    })))
723}
724
725async fn dev_mail_outbox_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
726    let sent = ctx.mail.list_sent(50).await?;
727    Ok(Json(json!({ "emails": sent })))
728}
729
730fn vendor_response(content_type: &'static str, body: &'static str) -> Response {
731    (
732        StatusCode::OK,
733        [
734            (header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
735            (
736                header::CACHE_CONTROL,
737                HeaderValue::from_static("public, max-age=86400"),
738            ),
739        ],
740        body,
741    )
742        .into_response()
743}
744
745async fn vendor_basecoat_css() -> Response {
746    vendor_response(
747        "text/css; charset=utf-8",
748        include_str!("../assets/vendor/basecoat.min.css"),
749    )
750}
751
752async fn vendor_basecoat_js() -> Response {
753    vendor_response(
754        "text/javascript; charset=utf-8",
755        include_str!("../assets/vendor/basecoat.min.js"),
756    )
757}
758
759async fn vendor_htmx_js() -> Response {
760    vendor_response(
761        "text/javascript; charset=utf-8",
762        include_str!("../assets/vendor/htmx.min.js"),
763    )
764}
765
766async fn vendor_htmx_sse_js() -> Response {
767    vendor_response(
768        "text/javascript; charset=utf-8",
769        include_str!("../assets/vendor/htmx-ext-sse.js"),
770    )
771}
772
773async fn vendor_idiomorph_js() -> Response {
774    vendor_response(
775        "text/javascript; charset=utf-8",
776        include_str!("../assets/vendor/idiomorph-ext.min.js"),
777    )
778}
779
780async fn vendor_alpine_js() -> Response {
781    vendor_response(
782        "text/javascript; charset=utf-8",
783        include_str!("../assets/vendor/alpine.min.js"),
784    )
785}
786
787async fn serve_asset_handler(
788    State(ctx): State<AppCtx>,
789    Path((hash, path)): Path<(String, String)>,
790) -> SlabResult<Response> {
791    let Some(entry) = ctx.assets.get(&hash, &path) else {
792        return Err(SlabError::not_found("asset not found"));
793    };
794    let ct = HeaderValue::from_str(&entry.content_type)
795        .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
796    Ok((
797        StatusCode::OK,
798        [
799            (header::CONTENT_TYPE, ct),
800            (
801                header::CACHE_CONTROL,
802                HeaderValue::from_static("public, max-age=31536000, immutable"),
803            ),
804        ],
805        entry.bytes.clone(),
806    )
807        .into_response())
808}