Skip to main content

capy_framework/
app.rs

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
8#[cfg(feature = "testing")]
9impl<M: MigratorTrait + Send> capy_testing::TestApplication for App<M> {
10    fn test_config(&self) -> Result<AppConfig> {
11        self.config
12            .clone()
13            .map(Ok)
14            .unwrap_or_else(|| AppConfig::load_for_tests("."))
15    }
16
17    async fn boot_test(self, context: AppContext, migrate: bool) -> Result<capy_testing::TestApp> {
18        context.config.validate()?;
19        self.api_document(&context.config)?;
20        if migrate {
21            M::up(&context.db, None).await?;
22        }
23        #[cfg(feature = "auth")]
24        let csrf = self.auth_delivery.is_some();
25        #[cfg(not(feature = "auth"))]
26        let csrf = false;
27        #[cfg(feature = "jobs")]
28        let jobs = self.jobs.clone();
29        #[cfg(all(feature = "jobs", feature = "mail"))]
30        let jobs = if let Some(mailer) = self.configured_mailer(&context.config)? {
31            Some(capy_mail::register_jobs(jobs.unwrap_or_default(), mailer))
32        } else {
33            jobs
34        };
35        #[cfg(feature = "jobs")]
36        let queue = jobs
37            .map(|jobs| capy_testing::TestQueue::new(context.clone(), jobs))
38            .transpose()?;
39        let seeds = self.seeds.clone();
40        let app = capy_testing::TestApp::new(self.into_router(context.clone()))
41            .with_context(context)
42            .with_csrf(csrf)
43            .with_seeds(seeds);
44        #[cfg(feature = "jobs")]
45        let app = if let Some(queue) = queue {
46            app.with_jobs(queue)
47        } else {
48            app
49        };
50        Ok(app)
51    }
52
53    #[cfg(feature = "mail")]
54    fn capture_test_mail(self, config: &AppConfig) -> Result<(Self, capy_testing::TestMailer)> {
55        let (mailer, capture) = capy_mail::Mailer::capture(config)?;
56        Ok((self.with_mail(mailer), capture))
57    }
58}
59
60/// Application builder: configuration, database, tracing, migrations, and HTTP.
61pub struct App<M = NoMigrations> {
62    seeds: Option<capy_db::Seeds>,
63    events: capy_core::Events,
64    routes: Routes,
65    api_routes: Option<Routes>,
66    frontend: Option<PathBuf>,
67    config: Option<AppConfig>,
68    request_timeouts: BTreeMap<String, Option<Duration>>,
69    observer: crate::diagnostics::Observer,
70    openapi_customizer: Option<OpenApiCustomizer>,
71    #[cfg(feature = "auth")]
72    auth_delivery: Option<Arc<dyn capy_auth::ResetDelivery>>,
73    #[cfg(feature = "auth")]
74    verification_delivery: Option<Arc<dyn capy_auth::VerificationDelivery>>,
75    #[cfg(feature = "jobs")]
76    jobs: Option<capy_jobs::Jobs>,
77    #[cfg(feature = "mail")]
78    mail_enabled: bool,
79    #[cfg(feature = "mail")]
80    mailer: Option<capy_mail::Mailer>,
81    migrations: PhantomData<M>,
82}
83
84impl Default for App {
85    fn default() -> Self {
86        Self::new()
87    }
88}
89
90impl App {
91    /// Begin an application using configuration from the current directory.
92    pub fn new() -> Self {
93        Self {
94            seeds: None,
95            events: capy_core::Events::new(),
96            routes: Routes::new(),
97            api_routes: None,
98            frontend: None,
99            config: None,
100            request_timeouts: BTreeMap::new(),
101            observer: None,
102            openapi_customizer: None,
103            #[cfg(feature = "auth")]
104            auth_delivery: None,
105            #[cfg(feature = "auth")]
106            verification_delivery: None,
107            #[cfg(feature = "jobs")]
108            jobs: None,
109            #[cfg(feature = "mail")]
110            mail_enabled: false,
111            #[cfg(feature = "mail")]
112            mailer: None,
113            migrations: PhantomData,
114        }
115    }
116}
117
118impl<M: MigratorTrait> App<M> {
119    /// Enable authenticated, single-use email verification. Register
120    /// EmailVerificationMigration after identity and supply private delivery.
121    #[cfg(feature = "auth")]
122    pub fn email_verification(mut self, delivery: impl capy_auth::VerificationDelivery) -> Self {
123        self.verification_delivery = Some(Arc::new(delivery));
124        self
125    }
126
127    #[cfg(feature = "auth")]
128    fn auth_routes(&self) -> Routes {
129        let routes = capy_auth::routes();
130        if self.verification_delivery.is_some() {
131            routes.merge(capy_auth::verification_routes())
132        } else {
133            routes
134        }
135    }
136
137    /// Register explicit development/test seeds, executed only by db:seed or the test harness.
138    /// The callback shares one database transaction; serving never runs it.
139    pub fn seeds(
140        mut self,
141        seed: impl for<'a> Fn(capy_db::SeedContext<'a>) -> capy_db::SeedFuture<'a>
142            + Send
143            + Sync
144            + 'static,
145    ) -> Self {
146        self.seeds = Some(capy_db::Seeds::new(seed));
147        self
148    }
149    /// Append a typed transaction listener. Return `Box::pin(async move { ... })`.
150    /// Handlers run in registration order before commit; failure rolls back built-in
151    /// auth transitions. Queue external side effects with `ctx.jobs().dispatch(job)`.
152    /// Capture additional services explicitly; never send email inside a transaction.
153    pub fn on<E: capy_core::Event>(
154        mut self,
155        listener: impl for<'a> Fn(&'a E, capy_core::EventContext<'a>) -> capy_core::EventFuture<'a>
156            + Send
157            + Sync
158            + 'static,
159    ) -> Self {
160        self.events = self.events.on::<E>(listener);
161        self
162    }
163
164    /// Enable configured outbound mail and the shared MailContext extractor.
165    /// With Jobs, the built-in versioned mail delivery handler is registered automatically.
166    #[cfg(feature = "mail")]
167    pub fn mail(mut self) -> Self {
168        self.mail_enabled = true;
169        self
170    }
171
172    /// Use an explicit shared transport, including real-rendering capture in tests.
173    #[cfg(feature = "mail")]
174    pub fn with_mail(mut self, mailer: capy_mail::Mailer) -> Self {
175        self.mail_enabled = true;
176        self.mailer = Some(mailer);
177        self
178    }
179    #[cfg(feature = "mail")]
180    fn validate_mail(&self, config: &AppConfig) -> Result<()> {
181        if self.mail_enabled {
182            if let Some(mailer) = &self.mailer {
183                mailer.validate_environment(config.app.environment == "production")?;
184            } else {
185                capy_mail::Mailer::validate(config)?;
186            }
187            #[cfg(feature = "jobs")]
188            capy_mail::validate_jobs(self.jobs.clone().unwrap_or_default())?;
189        }
190        Ok(())
191    }
192    #[cfg(feature = "mail")]
193    fn configured_mailer(&self, config: &AppConfig) -> Result<Option<capy_mail::Mailer>> {
194        self.validate_mail(config)?;
195        if !self.mail_enabled {
196            return Ok(None);
197        }
198        self.mailer
199            .clone()
200            .map(Ok)
201            .unwrap_or_else(|| capy_mail::Mailer::from_config(config))
202            .map(Some)
203    }
204
205    /// Install conventional `/api/auth` routes and synchronizer CSRF protection.
206    /// The application owns password-reset delivery. Migrate identity tables first.
207    #[cfg(feature = "auth")]
208    pub fn auth(mut self, delivery: impl capy_auth::ResetDelivery) -> Self {
209        self.auth_delivery = Some(Arc::new(delivery));
210        self
211    }
212
213    /// Register durable job handlers. HTTP only dispatches; workers run separately.
214    #[cfg(feature = "jobs")]
215    pub fn jobs(mut self, jobs: capy_jobs::Jobs) -> Self {
216        self.jobs = Some(jobs);
217        self
218    }
219
220    /// Customize standard OpenAPI metadata, servers or security schemes.
221    /// The same function runs during offline export and endpoint generation.
222    pub fn openapi_with(
223        mut self,
224        customize: impl Fn(&mut crate::ApiDocument) + Send + Sync + 'static,
225    ) -> Self {
226        self.openapi_customizer = Some(Arc::new(customize));
227        self
228    }
229
230    /// Generate this application's explicit contract without opening a database connection.
231    pub fn openapi(&self) -> Result<crate::ApiDocument> {
232        let config = self
233            .config
234            .clone()
235            .map(Ok)
236            .unwrap_or_else(AppConfig::load_for_contracts)?;
237        self.api_document(&config)
238    }
239
240    /// Export while rejecting undocumented public API routes, independent of config defaults.
241    pub fn openapi_strict(&self) -> Result<crate::ApiDocument> {
242        let mut config = self
243            .config
244            .clone()
245            .map(Ok)
246            .unwrap_or_else(AppConfig::load_for_contracts)?;
247        config.api.require_documented_routes = true;
248        self.api_document(&config)
249    }
250
251    fn api_document(&self, config: &AppConfig) -> Result<crate::ApiDocument> {
252        #[cfg(feature = "mail")]
253        self.validate_mail(config)?;
254        #[cfg(feature = "jobs")]
255        if let Some(jobs) = &self.jobs {
256            jobs.validate()?;
257        }
258        let mut routes = vec![("", &self.routes)];
259        if let Some(api) = &self.api_routes {
260            routes.push(("/api", api));
261        }
262        if config.api.require_documented_routes {
263            for (prefix, routes) in &routes {
264                routes.require_documented(prefix)?;
265            }
266        }
267        #[cfg(feature = "auth")]
268        let auth_routes = self.auth_routes();
269        #[cfg(feature = "auth")]
270        if let Some(delivery) = &self.verification_delivery {
271            if self.auth_delivery.is_none() {
272                return Err(AppError::Configuration(
273                    "Enable App::auth before email verification.".into(),
274                ));
275            }
276            if config.app.environment == "production" && delivery.development_only() {
277                return Err(AppError::Configuration(
278                    "Install a production email verification delivery adapter.".into(),
279                ));
280            }
281        }
282        #[cfg(feature = "auth")]
283        if let Some(delivery) = &self.auth_delivery {
284            let production = config.app.environment == "production";
285            config.auth.validate(production)?;
286            config.http.client_ip.validate()?;
287            if production && delivery.development_only() {
288                return Err(AppError::Configuration("Install an application-owned password reset delivery adapter before enabling auth in production.".into()));
289            }
290            routes.push(("/api/auth", &auth_routes));
291        }
292        let mut document = crate::ApiDocument::from_routes(
293            config.api.title.as_deref().unwrap_or(&config.app.name),
294            &config.api.version,
295            routes,
296        )?;
297        #[cfg(feature = "auth")]
298        if self.auth_delivery.is_some() {
299            document.as_value_mut()["components"]["securitySchemes"]["session"] = crate::serde_json::json!({
300                "type": "apiKey", "in": "cookie",
301                "name": config.auth.cookie_name(config.app.environment == "production")
302            });
303            if let Some(paths) = document.as_value_mut()["paths"].as_object_mut() {
304                for (path, methods) in paths {
305                    if let Some(methods) = methods.as_object_mut() {
306                        for (method, operation) in methods {
307                            let mutation =
308                                matches!(method.as_str(), "post" | "put" | "patch" | "delete");
309                            let bootstrap = path == "/api/auth/csrf" && method == "get";
310                            if mutation || bootstrap {
311                                if operation.get("parameters").is_none() {
312                                    operation["parameters"] = crate::serde_json::json!([]);
313                                }
314                                operation["parameters"].as_array_mut().expect("generated parameter array").push(crate::serde_json::json!({
315                                    "name": if bootstrap { "X-Capy-CSRF" } else { "X-CSRF-Token" },
316                                    "in": "header", "required": true,
317                                    "description": if bootstrap { "Send 1 to bootstrap a same-origin CSRF session." } else { "Synchronizer token from GET /api/auth/csrf; never a session secret." },
318                                    "schema": {"type": "string"}
319                                }));
320                                operation["responses"]["403"] = crate::serde_json::json!({"description": "CSRF or policy rejection", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ApiErrorResponse"}}}});
321                            }
322                        }
323                    }
324                }
325            }
326        }
327        if let Some(customize) = &self.openapi_customizer {
328            customize(&mut document);
329        }
330        Ok(document)
331    }
332
333    /// Install an application-owned, nonblocking response observer for telemetry.
334    pub fn observe_requests(mut self, observer: impl crate::RequestObserver) -> Self {
335        self.observer = Some(Arc::new(observer));
336        self
337    }
338
339    /// Override the response-header deadline for a full matched route template,
340    /// such as `/api/events` or `/api/posts/{id}`. `None` intentionally disables
341    /// it. Response body streaming is never subject to this header deadline.
342    pub fn request_timeout_for(
343        mut self,
344        route: impl Into<String>,
345        timeout: Option<Duration>,
346    ) -> Self {
347        self.request_timeouts.insert(route.into(), timeout);
348        self
349    }
350
351    /// Mount API routes under `/api`, preserving JSON errors within that namespace.
352    /// Declare paths such as `/posts` without repeating the prefix.
353    pub fn api_routes(mut self, routes: Routes) -> Self {
354        self.api_routes = Some(routes);
355        self
356    }
357
358    /// Serve built frontend assets and use index.html for non-API browser routes.
359    /// The path is relative to the application's working directory. Production
360    /// startup requires a readable index.html; development may use Vite instead.
361    pub fn frontend(mut self, directory: impl Into<PathBuf>) -> Self {
362        self.frontend = Some(directory.into());
363        self
364    }
365
366    /// Set the application's routes.
367    pub fn routes(mut self, routes: Routes) -> Self {
368        self.routes = routes;
369        self
370    }
371
372    /// Use explicit typed configuration, useful for tests and embedded apps.
373    pub fn config(mut self, config: AppConfig) -> Self {
374        self.config = Some(config);
375        self
376    }
377
378    /// Register a native SeaORM migrator for the application's CLI commands.
379    /// Serving never applies migrations implicitly.
380    pub fn migrations<N: MigratorTrait>(self, _migrator: N) -> App<N> {
381        App {
382            seeds: self.seeds,
383            events: self.events,
384            routes: self.routes,
385            api_routes: self.api_routes,
386            frontend: self.frontend,
387            config: self.config,
388            request_timeouts: self.request_timeouts,
389            observer: self.observer,
390            openapi_customizer: self.openapi_customizer,
391            #[cfg(feature = "auth")]
392            auth_delivery: self.auth_delivery,
393            #[cfg(feature = "auth")]
394            verification_delivery: self.verification_delivery,
395            #[cfg(feature = "jobs")]
396            jobs: self.jobs,
397            #[cfg(feature = "mail")]
398            mail_enabled: self.mail_enabled,
399            #[cfg(feature = "mail")]
400            mailer: self.mailer,
401            migrations: PhantomData,
402        }
403    }
404
405    /// Build a service using an existing context, without binding a TCP port.
406    /// The returned Axum router can be tested or served with native tooling.
407    pub fn into_router(self, context: AppContext) -> axum::Router {
408        #[cfg(feature = "auth")]
409        let auth_routes = self.auth_routes();
410        #[cfg(feature = "mail")]
411        let mailer = self.configured_mailer(&context.config);
412        let docs_enabled =
413            context.config.api.docs && context.config.app.environment != "production";
414        let schema = (context.config.api.openapi || docs_enabled).then(|| {
415            self.api_document(&context.config)
416                .map(|doc| doc.as_value().clone())
417        });
418        let http = context.config.http.clone();
419        let policy = crate::http_policy::HttpPolicy {
420            default_timeout: (http.request_timeout_seconds != 0)
421                .then(|| Duration::from_secs(http.request_timeout_seconds)),
422            overrides: self.request_timeouts,
423        };
424        let mut router = self.routes.into_router();
425        if let Some(api) = self.api_routes {
426            router = router.nest("/api", api.into_router());
427        }
428        #[cfg(feature = "auth")]
429        let auth = self.auth_delivery.map(|delivery| {
430            capy_auth::AuthService::new(context.clone(), delivery).and_then(|service| {
431                let service = service.with_events(self.events.clone());
432                match self.verification_delivery {
433                    Some(delivery) => service.with_email_verification(delivery),
434                    None => Ok(service),
435                }
436            })
437        });
438        #[cfg(feature = "auth")]
439        if auth.is_some() {
440            router = router.nest("/api/auth", auth_routes.into_router());
441        }
442        if let Some(schema) = schema {
443            // run_command reports generation errors before binding; native into_router
444            // callers receive the same sanitized HTTP envelope if their metadata is invalid.
445            let schema = Arc::new(schema.map_err(|error| error.to_string()));
446            router = router.route(
447                "/openapi.json",
448                axum::routing::get(move || {
449                    let schema = schema.clone();
450                    async move {
451                        match schema.as_ref() {
452                            Ok(document) => Ok(axum::Json(document.clone())),
453                            Err(_) => Err(AppError::Configuration(
454                                "Invalid API contract. Run capy openapi to inspect the error."
455                                    .into(),
456                            )),
457                        }
458                    }
459                }),
460            );
461        }
462        if docs_enabled {
463            router = router.route(
464                "/docs/api",
465                axum::routing::get(|| async {
466                    axum::response::Html(include_str!("api_docs.html"))
467                }),
468            );
469        }
470        if let Some(directory) = self.frontend {
471            router =
472                router.fallback(move |request| crate::frontend::serve(directory.clone(), request));
473        }
474        let mut router = router
475            .with_state(context)
476            .layer(axum::Extension(self.events));
477        #[cfg(feature = "mail")]
478        match mailer {
479            Ok(Some(mailer)) => router = router.layer(axum::Extension(mailer)),
480            Ok(None) => {}
481            Err(_) => {
482                router = axum::Router::new().fallback(|| async {
483                    AppError::Configuration("Invalid mail configuration. Run capy check.".into())
484                })
485            }
486        }
487
488        #[cfg(feature = "auth")]
489        if let Some(service) = auth {
490            router = match service {
491                Ok(service) => service.protect(router),
492                Err(_) => axum::Router::new().fallback(|| async {
493                    AppError::Configuration("Invalid auth configuration. Run capy check.".into())
494                }),
495            };
496        }
497        // Auth extraction and CSRF database work remain inside the existing deadline.
498        router = router
499            .layer(axum::extract::DefaultBodyLimit::max(http.max_body_bytes))
500            .layer(axum::middleware::from_fn_with_state(
501                policy,
502                crate::http_policy::deadline,
503            ));
504        if http.compression {
505            router = router.layer(tower_http::compression::CompressionLayer::new());
506        }
507        router
508            .layer(axum::middleware::from_fn_with_state(
509                self.observer,
510                crate::diagnostics::request,
511            ))
512            .layer(
513                tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer::new([
514                    axum::http::header::AUTHORIZATION,
515                    axum::http::header::COOKIE,
516                    axum::http::HeaderName::from_static("x-csrf-token"),
517                ]),
518            )
519            .layer(
520                tower_http::sensitive_headers::SetSensitiveResponseHeadersLayer::new([
521                    axum::http::header::SET_COOKIE,
522                ]),
523            )
524    }
525
526    /// Serve by default, or execute the command forwarded by `capy`.
527    /// Supported arguments: `serve`, `check`, `routes`, `migrate`, `migrate:rollback`,
528    /// and `migrate:status`. With jobs enabled, `queue:work` accepts `--queue` and
529    /// `--concurrency`; `queue:failed`, `queue:retry UUID`, `queue:forget UUID` and
530    /// `queue:check` share the same binary. Migrations are explicit; rollback reverts one.
531    pub async fn run(self) -> Result<()> {
532        let mut args = std::env::args().skip(1);
533        let command = args.next().unwrap_or_else(|| "serve".into());
534        #[cfg(feature = "jobs")]
535        if command.starts_with("queue:") {
536            return self
537                .run_queue_command(&command, &args.collect::<Vec<_>>())
538                .await;
539        }
540        #[cfg(feature = "mail")]
541        if matches!(command.as_str(), "mail:list" | "mail:show" | "mail:clear") {
542            let config = self
543                .config
544                .clone()
545                .map(Ok)
546                .unwrap_or_else(AppConfig::load_for_contracts)?;
547            return crate::mail_commands::run(&config, &command, &args.collect::<Vec<_>>());
548        }
549        if args.next().is_some() {
550            return Err(AppError::Configuration(
551                "Unexpected arguments. Use the capy CLI for application commands.".into(),
552            ));
553        }
554        self.run_command(&command).await
555    }
556
557    #[cfg(feature = "jobs")]
558    async fn run_queue_command(self, command: &str, args: &[String]) -> Result<()> {
559        let config = self
560            .config
561            .clone()
562            .map(Ok)
563            .unwrap_or_else(AppConfig::load)?;
564        #[cfg(feature = "mail")]
565        let mailer = self.configured_mailer(&config)?;
566        let jobs = self.jobs;
567        #[cfg(feature = "mail")]
568        let jobs = if let Some(mailer) = mailer {
569            Some(capy_mail::register_jobs(jobs.unwrap_or_default(), mailer))
570        } else {
571            jobs
572        };
573        let jobs = jobs.ok_or_else(|| {
574            AppError::Configuration(
575                "Register jobs with App::jobs (capy make:job installs the conventional registry)."
576                    .into(),
577            )
578        })?;
579        crate::job_commands::run(command, args, config, jobs).await
580    }
581
582    /// Run a specific application command without reading process arguments.
583    pub async fn run_command(self, command: &str) -> Result<()> {
584        let command = match command {
585            "db:migrate" => "migrate",
586            "db:rollback" => "migrate:rollback",
587            "db:status" => "migrate:status",
588            command => command,
589        };
590        #[cfg(feature = "jobs")]
591        if command.starts_with("queue:") {
592            return self.run_queue_command(command, &[]).await;
593        }
594        #[cfg(feature = "mail")]
595        if command == "mail:check" {
596            let config = self
597                .config
598                .clone()
599                .map(Ok)
600                .unwrap_or_else(AppConfig::load_for_contracts)?;
601            if !self.mail_enabled {
602                return Err(AppError::Configuration(
603                    "Enable mail with App::mail.".into(),
604                ));
605            }
606            self.validate_mail(&config)?;
607            println!("Mail: configuration and compiled templates valid. No DNS, authentication or delivery attempted.");
608            return Ok(());
609        }
610        if matches!(command, "__capy_contract" | "__capy_contract_strict") {
611            let document = if command == "__capy_contract_strict" {
612                self.openapi_strict()?
613            } else {
614                self.openapi()?
615            };
616            print!("{}", document.to_json()?);
617            return Ok(());
618        }
619        if command == "routes:api" {
620            // Also validate incomplete/duplicate metadata before showing the inventory.
621            self.openapi()?;
622            for (prefix, routes) in std::iter::once(("", &self.routes))
623                .chain(self.api_routes.as_ref().map(|r| ("/api", r)))
624            {
625                for route in routes.api_inventory() {
626                    println!(
627                        "{:<7} {:<28} {:<22} {}",
628                        route.method,
629                        format!("{prefix}{}", route.path),
630                        route.operation_id.unwrap_or_default(),
631                        route.response.unwrap_or_default()
632                    );
633                }
634            }
635            #[cfg(feature = "auth")]
636            if self.auth_delivery.is_some() {
637                for route in self.auth_routes().api_inventory() {
638                    println!(
639                        "{:<7} {:<28} {:<22} {}",
640                        route.method,
641                        format!("/api/auth{}", route.path),
642                        route.operation_id.unwrap_or_default(),
643                        route.response.unwrap_or_default()
644                    );
645                }
646            }
647            return Ok(());
648        }
649        if command == "routes" {
650            for route in self.routes.inventory() {
651                println!("{:<7} {}", route.method, route.path);
652            }
653            if let Some(api) = &self.api_routes {
654                for route in api.inventory() {
655                    println!("{:<7} /api{}", route.method, route.path);
656                }
657            }
658            #[cfg(feature = "auth")]
659            if self.auth_delivery.is_some() {
660                for route in self.auth_routes().inventory() {
661                    println!("{:<7} /api/auth{}", route.method, route.path);
662                }
663            }
664            return Ok(());
665        }
666        if !matches!(
667            command,
668            "serve"
669                | "check"
670                | "migrate"
671                | "migrate:rollback"
672                | "migrate:status"
673                | "auth:prune"
674                | "db:seed"
675        ) {
676            return Err(AppError::Configuration(format!(
677                "Unknown application command: {command}"
678            )));
679        }
680        let config = match &self.config {
681            Some(config) => config.clone(),
682            None => AppConfig::load()?,
683        };
684        config.validate()?;
685        if command == "db:seed" {
686            capy_db::Seeds::validate_environment(&config)?;
687            let seeds = self.seeds.ok_or_else(|| {
688                AppError::Configuration(
689                    "Register application-owned seeds with App::seeds before running db:seed."
690                        .into(),
691                )
692            })?;
693            let db = capy_db::connect(&config.database).await?;
694            let context = AppContext {
695                db,
696                config: Arc::new(config),
697            };
698            seeds.run(&context).await?;
699            println!("Development seeds committed. Migrations were not run automatically.");
700            return Ok(());
701        }
702        // Validate declared contracts before starting HTTP or approving configuration.
703        if matches!(command, "serve" | "check") {
704            self.api_document(&config)?;
705        }
706        if command == "check" || (command == "serve" && config.app.environment == "production") {
707            if let Some(directory) = &self.frontend {
708                crate::frontend::validate(directory)?;
709            }
710        }
711        if command == "check" {
712            #[cfg(feature = "auth")]
713            if self.auth_delivery.is_some()
714                && config.app.environment == "production"
715                && !config.auth.throttle.enabled
716            {
717                // Offline check has no tracing subscriber. Keep its warning visible
718                // without contaminating JSON contract export on stdout.
719                eprintln!("Warning [auth.throttle.disabled]: built-in auth abuse limits are disabled; enforce equivalent deployment-level protection.");
720            }
721            #[cfg(feature = "jobs")]
722            {
723                let jobs_enabled = self.jobs.is_some();
724                #[cfg(feature = "mail")]
725                let jobs_enabled = jobs_enabled || self.mail_enabled;
726                if jobs_enabled {
727                    config.jobs.validate_database(&config.database)?;
728                }
729            }
730            let migrations = M::migrations();
731            let mut names = std::collections::BTreeSet::new();
732            for migration in &migrations {
733                if !names.insert(migration.name()) {
734                    return Err(AppError::Configuration(
735                        "Duplicate registered migration name.".into(),
736                    ));
737                }
738            }
739            println!(
740                "Configuration valid; {} migrations registered. No database connection opened.",
741                migrations.len()
742            );
743            return Ok(());
744        }
745        if command == "auth:prune" {
746            #[cfg(feature = "auth")]
747            if self.auth_delivery.is_some() {
748                let db = capy_db::connect(&config.database).await?;
749                let mut count = capy_auth::prune(&db).await?;
750                if self.verification_delivery.is_some() {
751                    count += capy_auth::verification::prune(&db).await?;
752                }
753                println!("Pruned {count} expired auth records.");
754                return Ok(());
755            }
756            return Err(AppError::Configuration(
757                "Install auth with capy make:auth before pruning.".into(),
758            ));
759        }
760        init_logging(&config);
761        let db = capy_db::connect(&config.database).await?;
762        match command {
763            "migrate" => {
764                M::up(&db, None).await?;
765                println!("Migrations applied.");
766            }
767            "migrate:rollback" => {
768                M::down(&db, Some(1)).await?;
769                println!("Rolled back the latest migration.");
770            }
771            "migrate:status" => {
772                let statuses = capy_db::status::<M>(&db).await?;
773                if statuses.is_empty() {
774                    println!("No migrations registered.");
775                }
776                for status in statuses {
777                    println!(
778                        "{:<8} {}",
779                        if status.applied { "Applied" } else { "Pending" },
780                        status.name
781                    );
782                }
783            }
784            _ => {
785                let listener =
786                    tokio::net::TcpListener::bind((config.host(), config.port())).await?;
787                let address = listener.local_addr()?;
788                if config.app.environment == "production" {
789                    tracing::info!(%address, environment = %config.app.environment, "Capy ready");
790                } else if std::env::var_os("CAPY_DEV").is_some() {
791                    println!(
792                        "āœ“ Database connected\nāœ“ Backend ready\nServer running on http://{address}"
793                    );
794                } else {
795                    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.",
796                        env!("CARGO_PKG_VERSION"), config.app.environment,
797                        if config.database.url.starts_with("sqlite:") { "SQLite" } else { "PostgreSQL" });
798                }
799                let shutdown_timeout = Duration::from_secs(config.server.shutdown_timeout_seconds);
800                let context = AppContext {
801                    config: Arc::new(config),
802                    db,
803                };
804                serve(
805                    listener,
806                    self.into_router(context),
807                    shutdown_timeout,
808                    shutdown_signal(),
809                )
810                .await?;
811            }
812        }
813        Ok(())
814    }
815}
816
817// axum-server owns connection cancellation. Merely dropping axum::serve's
818// graceful future leaves its detached connection tasks running in shared runtimes.
819pub(crate) async fn serve(
820    listener: tokio::net::TcpListener,
821    router: axum::Router,
822    timeout: Duration,
823    signal: impl std::future::Future<Output = ()>,
824) -> Result<()> {
825    let handle = axum_server::Handle::new();
826    let server = axum_server::from_tcp(listener.into_std()?)?
827        .handle(handle.clone())
828        .serve(router.into_make_service_with_connect_info::<std::net::SocketAddr>());
829    tokio::pin!(server);
830    tokio::select! {
831        result = &mut server => { result?; }
832        () = signal => {
833            tracing::info!("shutdown requested");
834            handle.graceful_shutdown(None);
835            tracing::info!("waiting for active requests");
836            match tokio::time::timeout(timeout, &mut server).await {
837                Ok(result) => result?,
838                Err(_) => {
839                    tracing::warn!("shutdown deadline reached");
840                    handle.shutdown();
841                    server.await?;
842                }
843            }
844        }
845    }
846    tracing::info!("server stopped");
847    Ok(())
848}
849
850pub(crate) fn init_logging(config: &AppConfig) {
851    let filter = EnvFilter::try_from_default_env()
852        .unwrap_or_else(|_| EnvFilter::new(crate::diagnostics::DEFAULT_FILTER));
853    if config.app.environment != "production"
854        && std::env::var("CAPY_DEV_LOG").is_ok_and(|value| value == "1")
855    {
856        let _ = tracing_subscriber::fmt()
857            .with_env_filter(filter)
858            .with_ansi(false)
859            .json()
860            .with_writer(crate::dev_logging::writer)
861            .try_init();
862    } else if config.app.environment == "production" {
863        let _ = tracing_subscriber::fmt()
864            .with_env_filter(filter)
865            .json()
866            .try_init();
867    } else {
868        let _ = tracing_subscriber::fmt()
869            .with_env_filter(filter)
870            .compact()
871            .try_init();
872    }
873}
874
875pub(crate) async fn shutdown_signal() {
876    let ctrl_c = async {
877        let _ = tokio::signal::ctrl_c().await;
878    };
879    #[cfg(unix)]
880    let terminate = async {
881        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
882            Ok(mut stream) => {
883                stream.recv().await;
884            }
885            Err(_) => std::future::pending::<()>().await,
886        }
887    };
888    #[cfg(not(unix))]
889    let terminate = std::future::pending::<()>();
890    tokio::select! { () = ctrl_c => {}, () = terminate => {} }
891}