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;
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("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 { .. } => 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()
}
}
pub type SlabResult<T> = Result<T, SlabError>;
#[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,
}
#[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>,
}
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>"));
}
}