slabs-http 0.2.0

HTTP router, AppCtx, SlabDef, JobDef, ScheduleDef, background job runner, and built-in observability/dev routes for Slabs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
//! 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`], and [`RateLimiter`].
//! - Router builder: [`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 /_slabs/health`: pings the database with `SELECT 1` and returns `{"status": "ok", "app": "<app_name>"}`.
//!   - `GET /_slabs/manifest`: returns the JSON [`slabs_core::AppManifest`] listing all registered routes and jobs.
//!   - `GET /_slabs/openapi.json`: returns an `OpenAPI` 3.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 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`.
//!   - `GET /assets/{hash}/{*path}`: serves content-hashed static files from `ctx.assets` with `Cache-Control: public, max-age=31536000, immutable`.
//! - Middleware stack order in [`build_router`] (outermost to innermost on incoming requests):
//!   1. `SetRequestIdLayer`: assigns a time-sortable ULID `X-Request-Id` (`req_<ulid>`) when absent.
//!   2. `TraceLayer`: records HTTP request and response tracing spans.
//!   3. `PropagateRequestIdLayer`: copies `X-Request-Id` onto the response.
//!   4. `CorsLayer::permissive()`: sets permissive CORS headers.
//!   5. `SetResponseHeaderLayer`: sets `X-Frame-Options: SAMEORIGIN` if absent.
//!   6. `SetResponseHeaderLayer`: sets `X-Content-Type-Options: nosniff` if absent.
//!   7. `RequestBodyLimitLayer`: limits request bodies to 25 MiB.
//!   8. `CompressionLayer`: compresses responses with gzip and brotli (`br`).
//!
//! # Agent invariants
//!
//! - Use Axum 0.8 `{param}` and `{*wildcard}` path syntax in [`SlabDef`] constructors. Do not use `:param` or `*wildcard`.
//! - 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.
//! - 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.
//! - 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.
//! - [`JobRegistry::new`] always registers the built-in `slabs.deliver_webhook` handler unless an application job overrides that name.
//!
//! # Example
//!
//! ```rust,no_run
//! 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()], &[])
//! }
//! ```

use axum::{
    extract::{Path, State},
    handler::Handler,
    http::{header, HeaderValue, StatusCode},
    response::{IntoResponse, Response},
    routing::{delete, get, patch, post, put, MethodRouter},
    Json, Router,
};
use futures_util::future::BoxFuture;
use serde_json::{json, Value};
use slabs_assets::Assets;
use slabs_auth::Auth;
use slabs_cache::Cache;
use slabs_core::{AppConfig, AppManifest, JobMeta, RouteMeta, SlabError, SlabResult};
use slabs_db::{AuditLog, Db};
use slabs_jobs::Jobs;
use slabs_mail::{MailTransport, Mailer};
use slabs_realtime::Realtime;
use slabs_storage::{S3Config, Storage, StorageBackend};
use slabs_webhooks::Webhooks;
use std::collections::{btree_map::Entry, BTreeMap, HashMap};
use std::fmt;
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::watch;
use tower_http::{
    compression::CompressionLayer,
    cors::CorsLayer,
    limit::RequestBodyLimitLayer,
    request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer},
    set_header::SetResponseHeaderLayer,
    trace::TraceLayer,
};

/// Generates time-sortable prefixed ULID `X-Request-Id` headers (`req_01j...`).
#[derive(Clone, Default)]
struct MakeUlidRequestId;

impl MakeRequestId for MakeUlidRequestId {
    fn make_request_id<B>(&mut self, _request: &http::Request<B>) -> Option<RequestId> {
        let id = slabs_core::id::new("req");
        HeaderValue::from_str(&id).ok().map(RequestId::new)
    }
}

/// Explicit in-memory fixed-window rate limiter for auth and sensitive slabs.
#[derive(Debug, Clone, Default)]
pub struct RateLimiter {
    buckets: Arc<Mutex<HashMap<String, (u64, Instant)>>>,
}

impl RateLimiter {
    /// Create a new empty in-memory rate limiter.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Increment the counter for `key` and return the remaining quota for the current window.
    ///
    /// Returns HTTP 429 (`SlabError::TooManyRequests`) with a `Retry-After` duration when `key`
    /// reaches `max_requests` within `window_secs`.
    pub fn check(&self, key: &str, max_requests: u64, window_secs: u64) -> SlabResult<u64> {
        let now = Instant::now();
        let window = Duration::from_secs(window_secs.max(1));
        let mut guard = self.buckets.lock().expect("rate limiter mutex poisoned");

        // Opportunistically prune expired entries if map grows large
        if guard.len() > 10_000 {
            guard.retain(|_, (_, expires_at)| *expires_at > now);
        }

        let entry = guard.entry(key.to_string()).or_insert((0, now + window));

        if entry.1 <= now {
            entry.0 = 0;
            entry.1 = now + window;
        }

        if entry.0 >= max_requests {
            let retry_after = entry.1.saturating_duration_since(now).as_secs().max(1);
            return Err(SlabError::too_many_requests(
                retry_after,
                "rate limit exceeded, please try again shortly",
            ));
        }

        entry.0 += 1;
        Ok(max_requests - entry.0)
    }
}

/// Shared runtime context passed to every HTTP slab handler and background job.
///
/// Every field is an explicit subsystem handle backed by `SQLite` or in-process state, with no ORM
/// or hidden middleware state.
#[derive(Debug, Clone)]
pub struct AppCtx {
    /// Runtime application configuration loaded from environment variables or defaults.
    pub config: AppConfig,
    /// Shared database connection pool.
    pub db: Db,
    /// Authentication, session, magic-link, and access-token helper.
    pub auth: Auth,
    /// Durable SQLite-backed background job queue.
    pub jobs: Jobs,
    /// Outbound email delivery and development outbox mailer.
    pub mail: Mailer,
    /// Local or S3-compatible blob storage handle.
    pub storage: Storage,
    /// SQLite-backed key/value cache.
    pub cache: Cache,
    /// In-process topic broadcast hub for SSE and `WebSocket` updates.
    pub realtime: Realtime,
    /// Outbound signed webhook subscription and delivery manager.
    pub webhooks: Webhooks,
    /// Content-hashed static asset registry.
    pub assets: Assets,
    /// In-memory fixed-window rate limiter.
    pub rate_limit: RateLimiter,
    /// Transactional SQLite-backed audit log.
    pub audit: AuditLog,
}

impl AppCtx {
    /// Initialize database connections and all framework subsystems from `config`.
    pub async fn connect(config: AppConfig) -> SlabResult<Self> {
        let db = Db::connect(&config.database_url).await?;
        let auth = Auth::new(db.clone(), config.secret_key.clone(), config.cookie_secure);
        let jobs = Jobs::new(db.clone());
        let mail = Mailer::with_transport(
            db.clone(),
            format!("noreply@{}.local", config.app_name),
            MailTransport::from_env(),
        );
        let storage_backend = match S3Config::from_env() {
            Some(s3) => StorageBackend::S3(s3),
            None => StorageBackend::Local {
                root_dir: config.storage_dir.clone(),
            },
        };
        let storage = Storage::with_backend(db.clone(), storage_backend);
        let cache = Cache::new(db.clone());
        let realtime = Realtime::new();
        let webhooks = Webhooks::new(db.clone(), jobs.clone());
        let assets = Assets::from_dir(&config.assets_dir);
        let rate_limit = RateLimiter::new();
        let audit = AuditLog::new(db.clone());

        Ok(Self {
            config,
            db,
            auth,
            jobs,
            mail,
            storage,
            cache,
            realtime,
            webhooks,
            assets,
            rate_limit,
            audit,
        })
    }
}

/// Self-contained HTTP Transaction Script definition returned by `pub fn slab() -> SlabDef`.
///
/// Route paths use Axum 0.8 `{param}` and `{*wildcard}` syntax.
#[derive(Debug)]
pub struct SlabDef {
    /// HTTP method handled by this slab (e.g. `"GET"`, `"POST"`).
    pub method: String,
    /// Route path pattern registered on the Axum router.
    pub path: String,
    /// Logical slab name (commonly `<feature>.<action>`).
    pub name: String,
    /// Feature grouping label for manifest inspection.
    pub feature: String,
    /// Short human-readable description of the endpoint.
    pub summary: String,
    /// Optional JSON Schema describing the expected request body for `OpenAPI` export.
    pub input_schema: Option<Value>,
    /// Optional JSON Schema describing the response body for `OpenAPI` export.
    pub output_schema: Option<Value>,
    /// Axum method router wrapping the slab's handler.
    pub router: MethodRouter<AppCtx>,
}

impl SlabDef {
    /// Define a `GET` slab at `path`.
    pub fn get<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, AppCtx>,
        T: 'static,
    {
        Self::new("GET", path, get(handler))
    }

    /// Define a `POST` slab at `path`.
    pub fn post<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, AppCtx>,
        T: 'static,
    {
        Self::new("POST", path, post(handler))
    }

    /// Define a `PUT` slab at `path`.
    pub fn put<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, AppCtx>,
        T: 'static,
    {
        Self::new("PUT", path, put(handler))
    }

    /// Define a `PATCH` slab at `path`.
    pub fn patch<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, AppCtx>,
        T: 'static,
    {
        Self::new("PATCH", path, patch(handler))
    }

    /// Define a `DELETE` slab at `path`.
    pub fn delete<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, AppCtx>,
        T: 'static,
    {
        Self::new("DELETE", path, delete(handler))
    }

    fn new(method: &str, path: impl Into<String>, router: MethodRouter<AppCtx>) -> Self {
        let path = path.into();
        Self {
            method: method.to_string(),
            name: format!("{method} {path}"),
            feature: "default".to_string(),
            summary: String::new(),
            input_schema: None,
            output_schema: None,
            path,
            router,
        }
    }

    /// Set the slab's logical name, automatically deriving `feature` from a `<feature>.<action>` prefix.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        let n = name.into();
        if let Some((feat, _)) = n.split_once('.') {
            self.feature = feat.to_string();
        }
        self.name = n;
        self
    }

    /// Explicitly set the slab's feature group name.
    #[must_use]
    pub fn feature(mut self, feature: impl Into<String>) -> Self {
        self.feature = feature.into();
        self
    }

    /// Set a short human-readable summary for the route manifest.
    #[must_use]
    pub fn summary(mut self, summary: impl Into<String>) -> Self {
        self.summary = summary.into();
        self
    }

    /// Attach a JSON Schema describing the expected request body for `/_slabs/openapi.json`.
    #[must_use]
    pub fn input_schema(mut self, schema: Value) -> Self {
        self.input_schema = Some(schema);
        self
    }

    /// Attach a JSON Schema describing the response body for `/_slabs/openapi.json`.
    #[must_use]
    pub fn output_schema(mut self, schema: Value) -> Self {
        self.output_schema = Some(schema);
        self
    }

    /// Extract serializable route metadata for the application manifest.
    pub fn meta(&self) -> RouteMeta {
        RouteMeta {
            name: self.name.clone(),
            method: self.method.clone(),
            path: self.path.clone(),
            summary: self.summary.clone(),
            feature: self.feature.clone(),
            input_schema: self.input_schema.clone(),
            output_schema: self.output_schema.clone(),
        }
    }
}

/// Type-erased async handler function stored in a [`JobDef`].
pub type JobHandlerFn =
    Arc<dyn Fn(AppCtx, Value) -> BoxFuture<'static, SlabResult<()>> + Send + Sync>;

/// Self-contained Background Job Transaction Script definition returned by `pub fn job() -> JobDef`.
#[derive(Clone)]
pub struct JobDef {
    /// Unique job identifier used when enqueueing and dispatching.
    pub name: String,
    /// Queue name this job belongs to (defaults to `"default"`).
    pub queue: String,
    /// Maximum execution attempts before marking the job dead.
    pub max_attempts: i64,
    /// Short human-readable summary of the job.
    pub summary: String,
    /// Async handler invoked with [`AppCtx`] and the JSON payload.
    pub handler: JobHandlerFn,
}

impl fmt::Debug for JobDef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("JobDef")
            .field("name", &self.name)
            .field("queue", &self.queue)
            .field("max_attempts", &self.max_attempts)
            .field("summary", &self.summary)
            .field("handler", &"<fn>")
            .finish()
    }
}

impl JobDef {
    /// Create a new [`JobDef`] with the given `name` and async `handler`.
    #[must_use]
    pub fn new<F, Fut>(name: impl Into<String>, handler: F) -> Self
    where
        F: Fn(AppCtx, Value) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = SlabResult<()>> + Send + 'static,
    {
        Self {
            name: name.into(),
            queue: "default".to_string(),
            max_attempts: 5,
            summary: String::new(),
            handler: Arc::new(move |ctx, payload| Box::pin(handler(ctx, payload))),
        }
    }

    /// Override the queue name for this job.
    #[must_use]
    pub fn queue(mut self, queue: impl Into<String>) -> Self {
        self.queue = queue.into();
        self
    }

    /// Override the maximum number of retry attempts for this job.
    #[must_use]
    pub fn max_attempts(mut self, attempts: i64) -> Self {
        self.max_attempts = attempts;
        self
    }

    /// Set a short human-readable summary for the job manifest.
    #[must_use]
    pub fn summary(mut self, summary: impl Into<String>) -> Self {
        self.summary = summary.into();
        self
    }

    /// Extract serializable job metadata for the application manifest.
    pub fn meta(&self) -> JobMeta {
        JobMeta {
            name: self.name.clone(),
            queue: self.queue.clone(),
            max_attempts: self.max_attempts,
            summary: self.summary.clone(),
        }
    }
}

/// Recurring maintenance schedule that enqueues a registered job on a fixed interval.
#[derive(Debug, Clone)]
pub struct ScheduleDef {
    /// Registered job name to enqueue on each tick.
    pub job_name: String,
    /// Interval between scheduled enqueues.
    pub every: Duration,
    /// JSON payload enqueued on each scheduled run.
    pub payload: Value,
}

impl ScheduleDef {
    /// Create a recurring schedule that enqueues `job_name` with `payload` on every `every` interval.
    #[must_use]
    pub fn every(every: Duration, job_name: impl Into<String>, payload: Value) -> Self {
        Self {
            job_name: job_name.into(),
            every,
            payload,
        }
    }
}

/// Dispatches `SQLite`-queued jobs to discovered [`JobDef`] handlers.
#[derive(Debug, Clone)]
pub struct JobRegistry {
    handlers: Arc<HashMap<String, JobDef>>,
}

impl JobRegistry {
    /// Build a registry from discovered `jobs`, including the built-in `slabs.deliver_webhook` handler.
    #[must_use]
    pub fn new(jobs: Vec<JobDef>) -> Self {
        let mut map = HashMap::new();
        // Built-in dev-safe webhook delivery job (records delivery as 200 in outbox unless overridden)
        map.insert(
            "slabs.deliver_webhook".to_string(),
            JobDef::new("slabs.deliver_webhook", default_deliver_webhook)
                .queue("webhooks")
                .summary("Built-in webhook delivery handler"),
        );
        for job in jobs {
            map.insert(job.name.clone(), job);
        }
        Self {
            handlers: Arc::new(map),
        }
    }

    /// Execute a registered job directly by name (ideal for testing scheduled/maintenance jobs).
    pub async fn run_now(&self, ctx: &AppCtx, job_name: &str, payload: Value) -> SlabResult<()> {
        let def = self
            .handlers
            .get(job_name)
            .ok_or_else(|| SlabError::not_found(format!("no job handler `{job_name}`")))?;
        (def.handler)(ctx.clone(), payload).await
    }

    /// Claim and execute the next ready job from the queue, returning `Ok(true)` if a job was processed.
    pub async fn run_next(&self, ctx: &AppCtx) -> SlabResult<bool> {
        let Some(record) = ctx.jobs.claim_next().await? else {
            return Ok(false);
        };

        let Some(def) = self.handlers.get(&record.job_name) else {
            let msg = format!("no job handler registered for `{}`", record.job_name);
            ctx.jobs.mark_failed(&record, &msg).await?;
            return Ok(true);
        };

        let payload: Value = serde_json::from_str(&record.payload_json)
            .map_err(|e| SlabError::internal(format!("invalid job json: {e}")))?;

        match (def.handler)(ctx.clone(), payload).await {
            Ok(()) => {
                ctx.jobs.mark_done(&record.id).await?;
            }
            Err(err) => {
                tracing::warn!(job_id = %record.id, job_name = %record.job_name, error = %err, "job execution failed");
                ctx.jobs.mark_failed(&record, &err.to_string()).await?;
            }
        }

        Ok(true)
    }

    /// Repeatedly run ready jobs until the queue is empty, returning the number of jobs processed.
    pub async fn drain_ready(&self, ctx: &AppCtx) -> SlabResult<usize> {
        let mut processed = 0;
        while self.run_next(ctx).await? {
            processed += 1;
        }
        Ok(processed)
    }

    /// Spawn background job worker tasks without an external shutdown signal.
    pub fn spawn_workers(&self, ctx: &AppCtx) {
        let (_tx, rx) = watch::channel(false);
        self.spawn_workers_with_shutdown(ctx, &rx);
    }

    /// Spawn background job worker tasks that stop cleanly when `shutdown` is signaled.
    pub fn spawn_workers_with_shutdown(&self, ctx: &AppCtx, shutdown: &watch::Receiver<bool>) {
        let concurrency = ctx.config.job_concurrency.max(1);
        let poll_ms = ctx.config.job_poll_interval_ms.max(50);

        for worker_idx in 0..concurrency {
            let registry = self.clone();
            let worker_ctx = ctx.clone();
            let mut rx = shutdown.clone();
            tokio::spawn(async move {
                loop {
                    if *rx.borrow() {
                        break;
                    }
                    match registry.run_next(&worker_ctx).await {
                        Ok(true) => {}
                        Ok(false) => {
                            tokio::select! {
                                () = tokio::time::sleep(Duration::from_millis(poll_ms)) => {},
                                _ = rx.changed() => { break; }
                            }
                        }
                        Err(err) => {
                            tracing::error!(worker = worker_idx, error = %err, "job worker error");
                            tokio::select! {
                                () = tokio::time::sleep(Duration::from_secs(1)) => {},
                                _ = rx.changed() => { break; }
                            }
                        }
                    }
                }
                tracing::debug!(worker = worker_idx, "job worker shut down cleanly");
            });
        }
    }

    /// Spawn recurring schedule tasks without an external shutdown signal.
    pub fn spawn_schedules(&self, ctx: &AppCtx, schedules: Vec<ScheduleDef>) {
        let (_tx, rx) = watch::channel(false);
        self.spawn_schedules_with_shutdown(ctx, schedules, &rx);
    }

    /// Spawn recurring schedule tasks that stop cleanly when `shutdown` is signaled.
    pub fn spawn_schedules_with_shutdown(
        &self,
        ctx: &AppCtx,
        schedules: Vec<ScheduleDef>,
        shutdown: &watch::Receiver<bool>,
    ) {
        for schedule in schedules {
            let sched_ctx = ctx.clone();
            let mut rx = shutdown.clone();
            tokio::spawn(async move {
                let mut ticker = tokio::time::interval(schedule.every);
                ticker.tick().await;
                loop {
                    tokio::select! {
                        _ = ticker.tick() => {
                            if let Err(err) = sched_ctx
                                .jobs
                                .enqueue(&schedule.job_name, schedule.payload.clone())
                                .await
                            {
                                tracing::error!(
                                    job = %schedule.job_name,
                                    error = %err,
                                    "failed to enqueue scheduled job"
                                );
                            }
                        }
                        _ = rx.changed() => {
                            break;
                        }
                    }
                }
            });
        }
    }
}

async fn default_deliver_webhook(ctx: AppCtx, payload: Value) -> SlabResult<()> {
    let delivery_id = payload
        .get("delivery_id")
        .and_then(|v| v.as_str())
        .ok_or_else(|| SlabError::bad_request("missing delivery_id"))?;
    if ctx.config.webhooks_live {
        ctx.webhooks
            .deliver_http(delivery_id, ctx.config.webhooks_allow_local)
            .await?;
    } else {
        // Dev/test safe mode: marks signed delivery recorded in outbox without external HTTP calls.
        ctx.webhooks.mark_delivered(delivery_id, 200).await?;
    }
    Ok(())
}

/// Assemble the full [`axum::Router`] from discovered slabs, built-in endpoints, and middleware.
///
/// Slabs registered on the same path with different HTTP methods are merged into one
/// [`MethodRouter`]. Mounts `/_slabs/health`, `/_slabs/manifest`, `/_slabs/mail`,
/// `/_slabs/vendor/*`, and `/assets/{hash}/{*path}`, then applies the default Tower middleware stack.
pub fn build_router(ctx: AppCtx, slabs: Vec<SlabDef>, jobs: &[JobDef]) -> Router {
    let manifest = Arc::new(AppManifest {
        app_name: ctx.config.app_name.clone(),
        routes: slabs.iter().map(SlabDef::meta).collect(),
        jobs: jobs.iter().map(JobDef::meta).collect(),
    });

    let mut grouped: BTreeMap<String, MethodRouter<AppCtx>> = BTreeMap::new();
    for slab in slabs {
        match grouped.entry(slab.path) {
            Entry::Occupied(mut existing) => {
                let taken = std::mem::take(existing.get_mut());
                *existing.get_mut() = taken.merge(slab.router);
            }
            Entry::Vacant(slot) => {
                slot.insert(slab.router);
            }
        }
    }

    let mut router: Router<AppCtx> = Router::new();
    for (path, method_router) in grouped {
        router = router.route(&path, method_router);
    }

    let openapi_manifest = manifest.clone();
    router = router
        .route("/_slabs/health", get(health_handler))
        .route(
            "/_slabs/manifest",
            get(move || {
                let m = manifest.clone();
                async move { Json((*m).clone()) }
            }),
        )
        .route(
            "/_slabs/openapi.json",
            get(move || {
                let m = openapi_manifest.clone();
                async move { Json(m.to_openapi_3_1()) }
            }),
        )
        .route("/_slabs/mail", get(dev_mail_outbox_handler))
        .route("/_slabs/vendor/basecoat.min.css", get(vendor_basecoat_css))
        .route("/_slabs/vendor/basecoat.min.js", get(vendor_basecoat_js))
        .route("/_slabs/vendor/htmx.min.js", get(vendor_htmx_js))
        .route("/_slabs/vendor/htmx-ext-sse.js", get(vendor_htmx_sse_js))
        .route(
            "/_slabs/vendor/idiomorph-ext.min.js",
            get(vendor_idiomorph_js),
        )
        .route("/_slabs/vendor/alpine.min.js", get(vendor_alpine_js))
        .route("/assets/{hash}/{*path}", get(serve_asset_handler));

    let x_request_id = header::HeaderName::from_static("x-request-id");
    router
        .with_state(ctx)
        .layer(CompressionLayer::new())
        .layer(RequestBodyLimitLayer::new(25 * 1024 * 1024))
        .layer(SetResponseHeaderLayer::if_not_present(
            header::X_CONTENT_TYPE_OPTIONS,
            HeaderValue::from_static("nosniff"),
        ))
        .layer(SetResponseHeaderLayer::if_not_present(
            header::X_FRAME_OPTIONS,
            HeaderValue::from_static("SAMEORIGIN"),
        ))
        .layer(CorsLayer::permissive())
        .layer(PropagateRequestIdLayer::new(x_request_id.clone()))
        .layer(TraceLayer::new_for_http())
        .layer(SetRequestIdLayer::new(x_request_id, MakeUlidRequestId))
}

async fn health_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
    ctx.db.ping().await?;
    Ok(Json(json!({
        "status": "ok",
        "app": ctx.config.app_name,
    })))
}

async fn dev_mail_outbox_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
    let sent = ctx.mail.list_sent(50).await?;
    Ok(Json(json!({ "emails": sent })))
}

fn vendor_response(content_type: &'static str, body: &'static str) -> Response {
    (
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
            (
                header::CACHE_CONTROL,
                HeaderValue::from_static("public, max-age=86400"),
            ),
        ],
        body,
    )
        .into_response()
}

async fn vendor_basecoat_css() -> Response {
    vendor_response(
        "text/css; charset=utf-8",
        include_str!("../assets/vendor/basecoat.min.css"),
    )
}

async fn vendor_basecoat_js() -> Response {
    vendor_response(
        "text/javascript; charset=utf-8",
        include_str!("../assets/vendor/basecoat.min.js"),
    )
}

async fn vendor_htmx_js() -> Response {
    vendor_response(
        "text/javascript; charset=utf-8",
        include_str!("../assets/vendor/htmx.min.js"),
    )
}

async fn vendor_htmx_sse_js() -> Response {
    vendor_response(
        "text/javascript; charset=utf-8",
        include_str!("../assets/vendor/htmx-ext-sse.js"),
    )
}

async fn vendor_idiomorph_js() -> Response {
    vendor_response(
        "text/javascript; charset=utf-8",
        include_str!("../assets/vendor/idiomorph-ext.min.js"),
    )
}

async fn vendor_alpine_js() -> Response {
    vendor_response(
        "text/javascript; charset=utf-8",
        include_str!("../assets/vendor/alpine.min.js"),
    )
}

async fn serve_asset_handler(
    State(ctx): State<AppCtx>,
    Path((hash, path)): Path<(String, String)>,
) -> SlabResult<Response> {
    let Some(entry) = ctx.assets.get(&hash, &path) else {
        return Err(SlabError::not_found("asset not found"));
    };
    let ct = HeaderValue::from_str(&entry.content_type)
        .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
    Ok((
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, ct),
            (
                header::CACHE_CONTROL,
                HeaderValue::from_static("public, max-age=31536000, immutable"),
            ),
        ],
        entry.bytes.clone(),
    )
        .into_response())
}