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