1use axum::{
60 extract::{Path, State},
61 handler::Handler,
62 http::{header, HeaderValue, StatusCode},
63 response::{IntoResponse, Response},
64 routing::{delete, get, patch, post, put, MethodRouter},
65 Json, Router,
66};
67use futures_util::future::BoxFuture;
68use serde_json::{json, Value};
69use slabs_assets::Assets;
70use slabs_auth::Auth;
71use slabs_cache::Cache;
72use slabs_core::{AppConfig, AppManifest, JobMeta, RouteMeta, SlabError, SlabResult};
73use slabs_db::{AuditLog, Db};
74use slabs_jobs::Jobs;
75use slabs_mail::{MailTransport, Mailer};
76use slabs_realtime::Realtime;
77use slabs_storage::{S3Config, Storage, StorageBackend};
78use slabs_webhooks::Webhooks;
79use std::collections::{btree_map::Entry, BTreeMap, HashMap};
80use std::fmt;
81use std::future::Future;
82use std::sync::{Arc, Mutex};
83use std::time::{Duration, Instant};
84use tokio::sync::watch;
85use tower_http::{
86 compression::CompressionLayer,
87 cors::CorsLayer,
88 limit::RequestBodyLimitLayer,
89 request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer},
90 set_header::SetResponseHeaderLayer,
91 trace::TraceLayer,
92};
93
94#[derive(Clone, Default)]
96struct MakeUlidRequestId;
97
98impl MakeRequestId for MakeUlidRequestId {
99 fn make_request_id<B>(&mut self, _request: &http::Request<B>) -> Option<RequestId> {
100 let id = slabs_core::id::new("req");
101 HeaderValue::from_str(&id).ok().map(RequestId::new)
102 }
103}
104
105#[derive(Debug, Clone, Default)]
107pub struct RateLimiter {
108 buckets: Arc<Mutex<HashMap<String, (u64, Instant)>>>,
109}
110
111impl RateLimiter {
112 #[must_use]
114 pub fn new() -> Self {
115 Self::default()
116 }
117
118 pub fn check(&self, key: &str, max_requests: u64, window_secs: u64) -> SlabResult<u64> {
123 let now = Instant::now();
124 let window = Duration::from_secs(window_secs.max(1));
125 let mut guard = self.buckets.lock().expect("rate limiter mutex poisoned");
126
127 if guard.len() > 10_000 {
129 guard.retain(|_, (_, expires_at)| *expires_at > now);
130 }
131
132 let entry = guard.entry(key.to_string()).or_insert((0, now + window));
133
134 if entry.1 <= now {
135 entry.0 = 0;
136 entry.1 = now + window;
137 }
138
139 if entry.0 >= max_requests {
140 let retry_after = entry.1.saturating_duration_since(now).as_secs().max(1);
141 return Err(SlabError::too_many_requests(
142 retry_after,
143 "rate limit exceeded, please try again shortly",
144 ));
145 }
146
147 entry.0 += 1;
148 Ok(max_requests - entry.0)
149 }
150}
151
152#[derive(Debug, Clone)]
157pub struct AppCtx {
158 pub config: AppConfig,
160 pub db: Db,
162 pub auth: Auth,
164 pub jobs: Jobs,
166 pub mail: Mailer,
168 pub storage: Storage,
170 pub cache: Cache,
172 pub realtime: Realtime,
174 pub webhooks: Webhooks,
176 pub assets: Assets,
178 pub rate_limit: RateLimiter,
180 pub audit: AuditLog,
182}
183
184impl AppCtx {
185 pub async fn connect(config: AppConfig) -> SlabResult<Self> {
187 let db = Db::connect(&config.database_url).await?;
188 let auth = Auth::new(db.clone(), config.secret_key.clone(), config.cookie_secure);
189 let jobs = Jobs::new(db.clone());
190 let mail = Mailer::with_transport(
191 db.clone(),
192 format!("noreply@{}.local", config.app_name),
193 MailTransport::from_env(),
194 );
195 let storage_backend = match S3Config::from_env() {
196 Some(s3) => StorageBackend::S3(s3),
197 None => StorageBackend::Local {
198 root_dir: config.storage_dir.clone(),
199 },
200 };
201 let storage = Storage::with_backend(db.clone(), storage_backend);
202 let cache = Cache::new(db.clone());
203 let realtime = Realtime::new();
204 let webhooks = Webhooks::new(db.clone(), jobs.clone());
205 let assets = Assets::from_dir(&config.assets_dir);
206 let rate_limit = RateLimiter::new();
207 let audit = AuditLog::new(db.clone());
208
209 Ok(Self {
210 config,
211 db,
212 auth,
213 jobs,
214 mail,
215 storage,
216 cache,
217 realtime,
218 webhooks,
219 assets,
220 rate_limit,
221 audit,
222 })
223 }
224}
225
226#[derive(Debug)]
230pub struct SlabDef {
231 pub method: String,
233 pub path: String,
235 pub name: String,
237 pub feature: String,
239 pub summary: String,
241 pub input_schema: Option<Value>,
243 pub output_schema: Option<Value>,
245 pub router: MethodRouter<AppCtx>,
247}
248
249impl SlabDef {
250 pub fn get<H, T>(path: impl Into<String>, handler: H) -> Self
252 where
253 H: Handler<T, AppCtx>,
254 T: 'static,
255 {
256 Self::new("GET", path, get(handler))
257 }
258
259 pub fn post<H, T>(path: impl Into<String>, handler: H) -> Self
261 where
262 H: Handler<T, AppCtx>,
263 T: 'static,
264 {
265 Self::new("POST", path, post(handler))
266 }
267
268 pub fn put<H, T>(path: impl Into<String>, handler: H) -> Self
270 where
271 H: Handler<T, AppCtx>,
272 T: 'static,
273 {
274 Self::new("PUT", path, put(handler))
275 }
276
277 pub fn patch<H, T>(path: impl Into<String>, handler: H) -> Self
279 where
280 H: Handler<T, AppCtx>,
281 T: 'static,
282 {
283 Self::new("PATCH", path, patch(handler))
284 }
285
286 pub fn delete<H, T>(path: impl Into<String>, handler: H) -> Self
288 where
289 H: Handler<T, AppCtx>,
290 T: 'static,
291 {
292 Self::new("DELETE", path, delete(handler))
293 }
294
295 fn new(method: &str, path: impl Into<String>, router: MethodRouter<AppCtx>) -> Self {
296 let path = path.into();
297 Self {
298 method: method.to_string(),
299 name: format!("{method} {path}"),
300 feature: "default".to_string(),
301 summary: String::new(),
302 input_schema: None,
303 output_schema: None,
304 path,
305 router,
306 }
307 }
308
309 #[must_use]
311 pub fn name(mut self, name: impl Into<String>) -> Self {
312 let n = name.into();
313 if let Some((feat, _)) = n.split_once('.') {
314 self.feature = feat.to_string();
315 }
316 self.name = n;
317 self
318 }
319
320 #[must_use]
322 pub fn feature(mut self, feature: impl Into<String>) -> Self {
323 self.feature = feature.into();
324 self
325 }
326
327 #[must_use]
329 pub fn summary(mut self, summary: impl Into<String>) -> Self {
330 self.summary = summary.into();
331 self
332 }
333
334 #[must_use]
336 pub fn input_schema(mut self, schema: Value) -> Self {
337 self.input_schema = Some(schema);
338 self
339 }
340
341 #[must_use]
343 pub fn output_schema(mut self, schema: Value) -> Self {
344 self.output_schema = Some(schema);
345 self
346 }
347
348 pub fn meta(&self) -> RouteMeta {
350 RouteMeta {
351 name: self.name.clone(),
352 method: self.method.clone(),
353 path: self.path.clone(),
354 summary: self.summary.clone(),
355 feature: self.feature.clone(),
356 input_schema: self.input_schema.clone(),
357 output_schema: self.output_schema.clone(),
358 }
359 }
360}
361
362pub type JobHandlerFn =
364 Arc<dyn Fn(AppCtx, Value) -> BoxFuture<'static, SlabResult<()>> + Send + Sync>;
365
366#[derive(Clone)]
368pub struct JobDef {
369 pub name: String,
371 pub queue: String,
373 pub max_attempts: i64,
375 pub summary: String,
377 pub handler: JobHandlerFn,
379}
380
381impl fmt::Debug for JobDef {
382 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383 f.debug_struct("JobDef")
384 .field("name", &self.name)
385 .field("queue", &self.queue)
386 .field("max_attempts", &self.max_attempts)
387 .field("summary", &self.summary)
388 .field("handler", &"<fn>")
389 .finish()
390 }
391}
392
393impl JobDef {
394 #[must_use]
396 pub fn new<F, Fut>(name: impl Into<String>, handler: F) -> Self
397 where
398 F: Fn(AppCtx, Value) -> Fut + Send + Sync + 'static,
399 Fut: Future<Output = SlabResult<()>> + Send + 'static,
400 {
401 Self {
402 name: name.into(),
403 queue: "default".to_string(),
404 max_attempts: 5,
405 summary: String::new(),
406 handler: Arc::new(move |ctx, payload| Box::pin(handler(ctx, payload))),
407 }
408 }
409
410 #[must_use]
412 pub fn queue(mut self, queue: impl Into<String>) -> Self {
413 self.queue = queue.into();
414 self
415 }
416
417 #[must_use]
419 pub fn max_attempts(mut self, attempts: i64) -> Self {
420 self.max_attempts = attempts;
421 self
422 }
423
424 #[must_use]
426 pub fn summary(mut self, summary: impl Into<String>) -> Self {
427 self.summary = summary.into();
428 self
429 }
430
431 pub fn meta(&self) -> JobMeta {
433 JobMeta {
434 name: self.name.clone(),
435 queue: self.queue.clone(),
436 max_attempts: self.max_attempts,
437 summary: self.summary.clone(),
438 }
439 }
440}
441
442#[derive(Debug, Clone)]
444pub struct ScheduleDef {
445 pub job_name: String,
447 pub every: Duration,
449 pub payload: Value,
451}
452
453impl ScheduleDef {
454 #[must_use]
456 pub fn every(every: Duration, job_name: impl Into<String>, payload: Value) -> Self {
457 Self {
458 job_name: job_name.into(),
459 every,
460 payload,
461 }
462 }
463}
464
465#[derive(Debug, Clone)]
467pub struct JobRegistry {
468 handlers: Arc<HashMap<String, JobDef>>,
469}
470
471impl JobRegistry {
472 #[must_use]
474 pub fn new(jobs: Vec<JobDef>) -> Self {
475 let mut map = HashMap::new();
476 map.insert(
478 "slabs.deliver_webhook".to_string(),
479 JobDef::new("slabs.deliver_webhook", default_deliver_webhook)
480 .queue("webhooks")
481 .summary("Built-in webhook delivery handler"),
482 );
483 for job in jobs {
484 map.insert(job.name.clone(), job);
485 }
486 Self {
487 handlers: Arc::new(map),
488 }
489 }
490
491 pub async fn run_now(&self, ctx: &AppCtx, job_name: &str, payload: Value) -> SlabResult<()> {
493 let def = self
494 .handlers
495 .get(job_name)
496 .ok_or_else(|| SlabError::not_found(format!("no job handler `{job_name}`")))?;
497 (def.handler)(ctx.clone(), payload).await
498 }
499
500 pub async fn run_next(&self, ctx: &AppCtx) -> SlabResult<bool> {
502 let Some(record) = ctx.jobs.claim_next().await? else {
503 return Ok(false);
504 };
505
506 let Some(def) = self.handlers.get(&record.job_name) else {
507 let msg = format!("no job handler registered for `{}`", record.job_name);
508 ctx.jobs.mark_failed(&record, &msg).await?;
509 return Ok(true);
510 };
511
512 let payload: Value = serde_json::from_str(&record.payload_json)
513 .map_err(|e| SlabError::internal(format!("invalid job json: {e}")))?;
514
515 match (def.handler)(ctx.clone(), payload).await {
516 Ok(()) => {
517 ctx.jobs.mark_done(&record.id).await?;
518 }
519 Err(err) => {
520 tracing::warn!(job_id = %record.id, job_name = %record.job_name, error = %err, "job execution failed");
521 ctx.jobs.mark_failed(&record, &err.to_string()).await?;
522 }
523 }
524
525 Ok(true)
526 }
527
528 pub async fn drain_ready(&self, ctx: &AppCtx) -> SlabResult<usize> {
530 let mut processed = 0;
531 while self.run_next(ctx).await? {
532 processed += 1;
533 }
534 Ok(processed)
535 }
536
537 pub fn spawn_workers(&self, ctx: &AppCtx) {
539 let (_tx, rx) = watch::channel(false);
540 self.spawn_workers_with_shutdown(ctx, &rx);
541 }
542
543 pub fn spawn_workers_with_shutdown(&self, ctx: &AppCtx, shutdown: &watch::Receiver<bool>) {
545 let concurrency = ctx.config.job_concurrency.max(1);
546 let poll_ms = ctx.config.job_poll_interval_ms.max(50);
547
548 for worker_idx in 0..concurrency {
549 let registry = self.clone();
550 let worker_ctx = ctx.clone();
551 let mut rx = shutdown.clone();
552 tokio::spawn(async move {
553 loop {
554 if *rx.borrow() {
555 break;
556 }
557 match registry.run_next(&worker_ctx).await {
558 Ok(true) => {}
559 Ok(false) => {
560 tokio::select! {
561 () = tokio::time::sleep(Duration::from_millis(poll_ms)) => {},
562 _ = rx.changed() => { break; }
563 }
564 }
565 Err(err) => {
566 tracing::error!(worker = worker_idx, error = %err, "job worker error");
567 tokio::select! {
568 () = tokio::time::sleep(Duration::from_secs(1)) => {},
569 _ = rx.changed() => { break; }
570 }
571 }
572 }
573 }
574 tracing::debug!(worker = worker_idx, "job worker shut down cleanly");
575 });
576 }
577 }
578
579 pub fn spawn_schedules(&self, ctx: &AppCtx, schedules: Vec<ScheduleDef>) {
581 let (_tx, rx) = watch::channel(false);
582 self.spawn_schedules_with_shutdown(ctx, schedules, &rx);
583 }
584
585 pub fn spawn_schedules_with_shutdown(
587 &self,
588 ctx: &AppCtx,
589 schedules: Vec<ScheduleDef>,
590 shutdown: &watch::Receiver<bool>,
591 ) {
592 for schedule in schedules {
593 let sched_ctx = ctx.clone();
594 let mut rx = shutdown.clone();
595 tokio::spawn(async move {
596 let mut ticker = tokio::time::interval(schedule.every);
597 ticker.tick().await;
598 loop {
599 tokio::select! {
600 _ = ticker.tick() => {
601 if let Err(err) = sched_ctx
602 .jobs
603 .enqueue(&schedule.job_name, schedule.payload.clone())
604 .await
605 {
606 tracing::error!(
607 job = %schedule.job_name,
608 error = %err,
609 "failed to enqueue scheduled job"
610 );
611 }
612 }
613 _ = rx.changed() => {
614 break;
615 }
616 }
617 }
618 });
619 }
620 }
621}
622
623async fn default_deliver_webhook(ctx: AppCtx, payload: Value) -> SlabResult<()> {
624 let delivery_id = payload
625 .get("delivery_id")
626 .and_then(|v| v.as_str())
627 .ok_or_else(|| SlabError::bad_request("missing delivery_id"))?;
628 if ctx.config.webhooks_live {
629 ctx.webhooks
630 .deliver_http(delivery_id, ctx.config.webhooks_allow_local)
631 .await?;
632 } else {
633 ctx.webhooks.mark_delivered(delivery_id, 200).await?;
635 }
636 Ok(())
637}
638
639pub fn build_router(ctx: AppCtx, slabs: Vec<SlabDef>, jobs: &[JobDef]) -> Router {
645 let manifest = Arc::new(AppManifest {
646 app_name: ctx.config.app_name.clone(),
647 routes: slabs.iter().map(SlabDef::meta).collect(),
648 jobs: jobs.iter().map(JobDef::meta).collect(),
649 });
650
651 let mut grouped: BTreeMap<String, MethodRouter<AppCtx>> = BTreeMap::new();
652 for slab in slabs {
653 match grouped.entry(slab.path) {
654 Entry::Occupied(mut existing) => {
655 let taken = std::mem::take(existing.get_mut());
656 *existing.get_mut() = taken.merge(slab.router);
657 }
658 Entry::Vacant(slot) => {
659 slot.insert(slab.router);
660 }
661 }
662 }
663
664 let mut router: Router<AppCtx> = Router::new();
665 for (path, method_router) in grouped {
666 router = router.route(&path, method_router);
667 }
668
669 let openapi_manifest = manifest.clone();
670 router = router
671 .route("/_slabs/health", get(health_handler))
672 .route(
673 "/_slabs/manifest",
674 get(move || {
675 let m = manifest.clone();
676 async move { Json((*m).clone()) }
677 }),
678 )
679 .route(
680 "/_slabs/openapi.json",
681 get(move || {
682 let m = openapi_manifest.clone();
683 async move { Json(m.to_openapi_3_1()) }
684 }),
685 )
686 .route("/_slabs/mail", get(dev_mail_outbox_handler))
687 .route("/_slabs/vendor/basecoat.min.css", get(vendor_basecoat_css))
688 .route("/_slabs/vendor/basecoat.min.js", get(vendor_basecoat_js))
689 .route("/_slabs/vendor/htmx.min.js", get(vendor_htmx_js))
690 .route("/_slabs/vendor/htmx-ext-sse.js", get(vendor_htmx_sse_js))
691 .route(
692 "/_slabs/vendor/idiomorph-ext.min.js",
693 get(vendor_idiomorph_js),
694 )
695 .route("/_slabs/vendor/alpine.min.js", get(vendor_alpine_js))
696 .route("/assets/{hash}/{*path}", get(serve_asset_handler));
697
698 let x_request_id = header::HeaderName::from_static("x-request-id");
699 router
700 .with_state(ctx)
701 .layer(CompressionLayer::new())
702 .layer(RequestBodyLimitLayer::new(25 * 1024 * 1024))
703 .layer(SetResponseHeaderLayer::if_not_present(
704 header::X_CONTENT_TYPE_OPTIONS,
705 HeaderValue::from_static("nosniff"),
706 ))
707 .layer(SetResponseHeaderLayer::if_not_present(
708 header::X_FRAME_OPTIONS,
709 HeaderValue::from_static("SAMEORIGIN"),
710 ))
711 .layer(CorsLayer::permissive())
712 .layer(PropagateRequestIdLayer::new(x_request_id.clone()))
713 .layer(TraceLayer::new_for_http())
714 .layer(SetRequestIdLayer::new(x_request_id, MakeUlidRequestId))
715}
716
717async fn health_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
718 ctx.db.ping().await?;
719 Ok(Json(json!({
720 "status": "ok",
721 "app": ctx.config.app_name,
722 })))
723}
724
725async fn dev_mail_outbox_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
726 let sent = ctx.mail.list_sent(50).await?;
727 Ok(Json(json!({ "emails": sent })))
728}
729
730fn vendor_response(content_type: &'static str, body: &'static str) -> Response {
731 (
732 StatusCode::OK,
733 [
734 (header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
735 (
736 header::CACHE_CONTROL,
737 HeaderValue::from_static("public, max-age=86400"),
738 ),
739 ],
740 body,
741 )
742 .into_response()
743}
744
745async fn vendor_basecoat_css() -> Response {
746 vendor_response(
747 "text/css; charset=utf-8",
748 include_str!("../assets/vendor/basecoat.min.css"),
749 )
750}
751
752async fn vendor_basecoat_js() -> Response {
753 vendor_response(
754 "text/javascript; charset=utf-8",
755 include_str!("../assets/vendor/basecoat.min.js"),
756 )
757}
758
759async fn vendor_htmx_js() -> Response {
760 vendor_response(
761 "text/javascript; charset=utf-8",
762 include_str!("../assets/vendor/htmx.min.js"),
763 )
764}
765
766async fn vendor_htmx_sse_js() -> Response {
767 vendor_response(
768 "text/javascript; charset=utf-8",
769 include_str!("../assets/vendor/htmx-ext-sse.js"),
770 )
771}
772
773async fn vendor_idiomorph_js() -> Response {
774 vendor_response(
775 "text/javascript; charset=utf-8",
776 include_str!("../assets/vendor/idiomorph-ext.min.js"),
777 )
778}
779
780async fn vendor_alpine_js() -> Response {
781 vendor_response(
782 "text/javascript; charset=utf-8",
783 include_str!("../assets/vendor/alpine.min.js"),
784 )
785}
786
787async fn serve_asset_handler(
788 State(ctx): State<AppCtx>,
789 Path((hash, path)): Path<(String, String)>,
790) -> SlabResult<Response> {
791 let Some(entry) = ctx.assets.get(&hash, &path) else {
792 return Err(SlabError::not_found("asset not found"));
793 };
794 let ct = HeaderValue::from_str(&entry.content_type)
795 .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
796 Ok((
797 StatusCode::OK,
798 [
799 (header::CONTENT_TYPE, ct),
800 (
801 header::CACHE_CONTROL,
802 HeaderValue::from_static("public, max-age=31536000, immutable"),
803 ),
804 ],
805 entry.bytes.clone(),
806 )
807 .into_response())
808}