use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::BTreeMap;
use std::fmt;
use std::path::PathBuf;
use thiserror::Error;
pub mod id {
use ulid::Ulid;
#[must_use]
pub fn new(prefix: &str) -> String {
format!("{prefix}_{}", Ulid::new().to_string().to_lowercase())
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum SlabError {
#[error("validation failed on `{field}`: {message}")]
Validation {
field: String,
message: String,
},
#[error("validation failed on {} field(s)", .0.len())]
ValidationErrors(BTreeMap<String, Vec<String>>),
#[error("bad request: {0}")]
BadRequest(String),
#[error("unauthorized: {0}")]
Unauthorized(String),
#[error("forbidden: {0}")]
Forbidden(String),
#[error("not found: {0}")]
NotFound(String),
#[error("conflict: {0}")]
Conflict(String),
#[error("too many requests: {message} (retry after {retry_after_secs}s)")]
TooManyRequests {
retry_after_secs: u64,
message: String,
},
#[error("database error: {0}")]
Database(#[from] sqlx::Error),
#[error("internal error: {0}")]
Internal(String),
}
impl SlabError {
#[must_use]
pub fn validation(field: impl Into<String>, message: impl Into<String>) -> Self {
Self::Validation {
field: field.into(),
message: message.into(),
}
}
#[must_use]
pub fn bad_request(msg: impl Into<String>) -> Self {
Self::BadRequest(msg.into())
}
#[must_use]
pub fn unauthorized(msg: impl Into<String>) -> Self {
Self::Unauthorized(msg.into())
}
#[must_use]
pub fn forbidden(msg: impl Into<String>) -> Self {
Self::Forbidden(msg.into())
}
#[must_use]
pub fn not_found(msg: impl Into<String>) -> Self {
Self::NotFound(msg.into())
}
#[must_use]
pub fn conflict(msg: impl Into<String>) -> Self {
Self::Conflict(msg.into())
}
#[must_use]
pub fn too_many_requests(retry_after_secs: u64, msg: impl Into<String>) -> Self {
Self::TooManyRequests {
retry_after_secs,
message: msg.into(),
}
}
#[must_use]
pub fn internal(msg: impl Into<String>) -> Self {
Self::Internal(msg.into())
}
#[must_use]
pub fn status_code(&self) -> StatusCode {
match self {
Self::Validation { .. } | Self::ValidationErrors(_) => 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::ValidationErrors(fields) => json!({
"error": "validation_error",
"fields": fields,
}),
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()
}
}
pub type SlabResult<T> = Result<T, SlabError>;
#[derive(Debug, Clone, Default)]
pub struct Validate {
errors: BTreeMap<String, Vec<String>>,
}
impl Validate {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn required(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
if value.trim().is_empty() {
self.push(field, "is required");
}
self
}
pub fn min_len(&mut self, field: impl Into<String>, value: &str, min: usize) -> &mut Self {
if value.trim().chars().count() < min {
self.push(field, format!("must be at least {min} characters"));
}
self
}
pub fn max_len(&mut self, field: impl Into<String>, value: &str, max: usize) -> &mut Self {
if value.trim().chars().count() > max {
self.push(field, format!("must be at most {max} characters"));
}
self
}
pub fn email(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
let trimmed = value.trim();
let valid = !trimmed.is_empty()
&& !trimmed.chars().any(char::is_whitespace)
&& trimmed.split_once('@').is_some_and(|(local, domain)| {
!local.is_empty()
&& !domain.is_empty()
&& !domain.contains('@')
&& domain.contains('.')
&& !domain.starts_with('.')
&& !domain.ends_with('.')
});
if !valid {
self.push(field, "must be a valid email address");
}
self
}
pub fn url(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
let trimmed = value.trim();
let valid = !trimmed.chars().any(char::is_whitespace)
&& ((trimmed.starts_with("http://") && trimmed.len() > "http://".len())
|| (trimmed.starts_with("https://") && trimmed.len() > "https://".len()));
if !valid {
self.push(field, "must start with http:// or https://");
}
self
}
pub fn one_of(&mut self, field: impl Into<String>, value: &str, allowed: &[&str]) -> &mut Self {
if !allowed.contains(&value) {
self.push(field, format!("must be one of: {}", allowed.join(", ")));
}
self
}
pub fn check(
&mut self,
field: impl Into<String>,
condition: bool,
message: impl Into<String>,
) -> &mut Self {
if !condition {
self.push(field, message);
}
self
}
pub fn push(&mut self, field: impl Into<String>, message: impl Into<String>) -> &mut Self {
self.errors
.entry(field.into())
.or_default()
.push(message.into());
self
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.errors.is_empty()
}
#[must_use]
pub fn errors(&self) -> &BTreeMap<String, Vec<String>> {
&self.errors
}
pub fn finish(self) -> SlabResult<()> {
if self.errors.is_empty() {
Ok(())
} else {
Err(SlabError::ValidationErrors(self.errors))
}
}
}
#[derive(Clone, Serialize, Deserialize)]
pub struct AppConfig {
pub app_name: String,
pub bind_addr: String,
pub database_url: String,
pub secret_key: String,
pub storage_dir: PathBuf,
pub assets_dir: PathBuf,
pub job_poll_interval_ms: u64,
pub job_concurrency: usize,
pub cookie_secure: bool,
pub webhooks_live: bool,
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 {
#[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")),
}
}
#[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,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteMeta {
pub name: String,
pub method: String,
pub path: String,
pub summary: String,
pub feature: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub input_schema: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output_schema: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobMeta {
pub name: String,
pub queue: String,
pub max_attempts: i64,
pub summary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppManifest {
pub app_name: String,
pub routes: Vec<RouteMeta>,
pub jobs: Vec<JobMeta>,
}
impl AppManifest {
#[must_use]
pub fn to_openapi_3_1(&self) -> serde_json::Value {
let mut paths = serde_json::Map::new();
for route in &self.routes {
let mut parameters = Vec::new();
let mut normalized_segments = Vec::new();
for segment in route.path.split('/') {
if let Some(inner) = segment.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
let param_name = inner.strip_prefix('*').unwrap_or(inner);
if !param_name.is_empty() {
parameters.push(json!({
"name": param_name,
"in": "path",
"required": true,
"schema": { "type": "string" },
}));
normalized_segments.push(format!("{{{param_name}}}"));
continue;
}
}
normalized_segments.push(segment.to_string());
}
let openapi_path = normalized_segments.join("/");
let method_key = route.method.to_ascii_lowercase();
let mut operation = serde_json::Map::new();
operation.insert("operationId".into(), json!(route.name));
operation.insert("summary".into(), json!(route.summary));
if !route.feature.is_empty() {
operation.insert("tags".into(), json!([route.feature]));
}
if !parameters.is_empty() {
operation.insert("parameters".into(), serde_json::Value::Array(parameters));
}
if let Some(input_schema) = &route.input_schema {
operation.insert(
"requestBody".into(),
json!({
"required": true,
"content": {
"application/json": {
"schema": input_schema,
}
}
}),
);
}
let ok_response = if let Some(output_schema) = &route.output_schema {
json!({
"description": "Success",
"content": {
"application/json": {
"schema": output_schema,
}
}
})
} else {
json!({
"description": "Success",
})
};
operation.insert("responses".into(), json!({ "200": ok_response }));
let path_item = paths
.entry(openapi_path)
.or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
if let Some(path_obj) = path_item.as_object_mut() {
path_obj.insert(method_key, serde_json::Value::Object(operation));
}
}
json!({
"openapi": "3.1.0",
"info": {
"title": self.app_name,
"version": "0.1.0",
},
"paths": serde_json::Value::Object(paths),
})
}
}
pub mod slug {
#[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
}
}
}
pub mod position {
#[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),
}
}
}
#[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>"));
}
#[test]
fn validate_builder_succeeds_for_valid_inputs() {
let mut v = Validate::new();
v.required("name", " Alice ")
.min_len("name", " Alice ", 3)
.max_len("name", " Alice ", 10)
.email("email", " alice@example.com ")
.url("website", "https://example.com/docs")
.one_of("role", "admin", &["member", "admin"])
.check("age", true, "must be adult");
assert!(v.is_empty());
assert!(v.errors().is_empty());
assert!(v.finish().is_ok());
}
#[test]
fn validate_builder_collects_all_field_errors_and_maps_to_422() {
let mut v = Validate::new();
v.required("title", " ")
.min_len("title", "hi", 3)
.max_len("bio", "123456", 5)
.email("email", "not-an-email")
.url("website", "ftp://example.com")
.one_of("role", "owner", &["member", "admin"])
.check("terms", false, "must accept terms")
.push("custom", "extra problem");
assert!(!v.is_empty());
assert_eq!(v.errors()["title"].len(), 2);
assert_eq!(v.errors()["title"][0], "is required");
assert!(v.errors().contains_key("bio"));
assert!(v.errors().contains_key("email"));
assert!(v.errors().contains_key("website"));
assert!(v.errors().contains_key("role"));
assert_eq!(v.errors()["terms"], vec!["must accept terms"]);
assert_eq!(v.errors()["custom"], vec!["extra problem"]);
let err = v.finish().unwrap_err();
assert_eq!(err.status_code(), StatusCode::UNPROCESSABLE_ENTITY);
let response = err.into_response();
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[test]
fn validate_checks_unicode_char_lengths_and_email_url_edge_cases() {
let mut v = Validate::new();
v.min_len("label", "café!", 5)
.max_len("label", "café!", 5)
.email("bad_at", "@example.com")
.email("bad_dot", "alice@localhost")
.email("bad_trail", "alice@example.")
.url("bare_scheme", "https://")
.url("http_ok", "http://localhost:3000");
assert!(!v.errors().contains_key("label"));
assert!(v.errors().contains_key("bad_at"));
assert!(v.errors().contains_key("bad_dot"));
assert!(v.errors().contains_key("bad_trail"));
assert!(v.errors().contains_key("bare_scheme"));
assert!(!v.errors().contains_key("http_ok"));
}
#[test]
fn app_manifest_to_openapi_3_1_builds_paths_params_and_schemas() {
let manifest = AppManifest {
app_name: "campfire".into(),
routes: vec![
RouteMeta {
name: "rooms::list_rooms".into(),
method: "GET".into(),
path: "/api/rooms".into(),
summary: "List all rooms".into(),
feature: "rooms".into(),
input_schema: None,
output_schema: Some(json!({
"type": "array",
"items": { "type": "object" }
})),
},
RouteMeta {
name: "rooms::create_room".into(),
method: "POST".into(),
path: "/api/rooms".into(),
summary: "Create a room".into(),
feature: "rooms".into(),
input_schema: Some(json!({
"type": "object",
"required": ["name"],
"properties": { "name": { "type": "string" } }
})),
output_schema: Some(json!({
"type": "object",
"properties": { "id": { "type": "string" } }
})),
},
RouteMeta {
name: "messages::get_message".into(),
method: "GET".into(),
path: "/api/rooms/{room_id}/messages/{msg_id}".into(),
summary: "Get one message".into(),
feature: "messages".into(),
input_schema: None,
output_schema: None,
},
RouteMeta {
name: "files::serve_asset".into(),
method: "GET".into(),
path: "/assets/{*filepath}".into(),
summary: "Serve a static asset".into(),
feature: "files".into(),
input_schema: None,
output_schema: None,
},
],
jobs: vec![],
};
let doc = manifest.to_openapi_3_1();
assert_eq!(doc["openapi"], "3.1.0");
assert_eq!(doc["info"]["title"], "campfire");
assert_eq!(doc["info"]["version"], "0.1.0");
assert_eq!(
doc["paths"]["/api/rooms"]["get"]["operationId"],
"rooms::list_rooms"
);
assert!(doc["paths"]["/api/rooms"]["get"]["requestBody"].is_null());
assert_eq!(
doc["paths"]["/api/rooms"]["get"]["responses"]["200"]["content"]["application/json"]
["schema"]["type"],
"array"
);
assert_eq!(
doc["paths"]["/api/rooms"]["post"]["operationId"],
"rooms::create_room"
);
assert_eq!(
doc["paths"]["/api/rooms"]["post"]["requestBody"]["content"]["application/json"]
["schema"]["required"][0],
"name"
);
assert_eq!(
doc["paths"]["/api/rooms"]["post"]["responses"]["200"]["content"]["application/json"]
["schema"]["properties"]["id"]["type"],
"string"
);
let params = doc["paths"]["/api/rooms/{room_id}/messages/{msg_id}"]["get"]["parameters"]
.as_array()
.unwrap();
assert_eq!(params.len(), 2);
assert_eq!(params[0]["name"], "room_id");
assert_eq!(params[0]["in"], "path");
assert_eq!(params[0]["required"], true);
assert_eq!(params[0]["schema"]["type"], "string");
assert_eq!(params[1]["name"], "msg_id");
let wildcard_params = doc["paths"]["/assets/{filepath}"]["get"]["parameters"]
.as_array()
.unwrap();
assert_eq!(wildcard_params.len(), 1);
assert_eq!(wildcard_params[0]["name"], "filepath");
assert_eq!(wildcard_params[0]["in"], "path");
assert_eq!(wildcard_params[0]["required"], true);
}
#[test]
fn route_meta_omits_none_schemas_when_serialized() {
let meta = RouteMeta {
name: "health::check".into(),
method: "GET".into(),
path: "/health".into(),
summary: "Health check".into(),
feature: "health".into(),
input_schema: None,
output_schema: None,
};
let value = serde_json::to_value(&meta).unwrap();
assert!(value.get("input_schema").is_none());
assert!(value.get("output_schema").is_none());
let parsed: RouteMeta = serde_json::from_value(value).unwrap();
assert!(parsed.input_schema.is_none());
assert!(parsed.output_schema.is_none());
}
}