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