1pub use slabs_assets as assets;
43pub use slabs_auth as auth;
44pub use slabs_cache as cache;
45pub use slabs_core as core;
46pub use slabs_db as db;
47pub use slabs_html as html;
48pub use slabs_http as http;
49pub use slabs_jobs as jobs;
50pub use slabs_mail as mail;
51pub use slabs_realtime as realtime;
52pub use slabs_storage as storage;
53pub use slabs_test as test;
54pub use slabs_webhooks as webhooks;
55
56pub use slabs_core::{
57 fingerprint, id, position, slug, AppConfig, AppEnv, AppManifest, JobMeta, RouteMeta, SlabError,
58 SlabResult, Validate,
59};
60pub use slabs_db::{
61 AuditEntry, AuditLog, CursorPage, IncidentInput, IncidentOutcome, IncidentRecord, Incidents,
62 Pagination,
63};
64pub use slabs_html::{json_script, redirect_external, Flash, FlashKind};
65pub use slabs_http::{
66 build_router, client_ip, AppCtx, ClientIp, JobDef, JobRegistry, RateLimiter, ScheduleDef,
67 SlabDef,
68};
69pub use slabs_realtime::{validate_ws_origin, PresenceEntry, PresenceGuard};
70
71pub mod prelude {
77 pub use slabs_auth::{Principal, Session, SESSION_COOKIE_NAME};
78 pub use slabs_core::{
79 fingerprint, id, position, slug, AppConfig, AppEnv, SlabError, SlabResult, Validate,
80 };
81 pub use slabs_db::{
82 AuditEntry, AuditLog, CursorPage, IncidentInput, IncidentOutcome, IncidentRecord,
83 Incidents, Pagination, QueryBuilder,
84 };
85 pub use slabs_html::{
86 self as html, html as maud, htmx, json_script, redirect_external, Flash, FlashKind, Markup,
87 };
88 pub use slabs_http::{client_ip, AppCtx, ClientIp, JobDef, ScheduleDef, SlabDef};
89 pub use slabs_mail::Email;
90 pub use slabs_realtime::{validate_ws_origin, PresenceEntry, PresenceGuard};
91 pub use slabs_storage::BlobMeta;
92}
93
94#[macro_export]
99macro_rules! discover_slabs {
100 () => {
101 include!(concat!(env!("OUT_DIR"), "/discovered_slabs.rs"));
102 };
103}
104
105#[derive(Debug)]
107pub struct SlabsApp {
108 pub ctx: AppCtx,
110 pub router: axum::Router,
112 pub job_registry: JobRegistry,
114 pub schedules: Vec<ScheduleDef>,
116}
117
118impl SlabsApp {
119 pub async fn boot(
122 config: AppConfig,
123 migrator: &sqlx::migrate::Migrator,
124 slabs: Vec<SlabDef>,
125 jobs: Vec<JobDef>,
126 ) -> SlabResult<Self> {
127 config.validate()?;
128 let ctx = AppCtx::connect(config).await?;
129 ctx.db.migrate(migrator).await?;
130 let router = build_router(ctx.clone(), slabs, &jobs);
131 let job_registry = JobRegistry::new(jobs);
132
133 Ok(Self {
134 ctx,
135 router,
136 job_registry,
137 schedules: Vec::new(),
138 })
139 }
140
141 #[must_use]
143 pub fn with_schedules(mut self, schedules: Vec<ScheduleDef>) -> Self {
144 self.schedules = schedules;
145 self
146 }
147
148 pub async fn serve(self) -> SlabResult<()> {
155 let addr = self.ctx.config.bind_addr.clone();
156 let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
157
158 let mut worker_handles = self
159 .job_registry
160 .spawn_workers_with_shutdown(&self.ctx, &shutdown_rx);
161 if !self.schedules.is_empty() {
162 worker_handles.extend(self.job_registry.spawn_schedules_with_shutdown(
163 &self.ctx,
164 self.schedules,
165 &shutdown_rx,
166 ));
167 }
168
169 let listener = tokio::net::TcpListener::bind(&addr)
170 .await
171 .map_err(|e| SlabError::internal(format!("failed to bind {addr}: {e}")))?;
172
173 tracing::info!(
174 app = %self.ctx.config.app_name,
175 addr = %addr,
176 env = %self.ctx.config.env.as_str(),
177 "slabs server listening"
178 );
179
180 let ctx_for_shutdown = self.ctx.clone();
181 let serve_result = axum::serve(
182 listener,
183 self.router
184 .into_make_service_with_connect_info::<std::net::SocketAddr>(),
185 )
186 .with_graceful_shutdown(shutdown_signal(ctx_for_shutdown, shutdown_tx))
187 .await;
188
189 let drain_workers = async {
190 for handle in worker_handles {
191 let _ = handle.await;
192 }
193 };
194 if tokio::time::timeout(std::time::Duration::from_secs(15), drain_workers)
195 .await
196 .is_err()
197 {
198 tracing::warn!("timed out waiting 15s for background workers to drain");
199 }
200
201 self.ctx.db.checkpoint_and_close().await;
202
203 serve_result.map_err(|e| SlabError::internal(format!("server error: {e}")))
204 }
205}
206
207async fn shutdown_signal(ctx: AppCtx, shutdown_tx: tokio::sync::watch::Sender<bool>) {
208 let ctrl_c = async {
209 let _ = tokio::signal::ctrl_c().await;
210 };
211
212 #[cfg(unix)]
213 let terminate = async {
214 match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
215 Ok(mut sig) => {
216 sig.recv().await;
217 }
218 Err(err) => {
219 tracing::warn!(error = %err, "failed to install SIGTERM handler");
220 std::future::pending::<()>().await;
221 }
222 }
223 };
224
225 #[cfg(not(unix))]
226 let terminate = std::future::pending::<()>();
227
228 tokio::select! {
229 () = ctrl_c => {},
230 () = terminate => {},
231 }
232
233 tracing::info!("shutdown signal received, draining requests and stopping job workers...");
234 ctx.set_draining();
235 let _ = shutdown_tx.send(true);
236}
237
238pub fn init_tracing() {
242 use tracing_subscriber::{fmt, EnvFilter};
243 let filter = EnvFilter::try_from_default_env()
244 .unwrap_or_else(|_| EnvFilter::new("info,tower_http=info,sqlx=warn"));
245
246 let use_json = std::env::var("SLABS_LOG_FORMAT").is_ok_and(|v| v.eq_ignore_ascii_case("json"));
247
248 if use_json {
249 let _ = fmt().json().with_env_filter(filter).try_init();
250 } else {
251 let _ = fmt().with_env_filter(filter).try_init();
252 }
253}