Skip to main content

slabs_core/
lib.rs

1//! Core types for the Slabs web framework.
2//!
3//! This crate owns prefixed ULID generation, the unified HTTP error type,
4//! environment configuration, and JSON route/job manifests.
5//!
6//! # Owned types
7//!
8//! - [`id::new`]: generates lowercase, time-sortable prefixed ULIDs such as `msg_01j...`.
9//! - [`SlabError`] and [`SlabResult`]: explicit error enum returned by every transaction script and background job.
10//! - [`Validate`]: multi-field procedural validation builder returning [`SlabError::ValidationErrors`].
11//! - [`AppConfig`]: runtime configuration loaded from `DATABASE_URL` and `SLABS_*` environment variables, plus [`AppConfig::for_test`] for isolated tests.
12//! - [`AppManifest`], [`RouteMeta`], and [`JobMeta`]: JSON metadata returned by `/_slabs/manifest` and `slabs manifest`, plus `OpenAPI` 3.1.0 export via [`AppManifest::to_openapi_3_1`].
13//!
14//! # HTTP status mapping
15//!
16//! [`SlabError`] implements [`axum::response::IntoResponse`] and returns a JSON body with `error` and `message` fields:
17//!
18//! | Variant | HTTP status | JSON `error` field | Notes |
19//! | --- | --- | --- | --- |
20//! | [`SlabError::BadRequest`] | `400` | `"bad_request"` | Includes the error message. |
21//! | [`SlabError::Unauthorized`] | `401` | `"unauthorized"` | Missing or invalid credentials. |
22//! | [`SlabError::Forbidden`] | `403` | `"forbidden"` | Authenticated caller lacks permission. |
23//! | [`SlabError::NotFound`] | `404` | `"not_found"` | Resource does not exist. |
24//! | [`SlabError::Database`] (`RowNotFound`) | `404` | `"not_found"` | Message is fixed to `"record not found"`. |
25//! | [`SlabError::Conflict`] | `409` | `"conflict"` | Unique key or state conflict. |
26//! | [`SlabError::Validation`] | `422` | `"validation_error"` | Also includes a `field` string. |
27//! | [`SlabError::ValidationErrors`] | `422` | `"validation_error"` | Includes a `fields` map of field names to error message lists. |
28//! | [`SlabError::TooManyRequests`] | `429` | `"too_many_requests"` | Sets `Retry-After` header and `retry_after_secs`. |
29//! | [`SlabError::Database`] (other) | `500` | `"database_error"` | Logs via `tracing::error!` and hides raw SQL details. |
30//! | [`SlabError::Internal`] | `500` | `"internal_error"` | Logs via `tracing::error!` and returns `"internal server error"`. |
31//!
32//! # Environment variables
33//!
34//! [`AppConfig::from_env`] reads these variables and falls back to local development defaults derived from `app_name`:
35//!
36//! - `SLABS_BIND`: bind address. Defaults to `"127.0.0.1:3000"`.
37//! - `DATABASE_URL`: database connection string. Defaults to `"sqlite://{app_name}.db?mode=rwc"`.
38//! - `SLABS_SECRET_KEY`: signing key for cookies, tokens, and HMAC digests. Defaults to a development-only string.
39//! - `SLABS_STORAGE_DIR`: local blob directory. Defaults to `"./storage/{app_name}"`.
40//! - `SLABS_ASSETS_DIR`: static assets directory. Defaults to `"./assets"` when present, otherwise `"./examples/{app_name}/assets"`.
41//! - `SLABS_JOB_POLL_MS`: background worker poll interval in milliseconds. Defaults to `500`.
42//! - `SLABS_JOB_CONCURRENCY`: maximum concurrent background jobs. Defaults to `4`.
43//! - `SLABS_COOKIE_SECURE`: enables the `Secure` cookie attribute when `"1"` or `"true"` (case-insensitive). Defaults to `false`.
44//! - `SLABS_WEBHOOKS_LIVE`: enables live outbound webhook HTTP requests when `"1"` or `"true"`. Defaults to `false`.
45//! - `SLABS_WEBHOOKS_ALLOW_LOCAL`: permits webhooks to target loopback addresses when `"1"` or `"true"`. Defaults to `false`.
46//!
47//! # Invariants
48//!
49//! - [`id::new`] produces lowercase ULIDs prefixed with `<prefix>_` so `SQLite` B-tree primary keys stay append-friendly.
50//! - Returning `?` on a [`sqlx::Error::RowNotFound`] produces HTTP 404 without manual mapping.
51//! - Unexpected database and internal errors never leak internal messages or SQL strings in the HTTP response body.
52//! - [`AppConfig::for_test`] pins `database_url` to `"sqlite::memory:"`, `bind_addr` to `"127.0.0.1:0"`, and disables live webhooks.
53//!
54//! # Usage
55//!
56//! ```rust
57//! use slabs_core::{id, AppConfig, SlabError, SlabResult};
58//!
59//! fn validate_title(title: &str) -> SlabResult<String> {
60//!     if title.trim().is_empty() {
61//!         return Err(SlabError::validation("title", "cannot be blank"));
62//!     }
63//!     Ok(id::new("room"))
64//! }
65//!
66//! let config = AppConfig::from_env("campfire");
67//! assert_eq!(config.app_name, "campfire");
68//! assert!(validate_title("Lobby").unwrap().starts_with("room_"));
69//! assert_eq!(validate_title("  ").unwrap_err().status_code().as_u16(), 422);
70//! ```
71
72use axum::{
73    http::StatusCode,
74    response::{IntoResponse, Response},
75    Json,
76};
77use serde::{Deserialize, Serialize};
78use serde_json::json;
79use std::collections::BTreeMap;
80use std::fmt;
81use std::path::PathBuf;
82use thiserror::Error;
83
84/// Prefix-tagged, time-sortable ULID generator (for example `msg_01j...` or `usr_01j...`).
85///
86/// Time-sorted IDs keep `SQLite` B-tree indexes compact and append-friendly.
87pub mod id {
88    use ulid::Ulid;
89
90    /// Generates a lowercase prefixed ULID string in the form `<prefix>_<ulid>`.
91    ///
92    /// The ULID suffix is 26 Crockford Base32 characters encoded in lowercase.
93    #[must_use]
94    pub fn new(prefix: &str) -> String {
95        format!("{prefix}_{}", Ulid::new().to_string().to_lowercase())
96    }
97}
98
99/// Unified HTTP error type returned by every transaction script and background job.
100///
101/// Implements [`IntoResponse`] with JSON error bodies and explicit HTTP status codes.
102#[derive(Debug, Error)]
103#[non_exhaustive]
104pub enum SlabError {
105    /// Input validation failure targeting a specific field (HTTP 422, `error: "validation_error"`).
106    #[error("validation failed on `{field}`: {message}")]
107    Validation {
108        /// Name of the field that failed validation.
109        field: String,
110        /// Human-readable description of the validation failure.
111        message: String,
112    },
113
114    /// Multi-field input validation failure (HTTP 422, `error: "validation_error"`).
115    #[error("validation failed on {} field(s)", .0.len())]
116    ValidationErrors(BTreeMap<String, Vec<String>>),
117
118    /// Malformed or invalid client request (HTTP 400, `error: "bad_request"`).
119    #[error("bad request: {0}")]
120    BadRequest(String),
121
122    /// Missing or invalid authentication credentials (HTTP 401, `error: "unauthorized"`).
123    #[error("unauthorized: {0}")]
124    Unauthorized(String),
125
126    /// Authenticated caller lacks permission for the requested action (HTTP 403, `error: "forbidden"`).
127    #[error("forbidden: {0}")]
128    Forbidden(String),
129
130    /// Requested resource does not exist (HTTP 404, `error: "not_found"`).
131    #[error("not found: {0}")]
132    NotFound(String),
133
134    /// Resource state conflict, such as a duplicate unique key (HTTP 409, `error: "conflict"`).
135    #[error("conflict: {0}")]
136    Conflict(String),
137
138    /// Rate limit exceeded (HTTP 429, `error: "too_many_requests"`).
139    ///
140    /// Sets the `Retry-After` response header to `retry_after_secs`.
141    #[error("too many requests: {message} (retry after {retry_after_secs}s)")]
142    TooManyRequests {
143        /// Seconds the client should wait before retrying.
144        retry_after_secs: u64,
145        /// Human-readable rate-limit explanation.
146        message: String,
147    },
148
149    /// Underlying `sqlx` database error.
150    ///
151    /// Maps [`sqlx::Error::RowNotFound`] to HTTP 404 (`"record not found"`).
152    /// Maps all other database errors to HTTP 500 and logs the raw error with `tracing::error!`.
153    #[error("database error: {0}")]
154    Database(#[from] sqlx::Error),
155
156    /// Unexpected server-side failure (HTTP 500, `error: "internal_error"`).
157    ///
158    /// Logs the message with `tracing::error!` and returns `"internal server error"` to clients.
159    #[error("internal error: {0}")]
160    Internal(String),
161}
162
163impl SlabError {
164    /// Creates a [`SlabError::Validation`] error (HTTP 422) for `field` with `message`.
165    #[must_use]
166    pub fn validation(field: impl Into<String>, message: impl Into<String>) -> Self {
167        Self::Validation {
168            field: field.into(),
169            message: message.into(),
170        }
171    }
172
173    /// Creates a [`SlabError::BadRequest`] error (HTTP 400).
174    #[must_use]
175    pub fn bad_request(msg: impl Into<String>) -> Self {
176        Self::BadRequest(msg.into())
177    }
178
179    /// Creates a [`SlabError::Unauthorized`] error (HTTP 401).
180    #[must_use]
181    pub fn unauthorized(msg: impl Into<String>) -> Self {
182        Self::Unauthorized(msg.into())
183    }
184
185    /// Creates a [`SlabError::Forbidden`] error (HTTP 403).
186    #[must_use]
187    pub fn forbidden(msg: impl Into<String>) -> Self {
188        Self::Forbidden(msg.into())
189    }
190
191    /// Creates a [`SlabError::NotFound`] error (HTTP 404).
192    #[must_use]
193    pub fn not_found(msg: impl Into<String>) -> Self {
194        Self::NotFound(msg.into())
195    }
196
197    /// Creates a [`SlabError::Conflict`] error (HTTP 409).
198    #[must_use]
199    pub fn conflict(msg: impl Into<String>) -> Self {
200        Self::Conflict(msg.into())
201    }
202
203    /// Creates a [`SlabError::TooManyRequests`] error (HTTP 429) with a `Retry-After` value in seconds.
204    #[must_use]
205    pub fn too_many_requests(retry_after_secs: u64, msg: impl Into<String>) -> Self {
206        Self::TooManyRequests {
207            retry_after_secs,
208            message: msg.into(),
209        }
210    }
211
212    /// Creates a [`SlabError::Internal`] error (HTTP 500).
213    #[must_use]
214    pub fn internal(msg: impl Into<String>) -> Self {
215        Self::Internal(msg.into())
216    }
217
218    /// Returns the HTTP [`StatusCode`] mapped to this error variant.
219    #[must_use]
220    pub fn status_code(&self) -> StatusCode {
221        match self {
222            Self::Validation { .. } | Self::ValidationErrors(_) => StatusCode::UNPROCESSABLE_ENTITY,
223            Self::BadRequest(_) => StatusCode::BAD_REQUEST,
224            Self::Unauthorized(_) => StatusCode::UNAUTHORIZED,
225            Self::Forbidden(_) => StatusCode::FORBIDDEN,
226            Self::NotFound(_) | Self::Database(sqlx::Error::RowNotFound) => StatusCode::NOT_FOUND,
227            Self::Conflict(_) => StatusCode::CONFLICT,
228            Self::TooManyRequests { .. } => StatusCode::TOO_MANY_REQUESTS,
229            Self::Database(_) | Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
230        }
231    }
232}
233
234impl IntoResponse for SlabError {
235    fn into_response(self) -> Response {
236        let status = self.status_code();
237        if let Self::TooManyRequests {
238            retry_after_secs,
239            message,
240        } = self
241        {
242            let mut resp = (
243                status,
244                Json(json!({
245                    "error": "too_many_requests",
246                    "retry_after_secs": retry_after_secs,
247                    "message": message,
248                })),
249            )
250                .into_response();
251            if let Ok(val) = http::HeaderValue::from_str(&retry_after_secs.to_string()) {
252                resp.headers_mut().insert(http::header::RETRY_AFTER, val);
253            }
254            return resp;
255        }
256        let body = match &self {
257            Self::Validation { field, message } => json!({
258                "error": "validation_error",
259                "field": field,
260                "message": message,
261            }),
262            Self::ValidationErrors(fields) => json!({
263                "error": "validation_error",
264                "fields": fields,
265            }),
266            Self::Database(sqlx::Error::RowNotFound) => json!({
267                "error": "not_found",
268                "message": "record not found",
269            }),
270            Self::Database(err) => {
271                tracing::error!(error = %err, "database error in slab");
272                json!({
273                    "error": "database_error",
274                    "message": "internal database error",
275                })
276            }
277            Self::Internal(msg) => {
278                tracing::error!(error = %msg, "internal error in slab");
279                json!({
280                    "error": "internal_error",
281                    "message": "internal server error",
282                })
283            }
284            other => json!({
285                "error": status.canonical_reason().unwrap_or("error").to_lowercase().replace(' ', "_"),
286                "message": other.to_string(),
287            }),
288        };
289
290        (status, Json(body)).into_response()
291    }
292}
293
294/// Result alias using [`SlabError`] as the error type.
295pub type SlabResult<T> = Result<T, SlabError>;
296
297/// Multi-field procedural validation builder for transaction scripts.
298///
299/// Accumulates field errors in deterministic key order and returns
300/// [`SlabError::ValidationErrors`] (HTTP 422) from [`Validate::finish`].
301#[derive(Debug, Clone, Default)]
302pub struct Validate {
303    errors: BTreeMap<String, Vec<String>>,
304}
305
306impl Validate {
307    /// Creates an empty [`Validate`] builder with no recorded errors.
308    #[must_use]
309    pub fn new() -> Self {
310        Self::default()
311    }
312
313    /// Requires `value` to be non-empty after trimming whitespace.
314    ///
315    /// Records `"is required"` under `field` when empty.
316    pub fn required(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
317        if value.trim().is_empty() {
318            self.push(field, "is required");
319        }
320        self
321    }
322
323    /// Requires the trimmed `value` to have at least `min` Unicode scalar characters.
324    pub fn min_len(&mut self, field: impl Into<String>, value: &str, min: usize) -> &mut Self {
325        if value.trim().chars().count() < min {
326            self.push(field, format!("must be at least {min} characters"));
327        }
328        self
329    }
330
331    /// Requires the trimmed `value` to have at most `max` Unicode scalar characters.
332    pub fn max_len(&mut self, field: impl Into<String>, value: &str, max: usize) -> &mut Self {
333        if value.trim().chars().count() > max {
334            self.push(field, format!("must be at most {max} characters"));
335        }
336        self
337    }
338
339    /// Requires the trimmed `value` to look like an email address.
340    ///
341    /// Checks that the trimmed string is non-empty, contains no whitespace, and has a
342    /// non-empty local part before `@` and a domain containing `.` after `@`.
343    pub fn email(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
344        let trimmed = value.trim();
345        let valid = !trimmed.is_empty()
346            && !trimmed.chars().any(char::is_whitespace)
347            && trimmed.split_once('@').is_some_and(|(local, domain)| {
348                !local.is_empty()
349                    && !domain.is_empty()
350                    && !domain.contains('@')
351                    && domain.contains('.')
352                    && !domain.starts_with('.')
353                    && !domain.ends_with('.')
354            });
355        if !valid {
356            self.push(field, "must be a valid email address");
357        }
358        self
359    }
360
361    /// Requires the trimmed `value` to start with `http://` or `https://` followed by a host.
362    pub fn url(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
363        let trimmed = value.trim();
364        let valid = !trimmed.chars().any(char::is_whitespace)
365            && ((trimmed.starts_with("http://") && trimmed.len() > "http://".len())
366                || (trimmed.starts_with("https://") && trimmed.len() > "https://".len()));
367        if !valid {
368            self.push(field, "must start with http:// or https://");
369        }
370        self
371    }
372
373    /// Requires `value` to match one of the entries in `allowed`.
374    pub fn one_of(&mut self, field: impl Into<String>, value: &str, allowed: &[&str]) -> &mut Self {
375        if !allowed.contains(&value) {
376            self.push(field, format!("must be one of: {}", allowed.join(", ")));
377        }
378        self
379    }
380
381    /// Records `message` under `field` when `condition` is `false`.
382    pub fn check(
383        &mut self,
384        field: impl Into<String>,
385        condition: bool,
386        message: impl Into<String>,
387    ) -> &mut Self {
388        if !condition {
389            self.push(field, message);
390        }
391        self
392    }
393
394    /// Unconditionally appends `message` to the error list for `field`.
395    pub fn push(&mut self, field: impl Into<String>, message: impl Into<String>) -> &mut Self {
396        self.errors
397            .entry(field.into())
398            .or_default()
399            .push(message.into());
400        self
401    }
402
403    /// Returns `true` when no validation errors have been recorded.
404    #[must_use]
405    pub fn is_empty(&self) -> bool {
406        self.errors.is_empty()
407    }
408
409    /// Returns the map of field names to accumulated validation messages.
410    #[must_use]
411    pub fn errors(&self) -> &BTreeMap<String, Vec<String>> {
412        &self.errors
413    }
414
415    /// Finalizes validation, returning `Ok(())` when empty or [`SlabError::ValidationErrors`].
416    pub fn finish(self) -> SlabResult<()> {
417        if self.errors.is_empty() {
418            Ok(())
419        } else {
420            Err(SlabError::ValidationErrors(self.errors))
421        }
422    }
423}
424
425/// Runtime configuration loaded from `SLABS_*` and `DATABASE_URL` environment variables.
426#[derive(Clone, Serialize, Deserialize)]
427pub struct AppConfig {
428    /// Application name used for default database filenames, storage directories, and manifests.
429    pub app_name: String,
430    /// Socket address to bind the HTTP server to (`SLABS_BIND`, default `"127.0.0.1:3000"`).
431    pub bind_addr: String,
432    /// Connection string for the primary database (`DATABASE_URL`, default `"sqlite://{app_name}.db?mode=rwc"`).
433    pub database_url: String,
434    /// Secret key for signing cookies, tokens, and HMAC digests (`SLABS_SECRET_KEY`).
435    pub secret_key: String,
436    /// Directory where uploaded blobs and local storage files are written (`SLABS_STORAGE_DIR`).
437    pub storage_dir: PathBuf,
438    /// Directory containing static assets such as CSS and JS files (`SLABS_ASSETS_DIR`).
439    pub assets_dir: PathBuf,
440    /// Polling interval in milliseconds for the background job worker (`SLABS_JOB_POLL_MS`, default `500`).
441    pub job_poll_interval_ms: u64,
442    /// Maximum number of background jobs executed concurrently (`SLABS_JOB_CONCURRENCY`, default `4`).
443    pub job_concurrency: usize,
444    /// Sets the `Secure` attribute on session cookies when `true` (`SLABS_COOKIE_SECURE`, default `false`).
445    pub cookie_secure: bool,
446    /// Enables live HTTP delivery for outbound webhooks when `true` (`SLABS_WEBHOOKS_LIVE`, default `false`).
447    pub webhooks_live: bool,
448    /// Allows outbound webhooks to target loopback addresses when `true` (`SLABS_WEBHOOKS_ALLOW_LOCAL`, default `false`).
449    pub webhooks_allow_local: bool,
450}
451
452impl fmt::Debug for AppConfig {
453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454        f.debug_struct("AppConfig")
455            .field("app_name", &self.app_name)
456            .field("bind_addr", &self.bind_addr)
457            .field("database_url", &self.database_url)
458            .field("secret_key", &"<redacted>")
459            .field("storage_dir", &self.storage_dir)
460            .field("assets_dir", &self.assets_dir)
461            .field("job_poll_interval_ms", &self.job_poll_interval_ms)
462            .field("job_concurrency", &self.job_concurrency)
463            .field("cookie_secure", &self.cookie_secure)
464            .field("webhooks_live", &self.webhooks_live)
465            .field("webhooks_allow_local", &self.webhooks_allow_local)
466            .finish()
467    }
468}
469
470impl AppConfig {
471    /// Loads configuration from `SLABS_*` and `DATABASE_URL` environment variables.
472    ///
473    /// Falls back to local development defaults derived from `app_name` when variables are unset.
474    /// Invalid numeric values for `SLABS_JOB_POLL_MS` or `SLABS_JOB_CONCURRENCY` also fall back to defaults.
475    #[must_use]
476    pub fn from_env(app_name: impl Into<String>) -> Self {
477        let app_name = app_name.into();
478        Self {
479            app_name: app_name.clone(),
480            bind_addr: std::env::var("SLABS_BIND").unwrap_or_else(|_| "127.0.0.1:3000".into()),
481            database_url: std::env::var("DATABASE_URL")
482                .unwrap_or_else(|_| format!("sqlite://{app_name}.db?mode=rwc")),
483            secret_key: std::env::var("SLABS_SECRET_KEY")
484                .unwrap_or_else(|_| "dev-only-change-me-in-production-slabs-secret-key".into()),
485            storage_dir: std::env::var("SLABS_STORAGE_DIR").map_or_else(
486                |_| PathBuf::from(format!("./storage/{app_name}")),
487                PathBuf::from,
488            ),
489            assets_dir: std::env::var("SLABS_ASSETS_DIR").map_or_else(
490                |_| {
491                    let local = PathBuf::from("./assets");
492                    if local.is_dir() {
493                        local
494                    } else {
495                        PathBuf::from(format!("./examples/{app_name}/assets"))
496                    }
497                },
498                PathBuf::from,
499            ),
500            job_poll_interval_ms: std::env::var("SLABS_JOB_POLL_MS")
501                .ok()
502                .and_then(|v| v.parse().ok())
503                .unwrap_or(500),
504            job_concurrency: std::env::var("SLABS_JOB_CONCURRENCY")
505                .ok()
506                .and_then(|v| v.parse().ok())
507                .unwrap_or(4),
508            cookie_secure: std::env::var("SLABS_COOKIE_SECURE")
509                .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
510            webhooks_live: std::env::var("SLABS_WEBHOOKS_LIVE")
511                .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
512            webhooks_allow_local: std::env::var("SLABS_WEBHOOKS_ALLOW_LOCAL")
513                .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
514        }
515    }
516
517    /// Builds an isolated configuration for parallel tests.
518    ///
519    /// Uses `database_url = "sqlite::memory:"`, `bind_addr = "127.0.0.1:0"`, a 50ms job poll interval,
520    /// and disables `cookie_secure`, `webhooks_live`, and `webhooks_allow_local`.
521    #[must_use]
522    pub fn for_test(app_name: impl Into<String>, storage_dir: PathBuf) -> Self {
523        let app_name = app_name.into();
524        let assets_dir = if PathBuf::from("./assets").is_dir() {
525            PathBuf::from("./assets")
526        } else {
527            PathBuf::from(format!("./examples/{app_name}/assets"))
528        };
529        Self {
530            app_name,
531            bind_addr: "127.0.0.1:0".into(),
532            database_url: "sqlite::memory:".into(),
533            secret_key: "test-secret-key-for-isolated-slabs-tests".into(),
534            storage_dir,
535            assets_dir,
536            job_poll_interval_ms: 50,
537            job_concurrency: 2,
538            cookie_secure: false,
539            webhooks_live: false,
540            webhooks_allow_local: false,
541        }
542    }
543}
544
545/// Machine-readable HTTP route metadata emitted by `/_slabs/manifest` and `slabs manifest`.
546///
547/// Agents read this list to inspect every registered endpoint in a single call.
548#[derive(Debug, Clone, Serialize, Deserialize)]
549pub struct RouteMeta {
550    /// Unique identifier for the slab route (for example `rooms::create_room`).
551    pub name: String,
552    /// HTTP verb accepted by the route (for example `GET` or `POST`).
553    pub method: String,
554    /// URL path pattern registered with the router (for example `/api/rooms/{room_id}`).
555    pub path: String,
556    /// Short description of what the slab does.
557    pub summary: String,
558    /// Feature group owning this slab, derived from `slabs/<feature>/`.
559    pub feature: String,
560    /// Optional JSON Schema describing the expected request body.
561    #[serde(default, skip_serializing_if = "Option::is_none")]
562    pub input_schema: Option<serde_json::Value>,
563    /// Optional JSON Schema describing the JSON response body.
564    #[serde(default, skip_serializing_if = "Option::is_none")]
565    pub output_schema: Option<serde_json::Value>,
566}
567
568/// Machine-readable metadata describing a registered background job.
569#[derive(Debug, Clone, Serialize, Deserialize)]
570pub struct JobMeta {
571    /// Unique job identifier used when enqueueing work.
572    pub name: String,
573    /// Queue name this job is routed to.
574    pub queue: String,
575    /// Maximum number of execution attempts before the worker marks the job failed.
576    pub max_attempts: i64,
577    /// Short description of what the job performs.
578    pub summary: String,
579}
580
581/// Complete JSON manifest of an application's discovered HTTP routes and background jobs.
582#[derive(Debug, Clone, Serialize, Deserialize)]
583pub struct AppManifest {
584    /// Name of the application producing this manifest.
585    pub app_name: String,
586    /// All HTTP slab routes registered in the application.
587    pub routes: Vec<RouteMeta>,
588    /// All background jobs registered in the application.
589    pub jobs: Vec<JobMeta>,
590}
591
592impl AppManifest {
593    /// Exports this application manifest as an `OpenAPI` `3.1.0` JSON document.
594    ///
595    /// Extracts `{param}` and `{*wildcard}` path segments into `OpenAPI` path parameters,
596    /// attaches `requestBody` (`application/json`) when `input_schema` is present, and
597    /// attaches `responses["200"]` (`application/json`) when `output_schema` is present.
598    #[must_use]
599    pub fn to_openapi_3_1(&self) -> serde_json::Value {
600        let mut paths = serde_json::Map::new();
601
602        for route in &self.routes {
603            let mut parameters = Vec::new();
604            let mut normalized_segments = Vec::new();
605
606            for segment in route.path.split('/') {
607                if let Some(inner) = segment.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
608                    let param_name = inner.strip_prefix('*').unwrap_or(inner);
609                    if !param_name.is_empty() {
610                        parameters.push(json!({
611                            "name": param_name,
612                            "in": "path",
613                            "required": true,
614                            "schema": { "type": "string" },
615                        }));
616                        normalized_segments.push(format!("{{{param_name}}}"));
617                        continue;
618                    }
619                }
620                normalized_segments.push(segment.to_string());
621            }
622
623            let openapi_path = normalized_segments.join("/");
624            let method_key = route.method.to_ascii_lowercase();
625
626            let mut operation = serde_json::Map::new();
627            operation.insert("operationId".into(), json!(route.name));
628            operation.insert("summary".into(), json!(route.summary));
629            if !route.feature.is_empty() {
630                operation.insert("tags".into(), json!([route.feature]));
631            }
632            if !parameters.is_empty() {
633                operation.insert("parameters".into(), serde_json::Value::Array(parameters));
634            }
635            if let Some(input_schema) = &route.input_schema {
636                operation.insert(
637                    "requestBody".into(),
638                    json!({
639                        "required": true,
640                        "content": {
641                            "application/json": {
642                                "schema": input_schema,
643                            }
644                        }
645                    }),
646                );
647            }
648
649            let ok_response = if let Some(output_schema) = &route.output_schema {
650                json!({
651                    "description": "Success",
652                    "content": {
653                        "application/json": {
654                            "schema": output_schema,
655                        }
656                    }
657                })
658            } else {
659                json!({
660                    "description": "Success",
661                })
662            };
663            operation.insert("responses".into(), json!({ "200": ok_response }));
664
665            let path_item = paths
666                .entry(openapi_path)
667                .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
668            if let Some(path_obj) = path_item.as_object_mut() {
669                path_obj.insert(method_key, serde_json::Value::Object(operation));
670            }
671        }
672
673        json!({
674            "openapi": "3.1.0",
675            "info": {
676                "title": self.app_name,
677                "version": "0.1.0",
678            },
679            "paths": serde_json::Value::Object(paths),
680        })
681    }
682}
683
684/// URL slug generation helpers.
685pub mod slug {
686    /// Convert arbitrary text into a lowercase, hyphen-separated URL slug.
687    ///
688    /// Keeps ASCII alphanumeric characters, collapses separator runs into a single `-`,
689    /// trims leading and trailing hyphens, and returns `"-"` if no alphanumeric characters remain.
690    #[must_use]
691    pub fn slugify(input: &str) -> String {
692        let mut out = String::with_capacity(input.len());
693        let mut prev_hyphen = true;
694        for ch in input.chars() {
695            if ch.is_ascii_alphanumeric() {
696                out.push(ch.to_ascii_lowercase());
697                prev_hyphen = false;
698            } else if !prev_hyphen {
699                out.push('-');
700                prev_hyphen = true;
701            }
702        }
703        while out.ends_with('-') {
704            out.pop();
705        }
706        if out.is_empty() {
707            "-".to_string()
708        } else {
709            out
710        }
711    }
712}
713
714/// Fractional list positioning helpers for O(1) single-row reordering.
715pub mod position {
716    /// Compute a fractional `f64` sort score between two optional neighbor positions.
717    ///
718    /// - `(None, None)` returns `1.0` (first item in an empty list).
719    /// - `(Some(prev), None)` returns `prev + 1.0` (append after `prev`).
720    /// - `(None, Some(next))` returns `next / 2.0` (prepend before `next`, or `next - 1.0` when `next <= 0.0`).
721    /// - `(Some(prev), Some(next))` returns `(prev + next) / 2.0` (insert between `prev` and `next`).
722    #[must_use]
723    pub fn between(prev: Option<f64>, next: Option<f64>) -> f64 {
724        match (prev, next) {
725            (None, None) => 1.0,
726            (Some(p), None) => p + 1.0,
727            (None, Some(n)) => {
728                if n > 0.0 {
729                    n / 2.0
730                } else {
731                    n - 1.0
732                }
733            }
734            (Some(p), Some(n)) => f64::midpoint(p, n),
735        }
736    }
737}
738
739/// Compute a lowercase SHA-256 hex digest over NUL-separated string parts.
740///
741/// Use this for content fingerprints, optimistic concurrency checks (`If-Match`), and cache keys.
742#[must_use]
743pub fn fingerprint(parts: &[&str]) -> String {
744    use sha2::{Digest, Sha256};
745
746    let mut hasher = Sha256::new();
747    for (idx, part) in parts.iter().enumerate() {
748        if idx > 0 {
749            hasher.update([0u8]);
750        }
751        hasher.update(part.as_bytes());
752    }
753    hex::encode(hasher.finalize())
754}
755
756#[cfg(test)]
757mod tests {
758    use super::*;
759
760    #[test]
761    fn slugify_normalizes_titles_and_fallbacks() {
762        assert_eq!(slug::slugify("Hello, World! 2026"), "hello-world-2026");
763        assert_eq!(
764            slug::slugify("  Rust & SQLite --- WAL  "),
765            "rust-sqlite-wal"
766        );
767        assert_eq!(slug::slugify("!!!"), "-");
768    }
769
770    #[test]
771    fn position_between_orders_items() {
772        assert!((position::between(None, None) - 1.0).abs() < f64::EPSILON);
773        assert!((position::between(Some(2.0), None) - 3.0).abs() < f64::EPSILON);
774        assert!((position::between(None, Some(1.0)) - 0.5).abs() < f64::EPSILON);
775        assert!((position::between(Some(1.0), Some(2.0)) - 1.5).abs() < f64::EPSILON);
776    }
777
778    #[test]
779    fn fingerprint_distinguishes_part_boundaries() {
780        assert_ne!(fingerprint(&["ab", "c"]), fingerprint(&["a", "bc"]));
781        assert_eq!(fingerprint(&["a", "b"]).len(), 64);
782    }
783
784    #[test]
785    fn app_config_debug_redacts_secret_key() {
786        let mut config = AppConfig::for_test("demo", PathBuf::from("./tmp"));
787        config.secret_key = "super-secret-signing-key".into();
788        let rendered = format!("{config:?}");
789        assert!(!rendered.contains("super-secret-signing-key"));
790        assert!(rendered.contains("<redacted>"));
791    }
792
793    #[test]
794    fn validate_builder_succeeds_for_valid_inputs() {
795        let mut v = Validate::new();
796        v.required("name", "  Alice  ")
797            .min_len("name", "  Alice  ", 3)
798            .max_len("name", "  Alice  ", 10)
799            .email("email", " alice@example.com ")
800            .url("website", "https://example.com/docs")
801            .one_of("role", "admin", &["member", "admin"])
802            .check("age", true, "must be adult");
803
804        assert!(v.is_empty());
805        assert!(v.errors().is_empty());
806        assert!(v.finish().is_ok());
807    }
808
809    #[test]
810    fn validate_builder_collects_all_field_errors_and_maps_to_422() {
811        let mut v = Validate::new();
812        v.required("title", "   ")
813            .min_len("title", "hi", 3)
814            .max_len("bio", "123456", 5)
815            .email("email", "not-an-email")
816            .url("website", "ftp://example.com")
817            .one_of("role", "owner", &["member", "admin"])
818            .check("terms", false, "must accept terms")
819            .push("custom", "extra problem");
820
821        assert!(!v.is_empty());
822        assert_eq!(v.errors()["title"].len(), 2);
823        assert_eq!(v.errors()["title"][0], "is required");
824        assert!(v.errors().contains_key("bio"));
825        assert!(v.errors().contains_key("email"));
826        assert!(v.errors().contains_key("website"));
827        assert!(v.errors().contains_key("role"));
828        assert_eq!(v.errors()["terms"], vec!["must accept terms"]);
829        assert_eq!(v.errors()["custom"], vec!["extra problem"]);
830
831        let err = v.finish().unwrap_err();
832        assert_eq!(err.status_code(), StatusCode::UNPROCESSABLE_ENTITY);
833
834        let response = err.into_response();
835        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
836    }
837
838    #[test]
839    fn validate_checks_unicode_char_lengths_and_email_url_edge_cases() {
840        let mut v = Validate::new();
841        // 5 chars ("café!"), even though UTF-8 byte length is 6
842        v.min_len("label", "café!", 5)
843            .max_len("label", "café!", 5)
844            .email("bad_at", "@example.com")
845            .email("bad_dot", "alice@localhost")
846            .email("bad_trail", "alice@example.")
847            .url("bare_scheme", "https://")
848            .url("http_ok", "http://localhost:3000");
849
850        assert!(!v.errors().contains_key("label"));
851        assert!(v.errors().contains_key("bad_at"));
852        assert!(v.errors().contains_key("bad_dot"));
853        assert!(v.errors().contains_key("bad_trail"));
854        assert!(v.errors().contains_key("bare_scheme"));
855        assert!(!v.errors().contains_key("http_ok"));
856    }
857
858    #[test]
859    fn app_manifest_to_openapi_3_1_builds_paths_params_and_schemas() {
860        let manifest = AppManifest {
861            app_name: "campfire".into(),
862            routes: vec![
863                RouteMeta {
864                    name: "rooms::list_rooms".into(),
865                    method: "GET".into(),
866                    path: "/api/rooms".into(),
867                    summary: "List all rooms".into(),
868                    feature: "rooms".into(),
869                    input_schema: None,
870                    output_schema: Some(json!({
871                        "type": "array",
872                        "items": { "type": "object" }
873                    })),
874                },
875                RouteMeta {
876                    name: "rooms::create_room".into(),
877                    method: "POST".into(),
878                    path: "/api/rooms".into(),
879                    summary: "Create a room".into(),
880                    feature: "rooms".into(),
881                    input_schema: Some(json!({
882                        "type": "object",
883                        "required": ["name"],
884                        "properties": { "name": { "type": "string" } }
885                    })),
886                    output_schema: Some(json!({
887                        "type": "object",
888                        "properties": { "id": { "type": "string" } }
889                    })),
890                },
891                RouteMeta {
892                    name: "messages::get_message".into(),
893                    method: "GET".into(),
894                    path: "/api/rooms/{room_id}/messages/{msg_id}".into(),
895                    summary: "Get one message".into(),
896                    feature: "messages".into(),
897                    input_schema: None,
898                    output_schema: None,
899                },
900                RouteMeta {
901                    name: "files::serve_asset".into(),
902                    method: "GET".into(),
903                    path: "/assets/{*filepath}".into(),
904                    summary: "Serve a static asset".into(),
905                    feature: "files".into(),
906                    input_schema: None,
907                    output_schema: None,
908                },
909            ],
910            jobs: vec![],
911        };
912
913        let doc = manifest.to_openapi_3_1();
914        assert_eq!(doc["openapi"], "3.1.0");
915        assert_eq!(doc["info"]["title"], "campfire");
916        assert_eq!(doc["info"]["version"], "0.1.0");
917
918        // Same path with GET and POST should merge into one Path Item object
919        assert_eq!(
920            doc["paths"]["/api/rooms"]["get"]["operationId"],
921            "rooms::list_rooms"
922        );
923        assert!(doc["paths"]["/api/rooms"]["get"]["requestBody"].is_null());
924        assert_eq!(
925            doc["paths"]["/api/rooms"]["get"]["responses"]["200"]["content"]["application/json"]
926                ["schema"]["type"],
927            "array"
928        );
929
930        assert_eq!(
931            doc["paths"]["/api/rooms"]["post"]["operationId"],
932            "rooms::create_room"
933        );
934        assert_eq!(
935            doc["paths"]["/api/rooms"]["post"]["requestBody"]["content"]["application/json"]
936                ["schema"]["required"][0],
937            "name"
938        );
939        assert_eq!(
940            doc["paths"]["/api/rooms"]["post"]["responses"]["200"]["content"]["application/json"]
941                ["schema"]["properties"]["id"]["type"],
942            "string"
943        );
944
945        // Multi-parameter path extraction
946        let params = doc["paths"]["/api/rooms/{room_id}/messages/{msg_id}"]["get"]["parameters"]
947            .as_array()
948            .unwrap();
949        assert_eq!(params.len(), 2);
950        assert_eq!(params[0]["name"], "room_id");
951        assert_eq!(params[0]["in"], "path");
952        assert_eq!(params[0]["required"], true);
953        assert_eq!(params[0]["schema"]["type"], "string");
954        assert_eq!(params[1]["name"], "msg_id");
955
956        // Wildcard parameter extraction
957        let wildcard_params = doc["paths"]["/assets/{filepath}"]["get"]["parameters"]
958            .as_array()
959            .unwrap();
960        assert_eq!(wildcard_params.len(), 1);
961        assert_eq!(wildcard_params[0]["name"], "filepath");
962        assert_eq!(wildcard_params[0]["in"], "path");
963        assert_eq!(wildcard_params[0]["required"], true);
964    }
965
966    #[test]
967    fn route_meta_omits_none_schemas_when_serialized() {
968        let meta = RouteMeta {
969            name: "health::check".into(),
970            method: "GET".into(),
971            path: "/health".into(),
972            summary: "Health check".into(),
973            feature: "health".into(),
974            input_schema: None,
975            output_schema: None,
976        };
977        let value = serde_json::to_value(&meta).unwrap();
978        assert!(value.get("input_schema").is_none());
979        assert!(value.get("output_schema").is_none());
980
981        let parsed: RouteMeta = serde_json::from_value(value).unwrap();
982        assert!(parsed.input_schema.is_none());
983        assert!(parsed.output_schema.is_none());
984    }
985}