1use crate::{AppConfig, AppContext, AppError, Result, Routes};
2use capy_db::{MigratorTrait, NoMigrations};
3use std::{collections::BTreeMap, marker::PhantomData, path::PathBuf, sync::Arc, time::Duration};
4use tracing_subscriber::EnvFilter;
5
6type OpenApiCustomizer = Arc<dyn Fn(&mut crate::ApiDocument) + Send + Sync>;
7
8pub struct App<M = NoMigrations> {
10 routes: Routes,
11 api_routes: Option<Routes>,
12 frontend: Option<PathBuf>,
13 config: Option<AppConfig>,
14 request_timeouts: BTreeMap<String, Option<Duration>>,
15 observer: crate::diagnostics::Observer,
16 openapi_customizer: Option<OpenApiCustomizer>,
17 #[cfg(feature = "auth")]
18 auth_delivery: Option<Arc<dyn capy_auth::ResetDelivery>>,
19 #[cfg(feature = "jobs")]
20 jobs: Option<capy_jobs::Jobs>,
21 #[cfg(feature = "mail")]
22 mail_enabled: bool,
23 #[cfg(feature = "mail")]
24 mailer: Option<capy_mail::Mailer>,
25 migrations: PhantomData<M>,
26}
27
28impl Default for App {
29 fn default() -> Self {
30 Self::new()
31 }
32}
33
34impl App {
35 pub fn new() -> Self {
37 Self {
38 routes: Routes::new(),
39 api_routes: None,
40 frontend: None,
41 config: None,
42 request_timeouts: BTreeMap::new(),
43 observer: None,
44 openapi_customizer: None,
45 #[cfg(feature = "auth")]
46 auth_delivery: None,
47 #[cfg(feature = "jobs")]
48 jobs: None,
49 #[cfg(feature = "mail")]
50 mail_enabled: false,
51 #[cfg(feature = "mail")]
52 mailer: None,
53 migrations: PhantomData,
54 }
55 }
56}
57
58impl<M: MigratorTrait> App<M> {
59 #[cfg(feature = "mail")]
62 pub fn mail(mut self) -> Self {
63 self.mail_enabled = true;
64 self
65 }
66
67 #[cfg(feature = "mail")]
69 pub fn with_mail(mut self, mailer: capy_mail::Mailer) -> Self {
70 self.mail_enabled = true;
71 self.mailer = Some(mailer);
72 self
73 }
74 #[cfg(feature = "mail")]
75 fn validate_mail(&self, config: &AppConfig) -> Result<()> {
76 if self.mail_enabled {
77 if let Some(mailer) = &self.mailer {
78 mailer.validate_environment(config.app.environment == "production")?;
79 } else {
80 capy_mail::Mailer::validate(config)?;
81 }
82 #[cfg(feature = "jobs")]
83 capy_mail::validate_jobs(self.jobs.clone().unwrap_or_default())?;
84 }
85 Ok(())
86 }
87 #[cfg(feature = "mail")]
88 fn configured_mailer(&self, config: &AppConfig) -> Result<Option<capy_mail::Mailer>> {
89 self.validate_mail(config)?;
90 if !self.mail_enabled {
91 return Ok(None);
92 }
93 self.mailer
94 .clone()
95 .map(Ok)
96 .unwrap_or_else(|| capy_mail::Mailer::from_config(config))
97 .map(Some)
98 }
99
100 #[cfg(feature = "auth")]
103 pub fn auth(mut self, delivery: impl capy_auth::ResetDelivery) -> Self {
104 self.auth_delivery = Some(Arc::new(delivery));
105 self
106 }
107
108 #[cfg(feature = "jobs")]
110 pub fn jobs(mut self, jobs: capy_jobs::Jobs) -> Self {
111 self.jobs = Some(jobs);
112 self
113 }
114
115 pub fn openapi_with(
118 mut self,
119 customize: impl Fn(&mut crate::ApiDocument) + Send + Sync + 'static,
120 ) -> Self {
121 self.openapi_customizer = Some(Arc::new(customize));
122 self
123 }
124
125 pub fn openapi(&self) -> Result<crate::ApiDocument> {
127 let config = self
128 .config
129 .clone()
130 .map(Ok)
131 .unwrap_or_else(AppConfig::load_for_contracts)?;
132 self.api_document(&config)
133 }
134
135 fn api_document(&self, config: &AppConfig) -> Result<crate::ApiDocument> {
136 #[cfg(feature = "mail")]
137 self.validate_mail(config)?;
138 #[cfg(feature = "jobs")]
139 if let Some(jobs) = &self.jobs {
140 jobs.validate()?;
141 }
142 let mut routes = vec![("", &self.routes)];
143 if let Some(api) = &self.api_routes {
144 routes.push(("/api", api));
145 }
146 #[cfg(feature = "auth")]
147 let auth_routes = capy_auth::routes();
148 #[cfg(feature = "auth")]
149 if let Some(delivery) = &self.auth_delivery {
150 let production = config.app.environment == "production";
151 config.auth.validate(production)?;
152 if production && delivery.development_only() {
153 return Err(AppError::Configuration("Install an application-owned password reset delivery adapter before enabling auth in production.".into()));
154 }
155 routes.push(("/api/auth", &auth_routes));
156 }
157 let mut document = crate::ApiDocument::from_routes(
158 config.api.title.as_deref().unwrap_or(&config.app.name),
159 &config.api.version,
160 routes,
161 )?;
162 #[cfg(feature = "auth")]
163 if self.auth_delivery.is_some() {
164 document.as_value_mut()["components"]["securitySchemes"]["session"] = crate::serde_json::json!({
165 "type": "apiKey", "in": "cookie",
166 "name": config.auth.cookie_name(config.app.environment == "production")
167 });
168 if let Some(paths) = document.as_value_mut()["paths"].as_object_mut() {
169 for (path, methods) in paths {
170 if let Some(methods) = methods.as_object_mut() {
171 for (method, operation) in methods {
172 let mutation =
173 matches!(method.as_str(), "post" | "put" | "patch" | "delete");
174 let bootstrap = path == "/api/auth/csrf" && method == "get";
175 if mutation || bootstrap {
176 if operation.get("parameters").is_none() {
177 operation["parameters"] = crate::serde_json::json!([]);
178 }
179 operation["parameters"].as_array_mut().expect("generated parameter array").push(crate::serde_json::json!({
180 "name": if bootstrap { "X-Capy-CSRF" } else { "X-CSRF-Token" },
181 "in": "header", "required": true,
182 "description": if bootstrap { "Send 1 to bootstrap a same-origin CSRF session." } else { "Synchronizer token from GET /api/auth/csrf; never a session secret." },
183 "schema": {"type": "string"}
184 }));
185 operation["responses"]["403"] = crate::serde_json::json!({"description": "CSRF or policy rejection", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ApiErrorResponse"}}}});
186 }
187 }
188 }
189 }
190 }
191 }
192 if let Some(customize) = &self.openapi_customizer {
193 customize(&mut document);
194 }
195 Ok(document)
196 }
197
198 pub fn observe_requests(mut self, observer: impl crate::RequestObserver) -> Self {
200 self.observer = Some(Arc::new(observer));
201 self
202 }
203
204 pub fn request_timeout_for(
208 mut self,
209 route: impl Into<String>,
210 timeout: Option<Duration>,
211 ) -> Self {
212 self.request_timeouts.insert(route.into(), timeout);
213 self
214 }
215
216 pub fn api_routes(mut self, routes: Routes) -> Self {
219 self.api_routes = Some(routes);
220 self
221 }
222
223 pub fn frontend(mut self, directory: impl Into<PathBuf>) -> Self {
227 self.frontend = Some(directory.into());
228 self
229 }
230
231 pub fn routes(mut self, routes: Routes) -> Self {
233 self.routes = routes;
234 self
235 }
236
237 pub fn config(mut self, config: AppConfig) -> Self {
239 self.config = Some(config);
240 self
241 }
242
243 pub fn migrations<N: MigratorTrait>(self, _migrator: N) -> App<N> {
246 App {
247 routes: self.routes,
248 api_routes: self.api_routes,
249 frontend: self.frontend,
250 config: self.config,
251 request_timeouts: self.request_timeouts,
252 observer: self.observer,
253 openapi_customizer: self.openapi_customizer,
254 #[cfg(feature = "auth")]
255 auth_delivery: self.auth_delivery,
256 #[cfg(feature = "jobs")]
257 jobs: self.jobs,
258 #[cfg(feature = "mail")]
259 mail_enabled: self.mail_enabled,
260 #[cfg(feature = "mail")]
261 mailer: self.mailer,
262 migrations: PhantomData,
263 }
264 }
265
266 pub fn into_router(self, context: AppContext) -> axum::Router {
269 #[cfg(feature = "mail")]
270 let mailer = self.configured_mailer(&context.config);
271 let docs_enabled =
272 context.config.api.docs && context.config.app.environment != "production";
273 let schema = (context.config.api.openapi || docs_enabled).then(|| {
274 self.api_document(&context.config)
275 .map(|doc| doc.as_value().clone())
276 });
277 let http = context.config.http.clone();
278 let policy = crate::http_policy::HttpPolicy {
279 default_timeout: (http.request_timeout_seconds != 0)
280 .then(|| Duration::from_secs(http.request_timeout_seconds)),
281 overrides: self.request_timeouts,
282 };
283 let mut router = self.routes.into_router();
284 if let Some(api) = self.api_routes {
285 router = router.nest("/api", api.into_router());
286 }
287 #[cfg(feature = "auth")]
288 let auth = self
289 .auth_delivery
290 .map(|delivery| capy_auth::AuthService::new(context.clone(), delivery));
291 #[cfg(feature = "auth")]
292 if auth.is_some() {
293 router = router.nest("/api/auth", capy_auth::routes().into_router());
294 }
295 if let Some(schema) = schema {
296 let schema = Arc::new(schema.map_err(|error| error.to_string()));
299 router = router.route(
300 "/openapi.json",
301 axum::routing::get(move || {
302 let schema = schema.clone();
303 async move {
304 match schema.as_ref() {
305 Ok(document) => Ok(axum::Json(document.clone())),
306 Err(_) => Err(AppError::Configuration(
307 "Invalid API contract. Run capy openapi to inspect the error."
308 .into(),
309 )),
310 }
311 }
312 }),
313 );
314 }
315 if docs_enabled {
316 router = router.route(
317 "/docs/api",
318 axum::routing::get(|| async {
319 axum::response::Html(include_str!("api_docs.html"))
320 }),
321 );
322 }
323 if let Some(directory) = self.frontend {
324 router =
325 router.fallback(move |request| crate::frontend::serve(directory.clone(), request));
326 }
327 let mut router = router.with_state(context);
328 #[cfg(feature = "mail")]
329 match mailer {
330 Ok(Some(mailer)) => router = router.layer(axum::Extension(mailer)),
331 Ok(None) => {}
332 Err(_) => {
333 router = axum::Router::new().fallback(|| async {
334 AppError::Configuration("Invalid mail configuration. Run capy check.".into())
335 })
336 }
337 }
338
339 #[cfg(feature = "auth")]
340 if let Some(service) = auth {
341 router = match service {
342 Ok(service) => service.protect(router),
343 Err(_) => axum::Router::new().fallback(|| async {
344 AppError::Configuration("Invalid auth configuration. Run capy check.".into())
345 }),
346 };
347 }
348 router = router
350 .layer(axum::extract::DefaultBodyLimit::max(http.max_body_bytes))
351 .layer(axum::middleware::from_fn_with_state(
352 policy,
353 crate::http_policy::deadline,
354 ));
355 if http.compression {
356 router = router.layer(tower_http::compression::CompressionLayer::new());
357 }
358 router
359 .layer(axum::middleware::from_fn_with_state(
360 self.observer,
361 crate::diagnostics::request,
362 ))
363 .layer(
364 tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer::new([
365 axum::http::header::AUTHORIZATION,
366 axum::http::header::COOKIE,
367 axum::http::HeaderName::from_static("x-csrf-token"),
368 ]),
369 )
370 .layer(
371 tower_http::sensitive_headers::SetSensitiveResponseHeadersLayer::new([
372 axum::http::header::SET_COOKIE,
373 ]),
374 )
375 }
376
377 pub async fn run(self) -> Result<()> {
383 let mut args = std::env::args().skip(1);
384 let command = args.next().unwrap_or_else(|| "serve".into());
385 #[cfg(feature = "jobs")]
386 if command.starts_with("queue:") {
387 return self
388 .run_queue_command(&command, &args.collect::<Vec<_>>())
389 .await;
390 }
391 if args.next().is_some() {
392 return Err(AppError::Configuration(
393 "Unexpected arguments. Use the capy CLI for application commands.".into(),
394 ));
395 }
396 self.run_command(&command).await
397 }
398
399 #[cfg(feature = "jobs")]
400 async fn run_queue_command(self, command: &str, args: &[String]) -> Result<()> {
401 let config = self
402 .config
403 .clone()
404 .map(Ok)
405 .unwrap_or_else(AppConfig::load)?;
406 #[cfg(feature = "mail")]
407 let mailer = self.configured_mailer(&config)?;
408 let jobs = self.jobs;
409 #[cfg(feature = "mail")]
410 let jobs = if let Some(mailer) = mailer {
411 Some(capy_mail::register_jobs(jobs.unwrap_or_default(), mailer))
412 } else {
413 jobs
414 };
415 let jobs = jobs.ok_or_else(|| {
416 AppError::Configuration(
417 "Register jobs with App::jobs (capy make:job installs the conventional registry)."
418 .into(),
419 )
420 })?;
421 crate::job_commands::run(command, args, config, jobs).await
422 }
423
424 pub async fn run_command(self, command: &str) -> Result<()> {
426 #[cfg(feature = "jobs")]
427 if command.starts_with("queue:") {
428 return self.run_queue_command(command, &[]).await;
429 }
430 #[cfg(feature = "mail")]
431 if command == "mail:check" {
432 let config = self
433 .config
434 .clone()
435 .map(Ok)
436 .unwrap_or_else(AppConfig::load_for_contracts)?;
437 if !self.mail_enabled {
438 return Err(AppError::Configuration(
439 "Enable mail with App::mail.".into(),
440 ));
441 }
442 self.validate_mail(&config)?;
443 println!("Mail: configuration and compiled templates valid. No DNS, authentication or delivery attempted.");
444 return Ok(());
445 }
446 if command == "__capy_contract" {
447 print!("{}", self.openapi()?.to_json()?);
448 return Ok(());
449 }
450 if command == "routes:api" {
451 self.openapi()?;
453 for (prefix, routes) in std::iter::once(("", &self.routes))
454 .chain(self.api_routes.as_ref().map(|r| ("/api", r)))
455 {
456 for route in routes.api_inventory() {
457 println!(
458 "{:<7} {:<28} {:<22} {}",
459 route.method,
460 format!("{prefix}{}", route.path),
461 route.operation_id.unwrap_or_default(),
462 route.response.unwrap_or_default()
463 );
464 }
465 }
466 #[cfg(feature = "auth")]
467 if self.auth_delivery.is_some() {
468 for route in capy_auth::routes().api_inventory() {
469 println!(
470 "{:<7} {:<28} {:<22} {}",
471 route.method,
472 format!("/api/auth{}", route.path),
473 route.operation_id.unwrap_or_default(),
474 route.response.unwrap_or_default()
475 );
476 }
477 }
478 return Ok(());
479 }
480 if command == "routes" {
481 for route in self.routes.inventory() {
482 println!("{:<7} {}", route.method, route.path);
483 }
484 if let Some(api) = &self.api_routes {
485 for route in api.inventory() {
486 println!("{:<7} /api{}", route.method, route.path);
487 }
488 }
489 #[cfg(feature = "auth")]
490 if self.auth_delivery.is_some() {
491 for route in capy_auth::routes().inventory() {
492 println!("{:<7} /api/auth{}", route.method, route.path);
493 }
494 }
495 return Ok(());
496 }
497 if !matches!(
498 command,
499 "serve" | "check" | "migrate" | "migrate:rollback" | "migrate:status" | "auth:prune"
500 ) {
501 return Err(AppError::Configuration(format!(
502 "Unknown application command: {command}"
503 )));
504 }
505 let config = match &self.config {
506 Some(config) => config.clone(),
507 None => AppConfig::load()?,
508 };
509 config.validate()?;
510 if matches!(command, "serve" | "check") {
512 self.api_document(&config)?;
513 }
514 if command == "check" || (command == "serve" && config.app.environment == "production") {
515 if let Some(directory) = &self.frontend {
516 crate::frontend::validate(directory)?;
517 }
518 }
519 if command == "check" {
520 #[cfg(feature = "jobs")]
521 {
522 let jobs_enabled = self.jobs.is_some();
523 #[cfg(feature = "mail")]
524 let jobs_enabled = jobs_enabled || self.mail_enabled;
525 if jobs_enabled {
526 config.jobs.validate_database(&config.database)?;
527 }
528 }
529 let migrations = M::migrations();
530 let mut names = std::collections::BTreeSet::new();
531 for migration in &migrations {
532 if !names.insert(migration.name()) {
533 return Err(AppError::Configuration(
534 "Duplicate registered migration name.".into(),
535 ));
536 }
537 }
538 println!(
539 "Configuration valid; {} migrations registered. No database connection opened.",
540 migrations.len()
541 );
542 return Ok(());
543 }
544 if command == "auth:prune" {
545 #[cfg(feature = "auth")]
546 if self.auth_delivery.is_some() {
547 let db = capy_db::connect(&config.database).await?;
548 println!(
549 "Pruned {} expired auth records.",
550 capy_auth::prune(&db).await?
551 );
552 return Ok(());
553 }
554 return Err(AppError::Configuration(
555 "Install auth with capy make:auth before pruning.".into(),
556 ));
557 }
558 init_logging(&config);
559 let db = capy_db::connect(&config.database).await?;
560 match command {
561 "migrate" => {
562 M::up(&db, None).await?;
563 println!("Migrations applied.");
564 }
565 "migrate:rollback" => {
566 M::down(&db, Some(1)).await?;
567 println!("Rolled back the latest migration.");
568 }
569 "migrate:status" => {
570 let statuses = capy_db::status::<M>(&db).await?;
571 if statuses.is_empty() {
572 println!("No migrations registered.");
573 }
574 for status in statuses {
575 println!(
576 "{:<8} {}",
577 if status.applied { "Applied" } else { "Pending" },
578 status.name
579 );
580 }
581 }
582 _ => {
583 let listener =
584 tokio::net::TcpListener::bind((config.host(), config.port())).await?;
585 let address = listener.local_addr()?;
586 if config.app.environment == "production" {
587 tracing::info!(%address, environment = %config.app.environment, "Capy ready");
588 } else if std::env::var_os("CAPY_DEV").is_some() {
589 println!(
590 "ā Database connected\nā Backend ready\nServer running on http://{address}"
591 );
592 } else {
593 println!("Capy v{}\n\nA calmer way to build web apps in Rust.\n\nApplication\n http://{address}\n\nEnvironment\n {}\n\nDatabase\n {}\n\nReady.",
594 env!("CARGO_PKG_VERSION"), config.app.environment,
595 if config.database.url.starts_with("sqlite:") { "SQLite" } else { "PostgreSQL" });
596 }
597 let shutdown_timeout = Duration::from_secs(config.server.shutdown_timeout_seconds);
598 let context = AppContext {
599 config: Arc::new(config),
600 db,
601 };
602 serve(
603 listener,
604 self.into_router(context),
605 shutdown_timeout,
606 shutdown_signal(),
607 )
608 .await?;
609 }
610 }
611 Ok(())
612 }
613}
614
615pub(crate) async fn serve(
618 listener: tokio::net::TcpListener,
619 router: axum::Router,
620 timeout: Duration,
621 signal: impl std::future::Future<Output = ()>,
622) -> Result<()> {
623 let handle = axum_server::Handle::new();
624 let server = axum_server::from_tcp(listener.into_std()?)?
625 .handle(handle.clone())
626 .serve(router.into_make_service_with_connect_info::<std::net::SocketAddr>());
627 tokio::pin!(server);
628 tokio::select! {
629 result = &mut server => { result?; }
630 () = signal => {
631 tracing::info!("shutdown requested");
632 handle.graceful_shutdown(None);
633 tracing::info!("waiting for active requests");
634 match tokio::time::timeout(timeout, &mut server).await {
635 Ok(result) => result?,
636 Err(_) => {
637 tracing::warn!("shutdown deadline reached");
638 handle.shutdown();
639 server.await?;
640 }
641 }
642 }
643 }
644 tracing::info!("server stopped");
645 Ok(())
646}
647
648pub(crate) fn init_logging(config: &AppConfig) {
649 let filter = EnvFilter::try_from_default_env()
650 .unwrap_or_else(|_| EnvFilter::new(crate::diagnostics::DEFAULT_FILTER));
651 if config.app.environment != "production"
652 && std::env::var("CAPY_DEV_LOG").is_ok_and(|value| value == "1")
653 {
654 let _ = tracing_subscriber::fmt()
655 .with_env_filter(filter)
656 .with_ansi(false)
657 .json()
658 .with_writer(crate::dev_logging::writer)
659 .try_init();
660 } else if config.app.environment == "production" {
661 let _ = tracing_subscriber::fmt()
662 .with_env_filter(filter)
663 .json()
664 .try_init();
665 } else {
666 let _ = tracing_subscriber::fmt()
667 .with_env_filter(filter)
668 .compact()
669 .try_init();
670 }
671}
672
673pub(crate) async fn shutdown_signal() {
674 let ctrl_c = async {
675 let _ = tokio::signal::ctrl_c().await;
676 };
677 #[cfg(unix)]
678 let terminate = async {
679 match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
680 Ok(mut stream) => {
681 stream.recv().await;
682 }
683 Err(_) => std::future::pending::<()>().await,
684 }
685 };
686 #[cfg(not(unix))]
687 let terminate = std::future::pending::<()>();
688 tokio::select! { () = ctrl_c => {}, () = terminate => {} }
689}