Skip to main content

capy_framework/
app.rs

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