slabs-core 0.1.0

Core error, ID, config, and manifest primitives 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
//! Core types for the Slabs web framework.
//!
//! This crate owns prefixed ULID generation, the unified HTTP error type,
//! environment configuration, and JSON route/job manifests.
//!
//! # Owned types
//!
//! - [`id::new`]: generates lowercase, time-sortable prefixed ULIDs such as `msg_01j...`.
//! - [`SlabError`] and [`SlabResult`]: explicit error enum returned by every transaction script and background job.
//! - [`AppConfig`]: runtime configuration loaded from `DATABASE_URL` and `SLABS_*` environment variables, plus [`AppConfig::for_test`] for isolated tests.
//! - [`AppManifest`], [`RouteMeta`], and [`JobMeta`]: JSON metadata returned by `/_slabs/manifest` and `slabs manifest`.
//!
//! # HTTP status mapping
//!
//! [`SlabError`] implements [`axum::response::IntoResponse`] and returns a JSON body with `error` and `message` fields:
//!
//! | Variant | HTTP status | JSON `error` field | Notes |
//! | --- | --- | --- | --- |
//! | [`SlabError::BadRequest`] | `400` | `"bad_request"` | Includes the error message. |
//! | [`SlabError::Unauthorized`] | `401` | `"unauthorized"` | Missing or invalid credentials. |
//! | [`SlabError::Forbidden`] | `403` | `"forbidden"` | Authenticated caller lacks permission. |
//! | [`SlabError::NotFound`] | `404` | `"not_found"` | Resource does not exist. |
//! | [`SlabError::Database`] (`RowNotFound`) | `404` | `"not_found"` | Message is fixed to `"record not found"`. |
//! | [`SlabError::Conflict`] | `409` | `"conflict"` | Unique key or state conflict. |
//! | [`SlabError::Validation`] | `422` | `"validation_error"` | Also includes a `field` string. |
//! | [`SlabError::TooManyRequests`] | `429` | `"too_many_requests"` | Sets `Retry-After` header and `retry_after_secs`. |
//! | [`SlabError::Database`] (other) | `500` | `"database_error"` | Logs via `tracing::error!` and hides raw SQL details. |
//! | [`SlabError::Internal`] | `500` | `"internal_error"` | Logs via `tracing::error!` and returns `"internal server error"`. |
//!
//! # Environment variables
//!
//! [`AppConfig::from_env`] reads these variables and falls back to local development defaults derived from `app_name`:
//!
//! - `SLABS_BIND`: bind address. Defaults to `"127.0.0.1:3000"`.
//! - `DATABASE_URL`: database connection string. Defaults to `"sqlite://{app_name}.db?mode=rwc"`.
//! - `SLABS_SECRET_KEY`: signing key for cookies, tokens, and HMAC digests. Defaults to a development-only string.
//! - `SLABS_STORAGE_DIR`: local blob directory. Defaults to `"./storage/{app_name}"`.
//! - `SLABS_ASSETS_DIR`: static assets directory. Defaults to `"./assets"` when present, otherwise `"./examples/{app_name}/assets"`.
//! - `SLABS_JOB_POLL_MS`: background worker poll interval in milliseconds. Defaults to `500`.
//! - `SLABS_JOB_CONCURRENCY`: maximum concurrent background jobs. Defaults to `4`.
//! - `SLABS_COOKIE_SECURE`: enables the `Secure` cookie attribute when `"1"` or `"true"` (case-insensitive). Defaults to `false`.
//! - `SLABS_WEBHOOKS_LIVE`: enables live outbound webhook HTTP requests when `"1"` or `"true"`. Defaults to `false`.
//! - `SLABS_WEBHOOKS_ALLOW_LOCAL`: permits webhooks to target loopback addresses when `"1"` or `"true"`. Defaults to `false`.
//!
//! # Invariants
//!
//! - [`id::new`] produces lowercase ULIDs prefixed with `<prefix>_` so `SQLite` B-tree primary keys stay append-friendly.
//! - Returning `?` on a [`sqlx::Error::RowNotFound`] produces HTTP 404 without manual mapping.
//! - Unexpected database and internal errors never leak internal messages or SQL strings in the HTTP response body.
//! - [`AppConfig::for_test`] pins `database_url` to `"sqlite::memory:"`, `bind_addr` to `"127.0.0.1:0"`, and disables live webhooks.
//!
//! # Usage
//!
//! ```rust
//! use slabs_core::{id, AppConfig, SlabError, SlabResult};
//!
//! fn validate_title(title: &str) -> SlabResult<String> {
//!     if title.trim().is_empty() {
//!         return Err(SlabError::validation("title", "cannot be blank"));
//!     }
//!     Ok(id::new("room"))
//! }
//!
//! let config = AppConfig::from_env("campfire");
//! assert_eq!(config.app_name, "campfire");
//! assert!(validate_title("Lobby").unwrap().starts_with("room_"));
//! assert_eq!(validate_title("  ").unwrap_err().status_code().as_u16(), 422);
//! ```

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::fmt;
use std::path::PathBuf;
use thiserror::Error;

/// Prefix-tagged, time-sortable ULID generator (for example `msg_01j...` or `usr_01j...`).
///
/// Time-sorted IDs keep `SQLite` B-tree indexes compact and append-friendly.
pub mod id {
    use ulid::Ulid;

    /// Generates a lowercase prefixed ULID string in the form `<prefix>_<ulid>`.
    ///
    /// The ULID suffix is 26 Crockford Base32 characters encoded in lowercase.
    #[must_use]
    pub fn new(prefix: &str) -> String {
        format!("{prefix}_{}", Ulid::new().to_string().to_lowercase())
    }
}

/// Unified HTTP error type returned by every transaction script and background job.
///
/// Implements [`IntoResponse`] with JSON error bodies and explicit HTTP status codes.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum SlabError {
    /// Input validation failure targeting a specific field (HTTP 422, `error: "validation_error"`).
    #[error("validation failed on `{field}`: {message}")]
    Validation {
        /// Name of the field that failed validation.
        field: String,
        /// Human-readable description of the validation failure.
        message: String,
    },

    /// Malformed or invalid client request (HTTP 400, `error: "bad_request"`).
    #[error("bad request: {0}")]
    BadRequest(String),

    /// Missing or invalid authentication credentials (HTTP 401, `error: "unauthorized"`).
    #[error("unauthorized: {0}")]
    Unauthorized(String),

    /// Authenticated caller lacks permission for the requested action (HTTP 403, `error: "forbidden"`).
    #[error("forbidden: {0}")]
    Forbidden(String),

    /// Requested resource does not exist (HTTP 404, `error: "not_found"`).
    #[error("not found: {0}")]
    NotFound(String),

    /// Resource state conflict, such as a duplicate unique key (HTTP 409, `error: "conflict"`).
    #[error("conflict: {0}")]
    Conflict(String),

    /// Rate limit exceeded (HTTP 429, `error: "too_many_requests"`).
    ///
    /// Sets the `Retry-After` response header to `retry_after_secs`.
    #[error("too many requests: {message} (retry after {retry_after_secs}s)")]
    TooManyRequests {
        /// Seconds the client should wait before retrying.
        retry_after_secs: u64,
        /// Human-readable rate-limit explanation.
        message: String,
    },

    /// Underlying `sqlx` database error.
    ///
    /// Maps [`sqlx::Error::RowNotFound`] to HTTP 404 (`"record not found"`).
    /// Maps all other database errors to HTTP 500 and logs the raw error with `tracing::error!`.
    #[error("database error: {0}")]
    Database(#[from] sqlx::Error),

    /// Unexpected server-side failure (HTTP 500, `error: "internal_error"`).
    ///
    /// Logs the message with `tracing::error!` and returns `"internal server error"` to clients.
    #[error("internal error: {0}")]
    Internal(String),
}

impl SlabError {
    /// Creates a [`SlabError::Validation`] error (HTTP 422) for `field` with `message`.
    #[must_use]
    pub fn validation(field: impl Into<String>, message: impl Into<String>) -> Self {
        Self::Validation {
            field: field.into(),
            message: message.into(),
        }
    }

    /// Creates a [`SlabError::BadRequest`] error (HTTP 400).
    #[must_use]
    pub fn bad_request(msg: impl Into<String>) -> Self {
        Self::BadRequest(msg.into())
    }

    /// Creates a [`SlabError::Unauthorized`] error (HTTP 401).
    #[must_use]
    pub fn unauthorized(msg: impl Into<String>) -> Self {
        Self::Unauthorized(msg.into())
    }

    /// Creates a [`SlabError::Forbidden`] error (HTTP 403).
    #[must_use]
    pub fn forbidden(msg: impl Into<String>) -> Self {
        Self::Forbidden(msg.into())
    }

    /// Creates a [`SlabError::NotFound`] error (HTTP 404).
    #[must_use]
    pub fn not_found(msg: impl Into<String>) -> Self {
        Self::NotFound(msg.into())
    }

    /// Creates a [`SlabError::Conflict`] error (HTTP 409).
    #[must_use]
    pub fn conflict(msg: impl Into<String>) -> Self {
        Self::Conflict(msg.into())
    }

    /// Creates a [`SlabError::TooManyRequests`] error (HTTP 429) with a `Retry-After` value in seconds.
    #[must_use]
    pub fn too_many_requests(retry_after_secs: u64, msg: impl Into<String>) -> Self {
        Self::TooManyRequests {
            retry_after_secs,
            message: msg.into(),
        }
    }

    /// Creates a [`SlabError::Internal`] error (HTTP 500).
    #[must_use]
    pub fn internal(msg: impl Into<String>) -> Self {
        Self::Internal(msg.into())
    }

    /// Returns the HTTP [`StatusCode`] mapped to this error variant.
    #[must_use]
    pub fn status_code(&self) -> StatusCode {
        match self {
            Self::Validation { .. } => StatusCode::UNPROCESSABLE_ENTITY,
            Self::BadRequest(_) => StatusCode::BAD_REQUEST,
            Self::Unauthorized(_) => StatusCode::UNAUTHORIZED,
            Self::Forbidden(_) => StatusCode::FORBIDDEN,
            Self::NotFound(_) | Self::Database(sqlx::Error::RowNotFound) => StatusCode::NOT_FOUND,
            Self::Conflict(_) => StatusCode::CONFLICT,
            Self::TooManyRequests { .. } => StatusCode::TOO_MANY_REQUESTS,
            Self::Database(_) | Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl IntoResponse for SlabError {
    fn into_response(self) -> Response {
        let status = self.status_code();
        if let Self::TooManyRequests {
            retry_after_secs,
            message,
        } = self
        {
            let mut resp = (
                status,
                Json(json!({
                    "error": "too_many_requests",
                    "retry_after_secs": retry_after_secs,
                    "message": message,
                })),
            )
                .into_response();
            if let Ok(val) = http::HeaderValue::from_str(&retry_after_secs.to_string()) {
                resp.headers_mut().insert(http::header::RETRY_AFTER, val);
            }
            return resp;
        }
        let body = match &self {
            Self::Validation { field, message } => json!({
                "error": "validation_error",
                "field": field,
                "message": message,
            }),
            Self::Database(sqlx::Error::RowNotFound) => json!({
                "error": "not_found",
                "message": "record not found",
            }),
            Self::Database(err) => {
                tracing::error!(error = %err, "database error in slab");
                json!({
                    "error": "database_error",
                    "message": "internal database error",
                })
            }
            Self::Internal(msg) => {
                tracing::error!(error = %msg, "internal error in slab");
                json!({
                    "error": "internal_error",
                    "message": "internal server error",
                })
            }
            other => json!({
                "error": status.canonical_reason().unwrap_or("error").to_lowercase().replace(' ', "_"),
                "message": other.to_string(),
            }),
        };

        (status, Json(body)).into_response()
    }
}

/// Result alias using [`SlabError`] as the error type.
pub type SlabResult<T> = Result<T, SlabError>;

/// Runtime configuration loaded from `SLABS_*` and `DATABASE_URL` environment variables.
#[derive(Clone, Serialize, Deserialize)]
pub struct AppConfig {
    /// Application name used for default database filenames, storage directories, and manifests.
    pub app_name: String,
    /// Socket address to bind the HTTP server to (`SLABS_BIND`, default `"127.0.0.1:3000"`).
    pub bind_addr: String,
    /// Connection string for the primary database (`DATABASE_URL`, default `"sqlite://{app_name}.db?mode=rwc"`).
    pub database_url: String,
    /// Secret key for signing cookies, tokens, and HMAC digests (`SLABS_SECRET_KEY`).
    pub secret_key: String,
    /// Directory where uploaded blobs and local storage files are written (`SLABS_STORAGE_DIR`).
    pub storage_dir: PathBuf,
    /// Directory containing static assets such as CSS and JS files (`SLABS_ASSETS_DIR`).
    pub assets_dir: PathBuf,
    /// Polling interval in milliseconds for the background job worker (`SLABS_JOB_POLL_MS`, default `500`).
    pub job_poll_interval_ms: u64,
    /// Maximum number of background jobs executed concurrently (`SLABS_JOB_CONCURRENCY`, default `4`).
    pub job_concurrency: usize,
    /// Sets the `Secure` attribute on session cookies when `true` (`SLABS_COOKIE_SECURE`, default `false`).
    pub cookie_secure: bool,
    /// Enables live HTTP delivery for outbound webhooks when `true` (`SLABS_WEBHOOKS_LIVE`, default `false`).
    pub webhooks_live: bool,
    /// Allows outbound webhooks to target loopback addresses when `true` (`SLABS_WEBHOOKS_ALLOW_LOCAL`, default `false`).
    pub webhooks_allow_local: bool,
}

impl fmt::Debug for AppConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AppConfig")
            .field("app_name", &self.app_name)
            .field("bind_addr", &self.bind_addr)
            .field("database_url", &self.database_url)
            .field("secret_key", &"<redacted>")
            .field("storage_dir", &self.storage_dir)
            .field("assets_dir", &self.assets_dir)
            .field("job_poll_interval_ms", &self.job_poll_interval_ms)
            .field("job_concurrency", &self.job_concurrency)
            .field("cookie_secure", &self.cookie_secure)
            .field("webhooks_live", &self.webhooks_live)
            .field("webhooks_allow_local", &self.webhooks_allow_local)
            .finish()
    }
}

impl AppConfig {
    /// Loads configuration from `SLABS_*` and `DATABASE_URL` environment variables.
    ///
    /// Falls back to local development defaults derived from `app_name` when variables are unset.
    /// Invalid numeric values for `SLABS_JOB_POLL_MS` or `SLABS_JOB_CONCURRENCY` also fall back to defaults.
    #[must_use]
    pub fn from_env(app_name: impl Into<String>) -> Self {
        let app_name = app_name.into();
        Self {
            app_name: app_name.clone(),
            bind_addr: std::env::var("SLABS_BIND").unwrap_or_else(|_| "127.0.0.1:3000".into()),
            database_url: std::env::var("DATABASE_URL")
                .unwrap_or_else(|_| format!("sqlite://{app_name}.db?mode=rwc")),
            secret_key: std::env::var("SLABS_SECRET_KEY")
                .unwrap_or_else(|_| "dev-only-change-me-in-production-slabs-secret-key".into()),
            storage_dir: std::env::var("SLABS_STORAGE_DIR").map_or_else(
                |_| PathBuf::from(format!("./storage/{app_name}")),
                PathBuf::from,
            ),
            assets_dir: std::env::var("SLABS_ASSETS_DIR").map_or_else(
                |_| {
                    let local = PathBuf::from("./assets");
                    if local.is_dir() {
                        local
                    } else {
                        PathBuf::from(format!("./examples/{app_name}/assets"))
                    }
                },
                PathBuf::from,
            ),
            job_poll_interval_ms: std::env::var("SLABS_JOB_POLL_MS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(500),
            job_concurrency: std::env::var("SLABS_JOB_CONCURRENCY")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(4),
            cookie_secure: std::env::var("SLABS_COOKIE_SECURE")
                .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
            webhooks_live: std::env::var("SLABS_WEBHOOKS_LIVE")
                .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
            webhooks_allow_local: std::env::var("SLABS_WEBHOOKS_ALLOW_LOCAL")
                .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
        }
    }

    /// Builds an isolated configuration for parallel tests.
    ///
    /// Uses `database_url = "sqlite::memory:"`, `bind_addr = "127.0.0.1:0"`, a 50ms job poll interval,
    /// and disables `cookie_secure`, `webhooks_live`, and `webhooks_allow_local`.
    #[must_use]
    pub fn for_test(app_name: impl Into<String>, storage_dir: PathBuf) -> Self {
        let app_name = app_name.into();
        let assets_dir = if PathBuf::from("./assets").is_dir() {
            PathBuf::from("./assets")
        } else {
            PathBuf::from(format!("./examples/{app_name}/assets"))
        };
        Self {
            app_name,
            bind_addr: "127.0.0.1:0".into(),
            database_url: "sqlite::memory:".into(),
            secret_key: "test-secret-key-for-isolated-slabs-tests".into(),
            storage_dir,
            assets_dir,
            job_poll_interval_ms: 50,
            job_concurrency: 2,
            cookie_secure: false,
            webhooks_live: false,
            webhooks_allow_local: false,
        }
    }
}

/// Machine-readable HTTP route metadata emitted by `/_slabs/manifest` and `slabs manifest`.
///
/// Agents read this list to inspect every registered endpoint in a single call.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteMeta {
    /// Unique identifier for the slab route (for example `rooms::create_room`).
    pub name: String,
    /// HTTP verb accepted by the route (for example `GET` or `POST`).
    pub method: String,
    /// URL path pattern registered with the router (for example `/api/rooms/{room_id}`).
    pub path: String,
    /// Short description of what the slab does.
    pub summary: String,
    /// Feature group owning this slab, derived from `slabs/<feature>/`.
    pub feature: String,
}

/// Machine-readable metadata describing a registered background job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobMeta {
    /// Unique job identifier used when enqueueing work.
    pub name: String,
    /// Queue name this job is routed to.
    pub queue: String,
    /// Maximum number of execution attempts before the worker marks the job failed.
    pub max_attempts: i64,
    /// Short description of what the job performs.
    pub summary: String,
}

/// Complete JSON manifest of an application's discovered HTTP routes and background jobs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppManifest {
    /// Name of the application producing this manifest.
    pub app_name: String,
    /// All HTTP slab routes registered in the application.
    pub routes: Vec<RouteMeta>,
    /// All background jobs registered in the application.
    pub jobs: Vec<JobMeta>,
}

/// URL slug generation helpers.
pub mod slug {
    /// Convert arbitrary text into a lowercase, hyphen-separated URL slug.
    ///
    /// Keeps ASCII alphanumeric characters, collapses separator runs into a single `-`,
    /// trims leading and trailing hyphens, and returns `"-"` if no alphanumeric characters remain.
    #[must_use]
    pub fn slugify(input: &str) -> String {
        let mut out = String::with_capacity(input.len());
        let mut prev_hyphen = true;
        for ch in input.chars() {
            if ch.is_ascii_alphanumeric() {
                out.push(ch.to_ascii_lowercase());
                prev_hyphen = false;
            } else if !prev_hyphen {
                out.push('-');
                prev_hyphen = true;
            }
        }
        while out.ends_with('-') {
            out.pop();
        }
        if out.is_empty() {
            "-".to_string()
        } else {
            out
        }
    }
}

/// Fractional list positioning helpers for O(1) single-row reordering.
pub mod position {
    /// Compute a fractional `f64` sort score between two optional neighbor positions.
    ///
    /// - `(None, None)` returns `1.0` (first item in an empty list).
    /// - `(Some(prev), None)` returns `prev + 1.0` (append after `prev`).
    /// - `(None, Some(next))` returns `next / 2.0` (prepend before `next`, or `next - 1.0` when `next <= 0.0`).
    /// - `(Some(prev), Some(next))` returns `(prev + next) / 2.0` (insert between `prev` and `next`).
    #[must_use]
    pub fn between(prev: Option<f64>, next: Option<f64>) -> f64 {
        match (prev, next) {
            (None, None) => 1.0,
            (Some(p), None) => p + 1.0,
            (None, Some(n)) => {
                if n > 0.0 {
                    n / 2.0
                } else {
                    n - 1.0
                }
            }
            (Some(p), Some(n)) => f64::midpoint(p, n),
        }
    }
}

/// Compute a lowercase SHA-256 hex digest over NUL-separated string parts.
///
/// Use this for content fingerprints, optimistic concurrency checks (`If-Match`), and cache keys.
#[must_use]
pub fn fingerprint(parts: &[&str]) -> String {
    use sha2::{Digest, Sha256};

    let mut hasher = Sha256::new();
    for (idx, part) in parts.iter().enumerate() {
        if idx > 0 {
            hasher.update([0u8]);
        }
        hasher.update(part.as_bytes());
    }
    hex::encode(hasher.finalize())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn slugify_normalizes_titles_and_fallbacks() {
        assert_eq!(slug::slugify("Hello, World! 2026"), "hello-world-2026");
        assert_eq!(
            slug::slugify("  Rust & SQLite --- WAL  "),
            "rust-sqlite-wal"
        );
        assert_eq!(slug::slugify("!!!"), "-");
    }

    #[test]
    fn position_between_orders_items() {
        assert!((position::between(None, None) - 1.0).abs() < f64::EPSILON);
        assert!((position::between(Some(2.0), None) - 3.0).abs() < f64::EPSILON);
        assert!((position::between(None, Some(1.0)) - 0.5).abs() < f64::EPSILON);
        assert!((position::between(Some(1.0), Some(2.0)) - 1.5).abs() < f64::EPSILON);
    }

    #[test]
    fn fingerprint_distinguishes_part_boundaries() {
        assert_ne!(fingerprint(&["ab", "c"]), fingerprint(&["a", "bc"]));
        assert_eq!(fingerprint(&["a", "b"]).len(), 64);
    }

    #[test]
    fn app_config_debug_redacts_secret_key() {
        let mut config = AppConfig::for_test("demo", PathBuf::from("./tmp"));
        config.secret_key = "super-secret-signing-key".into();
        let rendered = format!("{config:?}");
        assert!(!rendered.contains("super-secret-signing-key"));
        assert!(rendered.contains("<redacted>"));
    }
}