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//! - [`AppConfig`]: runtime configuration loaded from `DATABASE_URL` and `SLABS_*` environment variables, plus [`AppConfig::for_test`] for isolated tests.
11//! - [`AppManifest`], [`RouteMeta`], and [`JobMeta`]: JSON metadata returned by `/_slabs/manifest` and `slabs manifest`.
12//!
13//! # HTTP status mapping
14//!
15//! [`SlabError`] implements [`axum::response::IntoResponse`] and returns a JSON body with `error` and `message` fields:
16//!
17//! | Variant | HTTP status | JSON `error` field | Notes |
18//! | --- | --- | --- | --- |
19//! | [`SlabError::BadRequest`] | `400` | `"bad_request"` | Includes the error message. |
20//! | [`SlabError::Unauthorized`] | `401` | `"unauthorized"` | Missing or invalid credentials. |
21//! | [`SlabError::Forbidden`] | `403` | `"forbidden"` | Authenticated caller lacks permission. |
22//! | [`SlabError::NotFound`] | `404` | `"not_found"` | Resource does not exist. |
23//! | [`SlabError::Database`] (`RowNotFound`) | `404` | `"not_found"` | Message is fixed to `"record not found"`. |
24//! | [`SlabError::Conflict`] | `409` | `"conflict"` | Unique key or state conflict. |
25//! | [`SlabError::Validation`] | `422` | `"validation_error"` | Also includes a `field` string. |
26//! | [`SlabError::TooManyRequests`] | `429` | `"too_many_requests"` | Sets `Retry-After` header and `retry_after_secs`. |
27//! | [`SlabError::Database`] (other) | `500` | `"database_error"` | Logs via `tracing::error!` and hides raw SQL details. |
28//! | [`SlabError::Internal`] | `500` | `"internal_error"` | Logs via `tracing::error!` and returns `"internal server error"`. |
29//!
30//! # Environment variables
31//!
32//! [`AppConfig::from_env`] reads these variables and falls back to local development defaults derived from `app_name`:
33//!
34//! - `SLABS_BIND`: bind address. Defaults to `"127.0.0.1:3000"`.
35//! - `DATABASE_URL`: database connection string. Defaults to `"sqlite://{app_name}.db?mode=rwc"`.
36//! - `SLABS_SECRET_KEY`: signing key for cookies, tokens, and HMAC digests. Defaults to a development-only string.
37//! - `SLABS_STORAGE_DIR`: local blob directory. Defaults to `"./storage/{app_name}"`.
38//! - `SLABS_ASSETS_DIR`: static assets directory. Defaults to `"./assets"` when present, otherwise `"./examples/{app_name}/assets"`.
39//! - `SLABS_JOB_POLL_MS`: background worker poll interval in milliseconds. Defaults to `500`.
40//! - `SLABS_JOB_CONCURRENCY`: maximum concurrent background jobs. Defaults to `4`.
41//! - `SLABS_COOKIE_SECURE`: enables the `Secure` cookie attribute when `"1"` or `"true"` (case-insensitive). Defaults to `false`.
42//! - `SLABS_WEBHOOKS_LIVE`: enables live outbound webhook HTTP requests when `"1"` or `"true"`. Defaults to `false`.
43//! - `SLABS_WEBHOOKS_ALLOW_LOCAL`: permits webhooks to target loopback addresses when `"1"` or `"true"`. Defaults to `false`.
44//!
45//! # Invariants
46//!
47//! - [`id::new`] produces lowercase ULIDs prefixed with `<prefix>_` so `SQLite` B-tree primary keys stay append-friendly.
48//! - Returning `?` on a [`sqlx::Error::RowNotFound`] produces HTTP 404 without manual mapping.
49//! - Unexpected database and internal errors never leak internal messages or SQL strings in the HTTP response body.
50//! - [`AppConfig::for_test`] pins `database_url` to `"sqlite::memory:"`, `bind_addr` to `"127.0.0.1:0"`, and disables live webhooks.
51//!
52//! # Usage
53//!
54//! ```rust
55//! use slabs_core::{id, AppConfig, SlabError, SlabResult};
56//!
57//! fn validate_title(title: &str) -> SlabResult<String> {
58//! if title.trim().is_empty() {
59//! return Err(SlabError::validation("title", "cannot be blank"));
60//! }
61//! Ok(id::new("room"))
62//! }
63//!
64//! let config = AppConfig::from_env("campfire");
65//! assert_eq!(config.app_name, "campfire");
66//! assert!(validate_title("Lobby").unwrap().starts_with("room_"));
67//! assert_eq!(validate_title(" ").unwrap_err().status_code().as_u16(), 422);
68//! ```
69
70use axum::{
71 http::StatusCode,
72 response::{IntoResponse, Response},
73 Json,
74};
75use serde::{Deserialize, Serialize};
76use serde_json::json;
77use std::fmt;
78use std::path::PathBuf;
79use thiserror::Error;
80
81/// Prefix-tagged, time-sortable ULID generator (for example `msg_01j...` or `usr_01j...`).
82///
83/// Time-sorted IDs keep `SQLite` B-tree indexes compact and append-friendly.
84pub mod id {
85 use ulid::Ulid;
86
87 /// Generates a lowercase prefixed ULID string in the form `<prefix>_<ulid>`.
88 ///
89 /// The ULID suffix is 26 Crockford Base32 characters encoded in lowercase.
90 #[must_use]
91 pub fn new(prefix: &str) -> String {
92 format!("{prefix}_{}", Ulid::new().to_string().to_lowercase())
93 }
94}
95
96/// Unified HTTP error type returned by every transaction script and background job.
97///
98/// Implements [`IntoResponse`] with JSON error bodies and explicit HTTP status codes.
99#[derive(Debug, Error)]
100#[non_exhaustive]
101pub enum SlabError {
102 /// Input validation failure targeting a specific field (HTTP 422, `error: "validation_error"`).
103 #[error("validation failed on `{field}`: {message}")]
104 Validation {
105 /// Name of the field that failed validation.
106 field: String,
107 /// Human-readable description of the validation failure.
108 message: String,
109 },
110
111 /// Malformed or invalid client request (HTTP 400, `error: "bad_request"`).
112 #[error("bad request: {0}")]
113 BadRequest(String),
114
115 /// Missing or invalid authentication credentials (HTTP 401, `error: "unauthorized"`).
116 #[error("unauthorized: {0}")]
117 Unauthorized(String),
118
119 /// Authenticated caller lacks permission for the requested action (HTTP 403, `error: "forbidden"`).
120 #[error("forbidden: {0}")]
121 Forbidden(String),
122
123 /// Requested resource does not exist (HTTP 404, `error: "not_found"`).
124 #[error("not found: {0}")]
125 NotFound(String),
126
127 /// Resource state conflict, such as a duplicate unique key (HTTP 409, `error: "conflict"`).
128 #[error("conflict: {0}")]
129 Conflict(String),
130
131 /// Rate limit exceeded (HTTP 429, `error: "too_many_requests"`).
132 ///
133 /// Sets the `Retry-After` response header to `retry_after_secs`.
134 #[error("too many requests: {message} (retry after {retry_after_secs}s)")]
135 TooManyRequests {
136 /// Seconds the client should wait before retrying.
137 retry_after_secs: u64,
138 /// Human-readable rate-limit explanation.
139 message: String,
140 },
141
142 /// Underlying `sqlx` database error.
143 ///
144 /// Maps [`sqlx::Error::RowNotFound`] to HTTP 404 (`"record not found"`).
145 /// Maps all other database errors to HTTP 500 and logs the raw error with `tracing::error!`.
146 #[error("database error: {0}")]
147 Database(#[from] sqlx::Error),
148
149 /// Unexpected server-side failure (HTTP 500, `error: "internal_error"`).
150 ///
151 /// Logs the message with `tracing::error!` and returns `"internal server error"` to clients.
152 #[error("internal error: {0}")]
153 Internal(String),
154}
155
156impl SlabError {
157 /// Creates a [`SlabError::Validation`] error (HTTP 422) for `field` with `message`.
158 #[must_use]
159 pub fn validation(field: impl Into<String>, message: impl Into<String>) -> Self {
160 Self::Validation {
161 field: field.into(),
162 message: message.into(),
163 }
164 }
165
166 /// Creates a [`SlabError::BadRequest`] error (HTTP 400).
167 #[must_use]
168 pub fn bad_request(msg: impl Into<String>) -> Self {
169 Self::BadRequest(msg.into())
170 }
171
172 /// Creates a [`SlabError::Unauthorized`] error (HTTP 401).
173 #[must_use]
174 pub fn unauthorized(msg: impl Into<String>) -> Self {
175 Self::Unauthorized(msg.into())
176 }
177
178 /// Creates a [`SlabError::Forbidden`] error (HTTP 403).
179 #[must_use]
180 pub fn forbidden(msg: impl Into<String>) -> Self {
181 Self::Forbidden(msg.into())
182 }
183
184 /// Creates a [`SlabError::NotFound`] error (HTTP 404).
185 #[must_use]
186 pub fn not_found(msg: impl Into<String>) -> Self {
187 Self::NotFound(msg.into())
188 }
189
190 /// Creates a [`SlabError::Conflict`] error (HTTP 409).
191 #[must_use]
192 pub fn conflict(msg: impl Into<String>) -> Self {
193 Self::Conflict(msg.into())
194 }
195
196 /// Creates a [`SlabError::TooManyRequests`] error (HTTP 429) with a `Retry-After` value in seconds.
197 #[must_use]
198 pub fn too_many_requests(retry_after_secs: u64, msg: impl Into<String>) -> Self {
199 Self::TooManyRequests {
200 retry_after_secs,
201 message: msg.into(),
202 }
203 }
204
205 /// Creates a [`SlabError::Internal`] error (HTTP 500).
206 #[must_use]
207 pub fn internal(msg: impl Into<String>) -> Self {
208 Self::Internal(msg.into())
209 }
210
211 /// Returns the HTTP [`StatusCode`] mapped to this error variant.
212 #[must_use]
213 pub fn status_code(&self) -> StatusCode {
214 match self {
215 Self::Validation { .. } => StatusCode::UNPROCESSABLE_ENTITY,
216 Self::BadRequest(_) => StatusCode::BAD_REQUEST,
217 Self::Unauthorized(_) => StatusCode::UNAUTHORIZED,
218 Self::Forbidden(_) => StatusCode::FORBIDDEN,
219 Self::NotFound(_) | Self::Database(sqlx::Error::RowNotFound) => StatusCode::NOT_FOUND,
220 Self::Conflict(_) => StatusCode::CONFLICT,
221 Self::TooManyRequests { .. } => StatusCode::TOO_MANY_REQUESTS,
222 Self::Database(_) | Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
223 }
224 }
225}
226
227impl IntoResponse for SlabError {
228 fn into_response(self) -> Response {
229 let status = self.status_code();
230 if let Self::TooManyRequests {
231 retry_after_secs,
232 message,
233 } = self
234 {
235 let mut resp = (
236 status,
237 Json(json!({
238 "error": "too_many_requests",
239 "retry_after_secs": retry_after_secs,
240 "message": message,
241 })),
242 )
243 .into_response();
244 if let Ok(val) = http::HeaderValue::from_str(&retry_after_secs.to_string()) {
245 resp.headers_mut().insert(http::header::RETRY_AFTER, val);
246 }
247 return resp;
248 }
249 let body = match &self {
250 Self::Validation { field, message } => json!({
251 "error": "validation_error",
252 "field": field,
253 "message": message,
254 }),
255 Self::Database(sqlx::Error::RowNotFound) => json!({
256 "error": "not_found",
257 "message": "record not found",
258 }),
259 Self::Database(err) => {
260 tracing::error!(error = %err, "database error in slab");
261 json!({
262 "error": "database_error",
263 "message": "internal database error",
264 })
265 }
266 Self::Internal(msg) => {
267 tracing::error!(error = %msg, "internal error in slab");
268 json!({
269 "error": "internal_error",
270 "message": "internal server error",
271 })
272 }
273 other => json!({
274 "error": status.canonical_reason().unwrap_or("error").to_lowercase().replace(' ', "_"),
275 "message": other.to_string(),
276 }),
277 };
278
279 (status, Json(body)).into_response()
280 }
281}
282
283/// Result alias using [`SlabError`] as the error type.
284pub type SlabResult<T> = Result<T, SlabError>;
285
286/// Runtime configuration loaded from `SLABS_*` and `DATABASE_URL` environment variables.
287#[derive(Clone, Serialize, Deserialize)]
288pub struct AppConfig {
289 /// Application name used for default database filenames, storage directories, and manifests.
290 pub app_name: String,
291 /// Socket address to bind the HTTP server to (`SLABS_BIND`, default `"127.0.0.1:3000"`).
292 pub bind_addr: String,
293 /// Connection string for the primary database (`DATABASE_URL`, default `"sqlite://{app_name}.db?mode=rwc"`).
294 pub database_url: String,
295 /// Secret key for signing cookies, tokens, and HMAC digests (`SLABS_SECRET_KEY`).
296 pub secret_key: String,
297 /// Directory where uploaded blobs and local storage files are written (`SLABS_STORAGE_DIR`).
298 pub storage_dir: PathBuf,
299 /// Directory containing static assets such as CSS and JS files (`SLABS_ASSETS_DIR`).
300 pub assets_dir: PathBuf,
301 /// Polling interval in milliseconds for the background job worker (`SLABS_JOB_POLL_MS`, default `500`).
302 pub job_poll_interval_ms: u64,
303 /// Maximum number of background jobs executed concurrently (`SLABS_JOB_CONCURRENCY`, default `4`).
304 pub job_concurrency: usize,
305 /// Sets the `Secure` attribute on session cookies when `true` (`SLABS_COOKIE_SECURE`, default `false`).
306 pub cookie_secure: bool,
307 /// Enables live HTTP delivery for outbound webhooks when `true` (`SLABS_WEBHOOKS_LIVE`, default `false`).
308 pub webhooks_live: bool,
309 /// Allows outbound webhooks to target loopback addresses when `true` (`SLABS_WEBHOOKS_ALLOW_LOCAL`, default `false`).
310 pub webhooks_allow_local: bool,
311}
312
313impl fmt::Debug for AppConfig {
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 f.debug_struct("AppConfig")
316 .field("app_name", &self.app_name)
317 .field("bind_addr", &self.bind_addr)
318 .field("database_url", &self.database_url)
319 .field("secret_key", &"<redacted>")
320 .field("storage_dir", &self.storage_dir)
321 .field("assets_dir", &self.assets_dir)
322 .field("job_poll_interval_ms", &self.job_poll_interval_ms)
323 .field("job_concurrency", &self.job_concurrency)
324 .field("cookie_secure", &self.cookie_secure)
325 .field("webhooks_live", &self.webhooks_live)
326 .field("webhooks_allow_local", &self.webhooks_allow_local)
327 .finish()
328 }
329}
330
331impl AppConfig {
332 /// Loads configuration from `SLABS_*` and `DATABASE_URL` environment variables.
333 ///
334 /// Falls back to local development defaults derived from `app_name` when variables are unset.
335 /// Invalid numeric values for `SLABS_JOB_POLL_MS` or `SLABS_JOB_CONCURRENCY` also fall back to defaults.
336 #[must_use]
337 pub fn from_env(app_name: impl Into<String>) -> Self {
338 let app_name = app_name.into();
339 Self {
340 app_name: app_name.clone(),
341 bind_addr: std::env::var("SLABS_BIND").unwrap_or_else(|_| "127.0.0.1:3000".into()),
342 database_url: std::env::var("DATABASE_URL")
343 .unwrap_or_else(|_| format!("sqlite://{app_name}.db?mode=rwc")),
344 secret_key: std::env::var("SLABS_SECRET_KEY")
345 .unwrap_or_else(|_| "dev-only-change-me-in-production-slabs-secret-key".into()),
346 storage_dir: std::env::var("SLABS_STORAGE_DIR").map_or_else(
347 |_| PathBuf::from(format!("./storage/{app_name}")),
348 PathBuf::from,
349 ),
350 assets_dir: std::env::var("SLABS_ASSETS_DIR").map_or_else(
351 |_| {
352 let local = PathBuf::from("./assets");
353 if local.is_dir() {
354 local
355 } else {
356 PathBuf::from(format!("./examples/{app_name}/assets"))
357 }
358 },
359 PathBuf::from,
360 ),
361 job_poll_interval_ms: std::env::var("SLABS_JOB_POLL_MS")
362 .ok()
363 .and_then(|v| v.parse().ok())
364 .unwrap_or(500),
365 job_concurrency: std::env::var("SLABS_JOB_CONCURRENCY")
366 .ok()
367 .and_then(|v| v.parse().ok())
368 .unwrap_or(4),
369 cookie_secure: std::env::var("SLABS_COOKIE_SECURE")
370 .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
371 webhooks_live: std::env::var("SLABS_WEBHOOKS_LIVE")
372 .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
373 webhooks_allow_local: std::env::var("SLABS_WEBHOOKS_ALLOW_LOCAL")
374 .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
375 }
376 }
377
378 /// Builds an isolated configuration for parallel tests.
379 ///
380 /// Uses `database_url = "sqlite::memory:"`, `bind_addr = "127.0.0.1:0"`, a 50ms job poll interval,
381 /// and disables `cookie_secure`, `webhooks_live`, and `webhooks_allow_local`.
382 #[must_use]
383 pub fn for_test(app_name: impl Into<String>, storage_dir: PathBuf) -> Self {
384 let app_name = app_name.into();
385 let assets_dir = if PathBuf::from("./assets").is_dir() {
386 PathBuf::from("./assets")
387 } else {
388 PathBuf::from(format!("./examples/{app_name}/assets"))
389 };
390 Self {
391 app_name,
392 bind_addr: "127.0.0.1:0".into(),
393 database_url: "sqlite::memory:".into(),
394 secret_key: "test-secret-key-for-isolated-slabs-tests".into(),
395 storage_dir,
396 assets_dir,
397 job_poll_interval_ms: 50,
398 job_concurrency: 2,
399 cookie_secure: false,
400 webhooks_live: false,
401 webhooks_allow_local: false,
402 }
403 }
404}
405
406/// Machine-readable HTTP route metadata emitted by `/_slabs/manifest` and `slabs manifest`.
407///
408/// Agents read this list to inspect every registered endpoint in a single call.
409#[derive(Debug, Clone, Serialize, Deserialize)]
410pub struct RouteMeta {
411 /// Unique identifier for the slab route (for example `rooms::create_room`).
412 pub name: String,
413 /// HTTP verb accepted by the route (for example `GET` or `POST`).
414 pub method: String,
415 /// URL path pattern registered with the router (for example `/api/rooms/{room_id}`).
416 pub path: String,
417 /// Short description of what the slab does.
418 pub summary: String,
419 /// Feature group owning this slab, derived from `slabs/<feature>/`.
420 pub feature: String,
421}
422
423/// Machine-readable metadata describing a registered background job.
424#[derive(Debug, Clone, Serialize, Deserialize)]
425pub struct JobMeta {
426 /// Unique job identifier used when enqueueing work.
427 pub name: String,
428 /// Queue name this job is routed to.
429 pub queue: String,
430 /// Maximum number of execution attempts before the worker marks the job failed.
431 pub max_attempts: i64,
432 /// Short description of what the job performs.
433 pub summary: String,
434}
435
436/// Complete JSON manifest of an application's discovered HTTP routes and background jobs.
437#[derive(Debug, Clone, Serialize, Deserialize)]
438pub struct AppManifest {
439 /// Name of the application producing this manifest.
440 pub app_name: String,
441 /// All HTTP slab routes registered in the application.
442 pub routes: Vec<RouteMeta>,
443 /// All background jobs registered in the application.
444 pub jobs: Vec<JobMeta>,
445}
446
447/// URL slug generation helpers.
448pub mod slug {
449 /// Convert arbitrary text into a lowercase, hyphen-separated URL slug.
450 ///
451 /// Keeps ASCII alphanumeric characters, collapses separator runs into a single `-`,
452 /// trims leading and trailing hyphens, and returns `"-"` if no alphanumeric characters remain.
453 #[must_use]
454 pub fn slugify(input: &str) -> String {
455 let mut out = String::with_capacity(input.len());
456 let mut prev_hyphen = true;
457 for ch in input.chars() {
458 if ch.is_ascii_alphanumeric() {
459 out.push(ch.to_ascii_lowercase());
460 prev_hyphen = false;
461 } else if !prev_hyphen {
462 out.push('-');
463 prev_hyphen = true;
464 }
465 }
466 while out.ends_with('-') {
467 out.pop();
468 }
469 if out.is_empty() {
470 "-".to_string()
471 } else {
472 out
473 }
474 }
475}
476
477/// Fractional list positioning helpers for O(1) single-row reordering.
478pub mod position {
479 /// Compute a fractional `f64` sort score between two optional neighbor positions.
480 ///
481 /// - `(None, None)` returns `1.0` (first item in an empty list).
482 /// - `(Some(prev), None)` returns `prev + 1.0` (append after `prev`).
483 /// - `(None, Some(next))` returns `next / 2.0` (prepend before `next`, or `next - 1.0` when `next <= 0.0`).
484 /// - `(Some(prev), Some(next))` returns `(prev + next) / 2.0` (insert between `prev` and `next`).
485 #[must_use]
486 pub fn between(prev: Option<f64>, next: Option<f64>) -> f64 {
487 match (prev, next) {
488 (None, None) => 1.0,
489 (Some(p), None) => p + 1.0,
490 (None, Some(n)) => {
491 if n > 0.0 {
492 n / 2.0
493 } else {
494 n - 1.0
495 }
496 }
497 (Some(p), Some(n)) => f64::midpoint(p, n),
498 }
499 }
500}
501
502/// Compute a lowercase SHA-256 hex digest over NUL-separated string parts.
503///
504/// Use this for content fingerprints, optimistic concurrency checks (`If-Match`), and cache keys.
505#[must_use]
506pub fn fingerprint(parts: &[&str]) -> String {
507 use sha2::{Digest, Sha256};
508
509 let mut hasher = Sha256::new();
510 for (idx, part) in parts.iter().enumerate() {
511 if idx > 0 {
512 hasher.update([0u8]);
513 }
514 hasher.update(part.as_bytes());
515 }
516 hex::encode(hasher.finalize())
517}
518
519#[cfg(test)]
520mod tests {
521 use super::*;
522
523 #[test]
524 fn slugify_normalizes_titles_and_fallbacks() {
525 assert_eq!(slug::slugify("Hello, World! 2026"), "hello-world-2026");
526 assert_eq!(
527 slug::slugify(" Rust & SQLite --- WAL "),
528 "rust-sqlite-wal"
529 );
530 assert_eq!(slug::slugify("!!!"), "-");
531 }
532
533 #[test]
534 fn position_between_orders_items() {
535 assert!((position::between(None, None) - 1.0).abs() < f64::EPSILON);
536 assert!((position::between(Some(2.0), None) - 3.0).abs() < f64::EPSILON);
537 assert!((position::between(None, Some(1.0)) - 0.5).abs() < f64::EPSILON);
538 assert!((position::between(Some(1.0), Some(2.0)) - 1.5).abs() < f64::EPSILON);
539 }
540
541 #[test]
542 fn fingerprint_distinguishes_part_boundaries() {
543 assert_ne!(fingerprint(&["ab", "c"]), fingerprint(&["a", "bc"]));
544 assert_eq!(fingerprint(&["a", "b"]).len(), 64);
545 }
546
547 #[test]
548 fn app_config_debug_redacts_secret_key() {
549 let mut config = AppConfig::for_test("demo", PathBuf::from("./tmp"));
550 config.secret_key = "super-secret-signing-key".into();
551 let rendered = format!("{config:?}");
552 assert!(!rendered.contains("super-secret-signing-key"));
553 assert!(rendered.contains("<redacted>"));
554 }
555}