use axum::{
extract::{Path, State},
handler::Handler,
http::{header, HeaderValue, StatusCode},
response::{IntoResponse, Response},
routing::{delete, get, patch, post, put, MethodRouter},
Json, Router,
};
use futures_util::future::BoxFuture;
use serde_json::{json, Value};
use slabs_assets::Assets;
use slabs_auth::Auth;
use slabs_cache::Cache;
use slabs_core::{AppConfig, AppManifest, JobMeta, RouteMeta, SlabError, SlabResult};
use slabs_db::{AuditLog, Db};
use slabs_jobs::Jobs;
use slabs_mail::{MailTransport, Mailer};
use slabs_realtime::Realtime;
use slabs_storage::{S3Config, Storage, StorageBackend};
use slabs_webhooks::Webhooks;
use std::collections::{btree_map::Entry, BTreeMap, HashMap};
use std::fmt;
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::watch;
use tower_http::{
compression::CompressionLayer,
cors::CorsLayer,
limit::RequestBodyLimitLayer,
request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer},
set_header::SetResponseHeaderLayer,
trace::TraceLayer,
};
#[derive(Clone, Default)]
struct MakeUlidRequestId;
impl MakeRequestId for MakeUlidRequestId {
fn make_request_id<B>(&mut self, _request: &http::Request<B>) -> Option<RequestId> {
let id = slabs_core::id::new("req");
HeaderValue::from_str(&id).ok().map(RequestId::new)
}
}
#[derive(Debug, Clone, Default)]
pub struct RateLimiter {
buckets: Arc<Mutex<HashMap<String, (u64, Instant)>>>,
}
impl RateLimiter {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn check(&self, key: &str, max_requests: u64, window_secs: u64) -> SlabResult<u64> {
let now = Instant::now();
let window = Duration::from_secs(window_secs.max(1));
let mut guard = self.buckets.lock().expect("rate limiter mutex poisoned");
if guard.len() > 10_000 {
guard.retain(|_, (_, expires_at)| *expires_at > now);
}
let entry = guard.entry(key.to_string()).or_insert((0, now + window));
if entry.1 <= now {
entry.0 = 0;
entry.1 = now + window;
}
if entry.0 >= max_requests {
let retry_after = entry.1.saturating_duration_since(now).as_secs().max(1);
return Err(SlabError::too_many_requests(
retry_after,
"rate limit exceeded, please try again shortly",
));
}
entry.0 += 1;
Ok(max_requests - entry.0)
}
}
#[derive(Debug, Clone)]
pub struct AppCtx {
pub config: AppConfig,
pub db: Db,
pub auth: Auth,
pub jobs: Jobs,
pub mail: Mailer,
pub storage: Storage,
pub cache: Cache,
pub realtime: Realtime,
pub webhooks: Webhooks,
pub assets: Assets,
pub rate_limit: RateLimiter,
pub audit: AuditLog,
}
impl AppCtx {
pub async fn connect(config: AppConfig) -> SlabResult<Self> {
let db = Db::connect(&config.database_url).await?;
let auth = Auth::new(db.clone(), config.secret_key.clone(), config.cookie_secure);
let jobs = Jobs::new(db.clone());
let mail = Mailer::with_transport(
db.clone(),
format!("noreply@{}.local", config.app_name),
MailTransport::from_env(),
);
let storage_backend = match S3Config::from_env() {
Some(s3) => StorageBackend::S3(s3),
None => StorageBackend::Local {
root_dir: config.storage_dir.clone(),
},
};
let storage = Storage::with_backend(db.clone(), storage_backend);
let cache = Cache::new(db.clone());
let realtime = Realtime::new();
let webhooks = Webhooks::new(db.clone(), jobs.clone());
let assets = Assets::from_dir(&config.assets_dir);
let rate_limit = RateLimiter::new();
let audit = AuditLog::new(db.clone());
Ok(Self {
config,
db,
auth,
jobs,
mail,
storage,
cache,
realtime,
webhooks,
assets,
rate_limit,
audit,
})
}
}
#[derive(Debug)]
pub struct SlabDef {
pub method: String,
pub path: String,
pub name: String,
pub feature: String,
pub summary: String,
pub input_schema: Option<Value>,
pub output_schema: Option<Value>,
pub router: MethodRouter<AppCtx>,
}
impl SlabDef {
pub fn get<H, T>(path: impl Into<String>, handler: H) -> Self
where
H: Handler<T, AppCtx>,
T: 'static,
{
Self::new("GET", path, get(handler))
}
pub fn post<H, T>(path: impl Into<String>, handler: H) -> Self
where
H: Handler<T, AppCtx>,
T: 'static,
{
Self::new("POST", path, post(handler))
}
pub fn put<H, T>(path: impl Into<String>, handler: H) -> Self
where
H: Handler<T, AppCtx>,
T: 'static,
{
Self::new("PUT", path, put(handler))
}
pub fn patch<H, T>(path: impl Into<String>, handler: H) -> Self
where
H: Handler<T, AppCtx>,
T: 'static,
{
Self::new("PATCH", path, patch(handler))
}
pub fn delete<H, T>(path: impl Into<String>, handler: H) -> Self
where
H: Handler<T, AppCtx>,
T: 'static,
{
Self::new("DELETE", path, delete(handler))
}
fn new(method: &str, path: impl Into<String>, router: MethodRouter<AppCtx>) -> Self {
let path = path.into();
Self {
method: method.to_string(),
name: format!("{method} {path}"),
feature: "default".to_string(),
summary: String::new(),
input_schema: None,
output_schema: None,
path,
router,
}
}
#[must_use]
pub fn name(mut self, name: impl Into<String>) -> Self {
let n = name.into();
if let Some((feat, _)) = n.split_once('.') {
self.feature = feat.to_string();
}
self.name = n;
self
}
#[must_use]
pub fn feature(mut self, feature: impl Into<String>) -> Self {
self.feature = feature.into();
self
}
#[must_use]
pub fn summary(mut self, summary: impl Into<String>) -> Self {
self.summary = summary.into();
self
}
#[must_use]
pub fn input_schema(mut self, schema: Value) -> Self {
self.input_schema = Some(schema);
self
}
#[must_use]
pub fn output_schema(mut self, schema: Value) -> Self {
self.output_schema = Some(schema);
self
}
pub fn meta(&self) -> RouteMeta {
RouteMeta {
name: self.name.clone(),
method: self.method.clone(),
path: self.path.clone(),
summary: self.summary.clone(),
feature: self.feature.clone(),
input_schema: self.input_schema.clone(),
output_schema: self.output_schema.clone(),
}
}
}
pub type JobHandlerFn =
Arc<dyn Fn(AppCtx, Value) -> BoxFuture<'static, SlabResult<()>> + Send + Sync>;
#[derive(Clone)]
pub struct JobDef {
pub name: String,
pub queue: String,
pub max_attempts: i64,
pub summary: String,
pub handler: JobHandlerFn,
}
impl fmt::Debug for JobDef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("JobDef")
.field("name", &self.name)
.field("queue", &self.queue)
.field("max_attempts", &self.max_attempts)
.field("summary", &self.summary)
.field("handler", &"<fn>")
.finish()
}
}
impl JobDef {
#[must_use]
pub fn new<F, Fut>(name: impl Into<String>, handler: F) -> Self
where
F: Fn(AppCtx, Value) -> Fut + Send + Sync + 'static,
Fut: Future<Output = SlabResult<()>> + Send + 'static,
{
Self {
name: name.into(),
queue: "default".to_string(),
max_attempts: 5,
summary: String::new(),
handler: Arc::new(move |ctx, payload| Box::pin(handler(ctx, payload))),
}
}
#[must_use]
pub fn queue(mut self, queue: impl Into<String>) -> Self {
self.queue = queue.into();
self
}
#[must_use]
pub fn max_attempts(mut self, attempts: i64) -> Self {
self.max_attempts = attempts;
self
}
#[must_use]
pub fn summary(mut self, summary: impl Into<String>) -> Self {
self.summary = summary.into();
self
}
pub fn meta(&self) -> JobMeta {
JobMeta {
name: self.name.clone(),
queue: self.queue.clone(),
max_attempts: self.max_attempts,
summary: self.summary.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct ScheduleDef {
pub job_name: String,
pub every: Duration,
pub payload: Value,
}
impl ScheduleDef {
#[must_use]
pub fn every(every: Duration, job_name: impl Into<String>, payload: Value) -> Self {
Self {
job_name: job_name.into(),
every,
payload,
}
}
}
#[derive(Debug, Clone)]
pub struct JobRegistry {
handlers: Arc<HashMap<String, JobDef>>,
}
impl JobRegistry {
#[must_use]
pub fn new(jobs: Vec<JobDef>) -> Self {
let mut map = HashMap::new();
map.insert(
"slabs.deliver_webhook".to_string(),
JobDef::new("slabs.deliver_webhook", default_deliver_webhook)
.queue("webhooks")
.summary("Built-in webhook delivery handler"),
);
for job in jobs {
map.insert(job.name.clone(), job);
}
Self {
handlers: Arc::new(map),
}
}
pub async fn run_now(&self, ctx: &AppCtx, job_name: &str, payload: Value) -> SlabResult<()> {
let def = self
.handlers
.get(job_name)
.ok_or_else(|| SlabError::not_found(format!("no job handler `{job_name}`")))?;
(def.handler)(ctx.clone(), payload).await
}
pub async fn run_next(&self, ctx: &AppCtx) -> SlabResult<bool> {
let Some(record) = ctx.jobs.claim_next().await? else {
return Ok(false);
};
let Some(def) = self.handlers.get(&record.job_name) else {
let msg = format!("no job handler registered for `{}`", record.job_name);
ctx.jobs.mark_failed(&record, &msg).await?;
return Ok(true);
};
let payload: Value = serde_json::from_str(&record.payload_json)
.map_err(|e| SlabError::internal(format!("invalid job json: {e}")))?;
match (def.handler)(ctx.clone(), payload).await {
Ok(()) => {
ctx.jobs.mark_done(&record.id).await?;
}
Err(err) => {
tracing::warn!(job_id = %record.id, job_name = %record.job_name, error = %err, "job execution failed");
ctx.jobs.mark_failed(&record, &err.to_string()).await?;
}
}
Ok(true)
}
pub async fn drain_ready(&self, ctx: &AppCtx) -> SlabResult<usize> {
let mut processed = 0;
while self.run_next(ctx).await? {
processed += 1;
}
Ok(processed)
}
pub fn spawn_workers(&self, ctx: &AppCtx) {
let (_tx, rx) = watch::channel(false);
self.spawn_workers_with_shutdown(ctx, &rx);
}
pub fn spawn_workers_with_shutdown(&self, ctx: &AppCtx, shutdown: &watch::Receiver<bool>) {
let concurrency = ctx.config.job_concurrency.max(1);
let poll_ms = ctx.config.job_poll_interval_ms.max(50);
for worker_idx in 0..concurrency {
let registry = self.clone();
let worker_ctx = ctx.clone();
let mut rx = shutdown.clone();
tokio::spawn(async move {
loop {
if *rx.borrow() {
break;
}
match registry.run_next(&worker_ctx).await {
Ok(true) => {}
Ok(false) => {
tokio::select! {
() = tokio::time::sleep(Duration::from_millis(poll_ms)) => {},
_ = rx.changed() => { break; }
}
}
Err(err) => {
tracing::error!(worker = worker_idx, error = %err, "job worker error");
tokio::select! {
() = tokio::time::sleep(Duration::from_secs(1)) => {},
_ = rx.changed() => { break; }
}
}
}
}
tracing::debug!(worker = worker_idx, "job worker shut down cleanly");
});
}
}
pub fn spawn_schedules(&self, ctx: &AppCtx, schedules: Vec<ScheduleDef>) {
let (_tx, rx) = watch::channel(false);
self.spawn_schedules_with_shutdown(ctx, schedules, &rx);
}
pub fn spawn_schedules_with_shutdown(
&self,
ctx: &AppCtx,
schedules: Vec<ScheduleDef>,
shutdown: &watch::Receiver<bool>,
) {
for schedule in schedules {
let sched_ctx = ctx.clone();
let mut rx = shutdown.clone();
tokio::spawn(async move {
let mut ticker = tokio::time::interval(schedule.every);
ticker.tick().await;
loop {
tokio::select! {
_ = ticker.tick() => {
if let Err(err) = sched_ctx
.jobs
.enqueue(&schedule.job_name, schedule.payload.clone())
.await
{
tracing::error!(
job = %schedule.job_name,
error = %err,
"failed to enqueue scheduled job"
);
}
}
_ = rx.changed() => {
break;
}
}
}
});
}
}
}
async fn default_deliver_webhook(ctx: AppCtx, payload: Value) -> SlabResult<()> {
let delivery_id = payload
.get("delivery_id")
.and_then(|v| v.as_str())
.ok_or_else(|| SlabError::bad_request("missing delivery_id"))?;
if ctx.config.webhooks_live {
ctx.webhooks
.deliver_http(delivery_id, ctx.config.webhooks_allow_local)
.await?;
} else {
ctx.webhooks.mark_delivered(delivery_id, 200).await?;
}
Ok(())
}
pub fn build_router(ctx: AppCtx, slabs: Vec<SlabDef>, jobs: &[JobDef]) -> Router {
let manifest = Arc::new(AppManifest {
app_name: ctx.config.app_name.clone(),
routes: slabs.iter().map(SlabDef::meta).collect(),
jobs: jobs.iter().map(JobDef::meta).collect(),
});
let mut grouped: BTreeMap<String, MethodRouter<AppCtx>> = BTreeMap::new();
for slab in slabs {
match grouped.entry(slab.path) {
Entry::Occupied(mut existing) => {
let taken = std::mem::take(existing.get_mut());
*existing.get_mut() = taken.merge(slab.router);
}
Entry::Vacant(slot) => {
slot.insert(slab.router);
}
}
}
let mut router: Router<AppCtx> = Router::new();
for (path, method_router) in grouped {
router = router.route(&path, method_router);
}
let openapi_manifest = manifest.clone();
router = router
.route("/_slabs/health", get(health_handler))
.route(
"/_slabs/manifest",
get(move || {
let m = manifest.clone();
async move { Json((*m).clone()) }
}),
)
.route(
"/_slabs/openapi.json",
get(move || {
let m = openapi_manifest.clone();
async move { Json(m.to_openapi_3_1()) }
}),
)
.route("/_slabs/mail", get(dev_mail_outbox_handler))
.route("/_slabs/vendor/basecoat.min.css", get(vendor_basecoat_css))
.route("/_slabs/vendor/basecoat.min.js", get(vendor_basecoat_js))
.route("/_slabs/vendor/htmx.min.js", get(vendor_htmx_js))
.route("/_slabs/vendor/htmx-ext-sse.js", get(vendor_htmx_sse_js))
.route(
"/_slabs/vendor/idiomorph-ext.min.js",
get(vendor_idiomorph_js),
)
.route("/_slabs/vendor/alpine.min.js", get(vendor_alpine_js))
.route("/assets/{hash}/{*path}", get(serve_asset_handler));
let x_request_id = header::HeaderName::from_static("x-request-id");
router
.with_state(ctx)
.layer(CompressionLayer::new())
.layer(RequestBodyLimitLayer::new(25 * 1024 * 1024))
.layer(SetResponseHeaderLayer::if_not_present(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
))
.layer(SetResponseHeaderLayer::if_not_present(
header::X_FRAME_OPTIONS,
HeaderValue::from_static("SAMEORIGIN"),
))
.layer(CorsLayer::permissive())
.layer(PropagateRequestIdLayer::new(x_request_id.clone()))
.layer(TraceLayer::new_for_http())
.layer(SetRequestIdLayer::new(x_request_id, MakeUlidRequestId))
}
async fn health_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
ctx.db.ping().await?;
Ok(Json(json!({
"status": "ok",
"app": ctx.config.app_name,
})))
}
async fn dev_mail_outbox_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
let sent = ctx.mail.list_sent(50).await?;
Ok(Json(json!({ "emails": sent })))
}
fn vendor_response(content_type: &'static str, body: &'static str) -> Response {
(
StatusCode::OK,
[
(header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=86400"),
),
],
body,
)
.into_response()
}
async fn vendor_basecoat_css() -> Response {
vendor_response(
"text/css; charset=utf-8",
include_str!("../assets/vendor/basecoat.min.css"),
)
}
async fn vendor_basecoat_js() -> Response {
vendor_response(
"text/javascript; charset=utf-8",
include_str!("../assets/vendor/basecoat.min.js"),
)
}
async fn vendor_htmx_js() -> Response {
vendor_response(
"text/javascript; charset=utf-8",
include_str!("../assets/vendor/htmx.min.js"),
)
}
async fn vendor_htmx_sse_js() -> Response {
vendor_response(
"text/javascript; charset=utf-8",
include_str!("../assets/vendor/htmx-ext-sse.js"),
)
}
async fn vendor_idiomorph_js() -> Response {
vendor_response(
"text/javascript; charset=utf-8",
include_str!("../assets/vendor/idiomorph-ext.min.js"),
)
}
async fn vendor_alpine_js() -> Response {
vendor_response(
"text/javascript; charset=utf-8",
include_str!("../assets/vendor/alpine.min.js"),
)
}
async fn serve_asset_handler(
State(ctx): State<AppCtx>,
Path((hash, path)): Path<(String, String)>,
) -> SlabResult<Response> {
let Some(entry) = ctx.assets.get(&hash, &path) else {
return Err(SlabError::not_found("asset not found"));
};
let ct = HeaderValue::from_str(&entry.content_type)
.unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
Ok((
StatusCode::OK,
[
(header::CONTENT_TYPE, ct),
(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=31536000, immutable"),
),
],
entry.bytes.clone(),
)
.into_response())
}