capy-framework 0.10.0

An opinionated full-stack Rust web framework with strong conventions and sensible defaults.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
use crate::{AppConfig, AppContext, AppError, Result, Routes, Services};
use capy_db::{MigratorTrait, NoMigrations};
use std::{collections::BTreeMap, marker::PhantomData, path::PathBuf, sync::Arc, time::Duration};
use tracing_subscriber::EnvFilter;

type OpenApiCustomizer = Arc<dyn Fn(&mut crate::ApiDocument) + Send + Sync>;

#[cfg(feature = "testing")]
impl<M: MigratorTrait + Send> capy_testing::TestApplication for App<M> {
    fn test_config(&self) -> Result<AppConfig> {
        self.config
            .clone()
            .map(Ok)
            .unwrap_or_else(|| AppConfig::load_for_tests("."))
    }

    async fn boot_test(self, context: AppContext, migrate: bool) -> Result<capy_testing::TestApp> {
        context.config.validate()?;
        let contracts = self.api_document(&context.config)?.as_value().clone();
        if migrate {
            M::up(&context.db, None).await?;
        }
        #[cfg(feature = "auth")]
        let csrf = self.auth_delivery.is_some();
        #[cfg(not(feature = "auth"))]
        let csrf = false;
        #[cfg(feature = "jobs")]
        let jobs = self.jobs.clone();
        let services = self.resolved_services(&context.config)?;
        #[cfg(all(feature = "jobs", feature = "mail"))]
        let jobs = if let Some(mailer) = self.configured_mailer(&context.config)? {
            Some(capy_mail::register_jobs(jobs.unwrap_or_default(), mailer))
        } else {
            jobs
        };
        #[cfg(feature = "jobs")]
        let queue = jobs
            .map(|jobs| {
                capy_testing::TestQueue::new(context.clone(), jobs)
                    .map(|queue| queue.with_services(services.clone()))
            })
            .transpose()?;
        let seeds = self.seeds.clone();
        let app = capy_testing::TestApp::new(
            self.into_router_with_services(context.clone(), Ok(services.clone())),
        )
        .with_context(context)
        .with_services(services)
        .with_csrf(csrf)
        .with_seeds(seeds)
        .with_contracts(contracts);
        #[cfg(feature = "jobs")]
        let app = if let Some(queue) = queue {
            app.with_jobs(queue)
        } else {
            app
        };
        Ok(app)
    }

    #[cfg(feature = "mail")]
    fn capture_test_mail(self, config: &AppConfig) -> Result<(Self, capy_testing::TestMailer)> {
        let (mailer, capture) = capy_mail::Mailer::capture(config)?;
        Ok((self.with_mail(mailer), capture))
    }
}

/// Application builder: configuration, database, tracing, migrations, and HTTP.
pub struct App<M = NoMigrations> {
    services: Services,
    seeds: Option<capy_db::Seeds>,
    events: capy_core::Events,
    routes: Routes,
    api_routes: Option<Routes>,
    frontend: Option<PathBuf>,
    config: Option<AppConfig>,
    request_timeouts: BTreeMap<String, Option<Duration>>,
    observer: crate::diagnostics::Observer,
    openapi_customizer: Option<OpenApiCustomizer>,
    #[cfg(feature = "auth")]
    auth_delivery: Option<Arc<dyn capy_auth::ResetDelivery>>,
    #[cfg(feature = "auth")]
    verification_delivery: Option<Arc<dyn capy_auth::VerificationDelivery>>,
    #[cfg(feature = "jobs")]
    jobs: Option<capy_jobs::Jobs>,
    #[cfg(feature = "scheduler")]
    schedules: capy_jobs::scheduler::Schedules,
    #[cfg(feature = "scheduler")]
    tasks: capy_jobs::scheduler::Tasks,
    #[cfg(feature = "mail")]
    mail_enabled: bool,
    #[cfg(feature = "mail")]
    mailer: Option<capy_mail::Mailer>,
    migrations: PhantomData<M>,
}

impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}

impl App {
    /// Begin an application using configuration from the current directory.
    pub fn new() -> Self {
        Self {
            services: Services::new(),
            seeds: None,
            events: capy_core::Events::new(),
            routes: Routes::new(),
            api_routes: None,
            frontend: None,
            config: None,
            request_timeouts: BTreeMap::new(),
            observer: None,
            openapi_customizer: None,
            #[cfg(feature = "auth")]
            auth_delivery: None,
            #[cfg(feature = "auth")]
            verification_delivery: None,
            #[cfg(feature = "jobs")]
            jobs: None,
            #[cfg(feature = "scheduler")]
            schedules: capy_jobs::scheduler::Schedules::new(),
            #[cfg(feature = "scheduler")]
            tasks: capy_jobs::scheduler::Tasks::new(),
            #[cfg(feature = "mail")]
            mail_enabled: false,
            #[cfg(feature = "mail")]
            mailer: None,
            migrations: PhantomData,
        }
    }
}

impl<M: MigratorTrait> App<M> {
    /// Register or replace a typed dependency for HTTP, workers and tests.
    /// Register the same factory in each process; test factories may override a type.
    pub fn service<T: Send + Sync + 'static>(mut self, service: T) -> Self {
        self.services.insert(service);
        self
    }

    /// Register private storage, including isolated memory storage for tests.
    #[cfg(feature = "storage")]
    pub fn storage(self, storage: capy_storage::Storage) -> Self {
        self.service(storage)
    }

    fn resolved_services(&self, config: &AppConfig) -> Result<Services> {
        #[cfg(feature = "mail")]
        let mut services = self.services.clone();
        #[cfg(all(not(feature = "mail"), feature = "storage"))]
        let mut services = self.services.clone();
        #[cfg(all(not(feature = "mail"), not(feature = "storage")))]
        let services = self.services.clone();
        #[cfg(feature = "mail")]
        if let Some(mailer) = self.configured_mailer(config)? {
            services.insert(mailer);
        }
        #[cfg(feature = "storage")]
        if services.find::<capy_storage::Storage>().is_none() {
            if let Some(storage) = capy_storage::Storage::from_config(&config.storage)
                .map_err(|error| AppError::Configuration(error.to_string()))?
            {
                services.insert(storage);
            }
        }
        #[cfg(not(feature = "mail"))]
        let _ = config;
        Ok(services)
    }

    /// Enable authenticated, single-use email verification. Register
    /// EmailVerificationMigration after identity and supply private delivery.
    #[cfg(feature = "auth")]
    pub fn email_verification(mut self, delivery: impl capy_auth::VerificationDelivery) -> Self {
        self.verification_delivery = Some(Arc::new(delivery));
        self
    }

    #[cfg(feature = "auth")]
    fn auth_routes(&self) -> Routes {
        let routes = capy_auth::routes();
        if self.verification_delivery.is_some() {
            routes.merge(capy_auth::verification_routes())
        } else {
            routes
        }
    }

    /// Register explicit development/test seeds, executed only by db:seed or the test harness.
    /// The callback shares one database transaction; serving never runs it.
    pub fn seeds(
        mut self,
        seed: impl for<'a> Fn(capy_db::SeedContext<'a>) -> capy_db::SeedFuture<'a>
            + Send
            + Sync
            + 'static,
    ) -> Self {
        self.seeds = Some(capy_db::Seeds::new(seed));
        self
    }
    /// Append a typed transaction listener. Return `Box::pin(async move { ... })`.
    /// Handlers run in registration order before commit; failure rolls back built-in
    /// auth transitions. Queue external side effects with `ctx.jobs().dispatch(job)`.
    /// Capture additional services explicitly; never send email inside a transaction.
    pub fn on<E: capy_core::Event>(
        mut self,
        listener: impl for<'a> Fn(&'a E, capy_core::EventContext<'a>) -> capy_core::EventFuture<'a>
            + Send
            + Sync
            + 'static,
    ) -> Self {
        self.events = self.events.on::<E>(listener);
        self
    }

    /// Enable configured outbound mail and the shared MailContext extractor.
    /// With Jobs, the built-in versioned mail delivery handler is registered automatically.
    #[cfg(feature = "mail")]
    pub fn mail(mut self) -> Self {
        self.mail_enabled = true;
        self
    }

    /// Use an explicit shared transport, including real-rendering capture in tests.
    #[cfg(feature = "mail")]
    pub fn with_mail(mut self, mailer: capy_mail::Mailer) -> Self {
        self.mail_enabled = true;
        self.mailer = Some(mailer);
        self
    }
    #[cfg(feature = "mail")]
    fn validate_mail(&self, config: &AppConfig) -> Result<()> {
        if self.mail_enabled {
            if let Some(mailer) = &self.mailer {
                mailer.validate_environment(config.app.environment == "production")?;
            } else if let Some(mailer) = self.services.find::<capy_mail::Mailer>() {
                mailer.validate_environment(config.app.environment == "production")?;
            } else {
                capy_mail::Mailer::validate(config)?;
            }
            #[cfg(feature = "jobs")]
            capy_mail::validate_jobs(self.jobs.clone().unwrap_or_default())?;
        }
        Ok(())
    }
    #[cfg(feature = "mail")]
    fn configured_mailer(&self, config: &AppConfig) -> Result<Option<capy_mail::Mailer>> {
        self.validate_mail(config)?;
        if !self.mail_enabled {
            return Ok(None);
        }
        self.mailer
            .clone()
            .or_else(|| {
                self.services
                    .find::<capy_mail::Mailer>()
                    .map(|mailer| (*mailer).clone())
            })
            .map(Ok)
            .unwrap_or_else(|| capy_mail::Mailer::from_config(config))
            .map(Some)
    }

    /// Install conventional `/api/auth` routes and synchronizer CSRF protection.
    /// The application owns password-reset delivery. Migrate identity tables first.
    #[cfg(feature = "auth")]
    pub fn auth(mut self, delivery: impl capy_auth::ResetDelivery) -> Self {
        self.auth_delivery = Some(Arc::new(delivery));
        self
    }

    /// Register durable job handlers. HTTP only dispatches; workers run separately.
    #[cfg(feature = "jobs")]
    pub fn jobs(mut self, jobs: capy_jobs::Jobs) -> Self {
        self.jobs = Some(jobs);
        self
    }

    /// Register manually invoked named operational tasks.
    #[cfg(feature = "scheduler")]
    pub fn tasks(mut self, tasks: capy_jobs::scheduler::Tasks) -> Self {
        self.tasks = tasks;
        self
    }

    /// Register durable UTC schedules; the separate scheduler process publishes jobs.
    #[cfg(feature = "scheduler")]
    pub fn schedules(mut self, schedules: capy_jobs::scheduler::Schedules) -> Self {
        self.schedules = schedules;
        self
    }

    /// Customize standard OpenAPI metadata, servers or security schemes.
    /// The same function runs during offline export and endpoint generation.
    pub fn openapi_with(
        mut self,
        customize: impl Fn(&mut crate::ApiDocument) + Send + Sync + 'static,
    ) -> Self {
        self.openapi_customizer = Some(Arc::new(customize));
        self
    }

    /// Generate this application's explicit contract without opening a database connection.
    pub fn openapi(&self) -> Result<crate::ApiDocument> {
        let config = self
            .config
            .clone()
            .map(Ok)
            .unwrap_or_else(AppConfig::load_for_contracts)?;
        self.api_document(&config)
    }

    /// Export while rejecting undocumented public API routes, independent of config defaults.
    pub fn openapi_strict(&self) -> Result<crate::ApiDocument> {
        let mut config = self
            .config
            .clone()
            .map(Ok)
            .unwrap_or_else(AppConfig::load_for_contracts)?;
        config.api.require_documented_routes = true;
        self.api_document(&config)
    }

    fn api_document(&self, config: &AppConfig) -> Result<crate::ApiDocument> {
        #[cfg(feature = "mail")]
        self.validate_mail(config)?;
        #[cfg(feature = "jobs")]
        if let Some(jobs) = &self.jobs {
            jobs.validate()?;
        }
        let mut routes = vec![("", &self.routes)];
        if let Some(api) = &self.api_routes {
            routes.push(("/api", api));
        }
        if config.api.require_documented_routes {
            for (prefix, routes) in &routes {
                routes.require_documented(prefix)?;
            }
        }
        #[cfg(feature = "auth")]
        let auth_routes = self.auth_routes();
        #[cfg(feature = "auth")]
        if let Some(delivery) = &self.verification_delivery {
            if self.auth_delivery.is_none() {
                return Err(AppError::Configuration(
                    "Enable App::auth before email verification.".into(),
                ));
            }
            if config.app.environment == "production" && delivery.development_only() {
                return Err(AppError::Configuration(
                    "Install a production email verification delivery adapter.".into(),
                ));
            }
        }
        #[cfg(feature = "auth")]
        if let Some(delivery) = &self.auth_delivery {
            let production = config.app.environment == "production";
            config.auth.validate(production)?;
            config.http.client_ip.validate()?;
            if production && delivery.development_only() {
                return Err(AppError::Configuration("Install an application-owned password reset delivery adapter before enabling auth in production.".into()));
            }
            routes.push(("/api/auth", &auth_routes));
        }
        let mut document = crate::ApiDocument::from_routes(
            config.api.title.as_deref().unwrap_or(&config.app.name),
            &config.api.version,
            routes,
        )?;
        #[cfg(feature = "auth")]
        if self.auth_delivery.is_some() {
            document.as_value_mut()["components"]["securitySchemes"]["session"] = crate::serde_json::json!({
                "type": "apiKey", "in": "cookie",
                "name": config.auth.cookie_name(config.app.environment == "production")
            });
            if let Some(paths) = document.as_value_mut()["paths"].as_object_mut() {
                for (path, methods) in paths {
                    if let Some(methods) = methods.as_object_mut() {
                        for (method, operation) in methods {
                            let mutation =
                                matches!(method.as_str(), "post" | "put" | "patch" | "delete");
                            let bootstrap = path == "/api/auth/csrf" && method == "get";
                            if mutation || bootstrap {
                                if operation.get("parameters").is_none() {
                                    operation["parameters"] = crate::serde_json::json!([]);
                                }
                                operation["parameters"].as_array_mut().expect("generated parameter array").push(crate::serde_json::json!({
                                    "name": if bootstrap { "X-Capy-CSRF" } else { "X-CSRF-Token" },
                                    "in": "header", "required": true,
                                    "description": if bootstrap { "Send 1 to bootstrap a same-origin CSRF session." } else { "Synchronizer token from GET /api/auth/csrf; never a session secret." },
                                    "schema": {"type": "string"}
                                }));
                                operation["responses"]["403"] = crate::serde_json::json!({"description": "CSRF or policy rejection", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ApiErrorResponse"}}}});
                            }
                        }
                    }
                }
            }
        }
        if let Some(customize) = &self.openapi_customizer {
            customize(&mut document);
        }
        Ok(document)
    }

    /// Install an application-owned, nonblocking response observer for telemetry.
    pub fn observe_requests(mut self, observer: impl crate::RequestObserver) -> Self {
        self.observer = Some(Arc::new(observer));
        self
    }

    /// Override the response-header deadline for a full matched route template,
    /// such as `/api/events` or `/api/posts/{id}`. `None` intentionally disables
    /// it. Response body streaming is never subject to this header deadline.
    pub fn request_timeout_for(
        mut self,
        route: impl Into<String>,
        timeout: Option<Duration>,
    ) -> Self {
        self.request_timeouts.insert(route.into(), timeout);
        self
    }

    /// Mount API routes under `/api`, preserving JSON errors within that namespace.
    /// Declare paths such as `/posts` without repeating the prefix.
    pub fn api_routes(mut self, routes: Routes) -> Self {
        self.api_routes = Some(routes);
        self
    }

    /// Serve built frontend assets and use index.html for non-API browser routes.
    /// The path is relative to the application's working directory. Production
    /// startup requires a readable index.html; development may use Vite instead.
    pub fn frontend(mut self, directory: impl Into<PathBuf>) -> Self {
        self.frontend = Some(directory.into());
        self
    }

    /// Set the application's routes.
    pub fn routes(mut self, routes: Routes) -> Self {
        self.routes = routes;
        self
    }

    /// Use explicit typed configuration, useful for tests and embedded apps.
    pub fn config(mut self, config: AppConfig) -> Self {
        self.config = Some(config);
        self
    }

    /// Register a native SeaORM migrator for the application's CLI commands.
    /// Serving never applies migrations implicitly.
    pub fn migrations<N: MigratorTrait>(self, _migrator: N) -> App<N> {
        App {
            services: self.services,
            seeds: self.seeds,
            events: self.events,
            routes: self.routes,
            api_routes: self.api_routes,
            frontend: self.frontend,
            config: self.config,
            request_timeouts: self.request_timeouts,
            observer: self.observer,
            openapi_customizer: self.openapi_customizer,
            #[cfg(feature = "auth")]
            auth_delivery: self.auth_delivery,
            #[cfg(feature = "auth")]
            verification_delivery: self.verification_delivery,
            #[cfg(feature = "jobs")]
            jobs: self.jobs,
            #[cfg(feature = "scheduler")]
            schedules: self.schedules,
            #[cfg(feature = "scheduler")]
            tasks: self.tasks,
            #[cfg(feature = "mail")]
            mail_enabled: self.mail_enabled,
            #[cfg(feature = "mail")]
            mailer: self.mailer,
            migrations: PhantomData,
        }
    }

    /// Build a service using an existing context, without binding a TCP port.
    /// The returned Axum router can be tested or served with native tooling.
    pub fn into_router(self, context: AppContext) -> axum::Router {
        let services = self.resolved_services(&context.config);
        self.into_router_with_services(context, services)
    }

    fn into_router_with_services(
        self,
        context: AppContext,
        services: Result<Services>,
    ) -> axum::Router {
        #[cfg(feature = "auth")]
        let auth_routes = self.auth_routes();
        #[cfg(feature = "mail")]
        let mailer = self.configured_mailer(&context.config);
        let events = self
            .events
            .clone()
            .with_services(services.as_ref().cloned().unwrap_or_default());
        let docs_enabled =
            context.config.api.docs && context.config.app.environment != "production";
        let schema = (context.config.api.openapi || docs_enabled).then(|| {
            self.api_document(&context.config)
                .map(|doc| doc.as_value().clone())
        });
        let http = context.config.http.clone();
        let policy = crate::http_policy::HttpPolicy {
            default_timeout: (http.request_timeout_seconds != 0)
                .then(|| Duration::from_secs(http.request_timeout_seconds)),
            overrides: self.request_timeouts,
        };
        let mut router = self.routes.into_router();
        if let Some(api) = self.api_routes {
            router = router.nest("/api", api.into_router());
        }
        #[cfg(feature = "auth")]
        let auth = self.auth_delivery.map(|delivery| {
            capy_auth::AuthService::new(context.clone(), delivery).and_then(|service| {
                let service = service.with_events(events.clone());
                match self.verification_delivery {
                    Some(delivery) => service.with_email_verification(delivery),
                    None => Ok(service),
                }
            })
        });
        #[cfg(feature = "auth")]
        if auth.is_some() {
            router = router.nest("/api/auth", auth_routes.into_router());
        }
        if let Some(schema) = schema {
            // run_command reports generation errors before binding; native into_router
            // callers receive the same sanitized HTTP envelope if their metadata is invalid.
            let schema = Arc::new(schema.map_err(|error| error.to_string()));
            router = router.route(
                "/openapi.json",
                axum::routing::get(move || {
                    let schema = schema.clone();
                    async move {
                        match schema.as_ref() {
                            Ok(document) => Ok(axum::Json(document.clone())),
                            Err(_) => Err(AppError::Configuration(
                                "Invalid API contract. Run capy openapi to inspect the error."
                                    .into(),
                            )),
                        }
                    }
                }),
            );
        }
        if docs_enabled {
            router = router.route(
                "/docs/api",
                axum::routing::get(|| async {
                    axum::response::Html(include_str!("api_docs.html"))
                }),
            );
        }
        if let Some(directory) = self.frontend {
            router =
                router.fallback(move |request| crate::frontend::serve(directory.clone(), request));
        }
        let mut router = router.with_state(context).layer(axum::Extension(events));
        match services {
            Ok(services) => router = router.layer(axum::Extension(services)),
            Err(_) => {
                router = axum::Router::new().fallback(|| async {
                    AppError::Configuration("Invalid application services. Run capy check.".into())
                })
            }
        }
        #[cfg(feature = "mail")]
        match mailer {
            Ok(Some(mailer)) => router = router.layer(axum::Extension(mailer)),
            Ok(None) => {}
            Err(_) => {
                router = axum::Router::new().fallback(|| async {
                    AppError::Configuration("Invalid mail configuration. Run capy check.".into())
                })
            }
        }

        #[cfg(feature = "auth")]
        if let Some(service) = auth {
            router = match service {
                Ok(service) => service.protect(router),
                Err(_) => axum::Router::new().fallback(|| async {
                    AppError::Configuration("Invalid auth configuration. Run capy check.".into())
                }),
            };
        }
        // Auth extraction and CSRF database work remain inside the existing deadline.
        router = router
            .layer(axum::extract::DefaultBodyLimit::max(http.max_body_bytes))
            .layer(axum::middleware::from_fn_with_state(
                policy,
                crate::http_policy::deadline,
            ));
        if http.compression {
            router = router.layer(tower_http::compression::CompressionLayer::new());
        }
        router
            .layer(axum::middleware::from_fn_with_state(
                self.observer,
                crate::diagnostics::request,
            ))
            .layer(
                tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer::new([
                    axum::http::header::AUTHORIZATION,
                    axum::http::header::COOKIE,
                    axum::http::HeaderName::from_static("x-csrf-token"),
                ]),
            )
            .layer(
                tower_http::sensitive_headers::SetSensitiveResponseHeadersLayer::new([
                    axum::http::header::SET_COOKIE,
                ]),
            )
    }

    /// Serve by default, or execute the command forwarded by `capy`.
    /// Supported arguments: `serve`, `check`, `routes`, `migrate`, `migrate:rollback`,
    /// and `migrate:status`. With jobs enabled, `queue:work` accepts `--queue` and
    /// `--concurrency`; `queue:failed`, `queue:retry UUID`, `queue:forget UUID` and
    /// `queue:check` share the same binary. Migrations are explicit; rollback reverts one.
    pub async fn run(self) -> Result<()> {
        let mut args = std::env::args().skip(1);
        let command = args.next().unwrap_or_else(|| "serve".into());
        #[cfg(feature = "jobs")]
        if command.starts_with("queue:") {
            return self
                .run_queue_command(&command, &args.collect::<Vec<_>>())
                .await;
        }
        #[cfg(feature = "scheduler")]
        if command == "task:run" {
            let name = args.next().ok_or_else(|| {
                AppError::Configuration("task:run requires a registered task name.".into())
            })?;
            if args.next().is_some() {
                return Err(AppError::Configuration(
                    "task:run accepts exactly one task name.".into(),
                ));
            }
            return self.run_task(&name).await;
        }
        #[cfg(feature = "mail")]
        if matches!(command.as_str(), "mail:list" | "mail:show" | "mail:clear") {
            let config = self
                .config
                .clone()
                .map(Ok)
                .unwrap_or_else(AppConfig::load_for_contracts)?;
            return crate::mail_commands::run(&config, &command, &args.collect::<Vec<_>>());
        }
        if args.next().is_some() {
            return Err(AppError::Configuration(
                "Unexpected arguments. Use the capy CLI for application commands.".into(),
            ));
        }
        self.run_command(&command).await
    }

    #[cfg(feature = "jobs")]
    async fn run_queue_command(self, command: &str, args: &[String]) -> Result<()> {
        let config = self
            .config
            .clone()
            .map(Ok)
            .unwrap_or_else(AppConfig::load)?;
        #[cfg(feature = "mail")]
        let mailer = self.configured_mailer(&config)?;
        let services = self.resolved_services(&config)?;
        let jobs = self.jobs;
        #[cfg(feature = "mail")]
        let jobs = if let Some(mailer) = mailer {
            Some(capy_mail::register_jobs(jobs.unwrap_or_default(), mailer))
        } else {
            jobs
        };
        let jobs = jobs.ok_or_else(|| {
            AppError::Configuration(
                "Register jobs with App::jobs (capy make:job installs the conventional registry)."
                    .into(),
            )
        })?;
        crate::job_commands::run(command, args, config, jobs, services).await
    }

    #[cfg(feature = "scheduler")]
    async fn run_task(self, name: &str) -> Result<()> {
        let config = self
            .config
            .clone()
            .map(Ok)
            .unwrap_or_else(AppConfig::load)?;
        config.validate()?;
        let services = self.resolved_services(&config)?;
        let db = capy_db::connect(&config.database).await?;
        self.tasks
            .run(
                name,
                AppContext {
                    db,
                    config: Arc::new(config),
                },
                services,
            )
            .await
    }

    #[cfg(feature = "scheduler")]
    async fn run_scheduler(self) -> Result<()> {
        let config = self
            .config
            .clone()
            .map(Ok)
            .unwrap_or_else(AppConfig::load)?;
        config.validate()?;
        config.jobs.validate_database(&config.database)?;
        let jobs = self.jobs.as_ref().ok_or_else(|| {
            AppError::Configuration(
                "Register scheduled jobs with App::jobs before running the scheduler.".into(),
            )
        })?;
        self.schedules.validate_jobs(jobs)?;
        let db = capy_db::connect(&config.database).await?;
        let context = AppContext {
            db,
            config: Arc::new(config),
        };
        capy_jobs::scheduler::Scheduler::new(context, self.schedules)
            .run(async {
                let _ = tokio::signal::ctrl_c().await;
            })
            .await
    }

    /// Run a specific application command without reading process arguments.
    pub async fn run_command(self, command: &str) -> Result<()> {
        let command = match command {
            "db:migrate" => "migrate",
            "db:rollback" => "migrate:rollback",
            "db:status" => "migrate:status",
            command => command,
        };
        #[cfg(feature = "jobs")]
        if command.starts_with("queue:") {
            return self.run_queue_command(command, &[]).await;
        }
        #[cfg(feature = "scheduler")]
        if command == "scheduler:run" {
            return self.run_scheduler().await;
        }
        #[cfg(feature = "scheduler")]
        if command == "task:list" {
            for name in self.tasks.names() {
                println!("{name}");
            }
            return Ok(());
        }
        #[cfg(feature = "mail")]
        if command == "mail:check" {
            let config = self
                .config
                .clone()
                .map(Ok)
                .unwrap_or_else(AppConfig::load_for_contracts)?;
            if !self.mail_enabled {
                return Err(AppError::Configuration(
                    "Enable mail with App::mail.".into(),
                ));
            }
            self.validate_mail(&config)?;
            println!("Mail: configuration and compiled templates valid. No DNS, authentication or delivery attempted.");
            return Ok(());
        }
        if matches!(command, "__capy_contract" | "__capy_contract_strict") {
            let document = if command == "__capy_contract_strict" {
                self.openapi_strict()?
            } else {
                self.openapi()?
            };
            print!("{}", document.to_json()?);
            return Ok(());
        }
        if command == "routes:api" {
            // Also validate incomplete/duplicate metadata before showing the inventory.
            self.openapi()?;
            for (prefix, routes) in std::iter::once(("", &self.routes))
                .chain(self.api_routes.as_ref().map(|r| ("/api", r)))
            {
                for route in routes.api_inventory() {
                    println!(
                        "{:<7} {:<28} {:<22} {}",
                        route.method,
                        format!("{prefix}{}", route.path),
                        route.operation_id.unwrap_or_default(),
                        route.response.unwrap_or_default()
                    );
                }
            }
            #[cfg(feature = "auth")]
            if self.auth_delivery.is_some() {
                for route in self.auth_routes().api_inventory() {
                    println!(
                        "{:<7} {:<28} {:<22} {}",
                        route.method,
                        format!("/api/auth{}", route.path),
                        route.operation_id.unwrap_or_default(),
                        route.response.unwrap_or_default()
                    );
                }
            }
            return Ok(());
        }
        if command == "routes" {
            for route in self.routes.inventory() {
                println!("{:<7} {}", route.method, route.path);
            }
            if let Some(api) = &self.api_routes {
                for route in api.inventory() {
                    println!("{:<7} /api{}", route.method, route.path);
                }
            }
            #[cfg(feature = "auth")]
            if self.auth_delivery.is_some() {
                for route in self.auth_routes().inventory() {
                    println!("{:<7} /api/auth{}", route.method, route.path);
                }
            }
            return Ok(());
        }
        if !matches!(
            command,
            "serve"
                | "check"
                | "migrate"
                | "migrate:rollback"
                | "migrate:status"
                | "auth:prune"
                | "db:seed"
        ) {
            return Err(AppError::Configuration(format!(
                "Unknown application command: {command}"
            )));
        }
        let config = match &self.config {
            Some(config) => config.clone(),
            None => AppConfig::load()?,
        };
        config.validate()?;
        if matches!(command, "serve" | "check") {
            #[cfg(feature = "storage")]
            if command == "serve" {
                self.resolved_services(&config)?;
            }
            #[cfg(not(feature = "storage"))]
            if config.storage.driver != "none" {
                return Err(AppError::Configuration(
                    "Storage is configured but the capy storage feature is disabled.".into(),
                ));
            }
            #[cfg(all(feature = "storage", not(feature = "storage-s3")))]
            if config.storage.driver == "s3" {
                return Err(AppError::Configuration(
                    "S3 storage requires the capy storage-s3 feature.".into(),
                ));
            }
        }
        if command == "db:seed" {
            capy_db::Seeds::validate_environment(&config)?;
            let seeds = self.seeds.ok_or_else(|| {
                AppError::Configuration(
                    "Register application-owned seeds with App::seeds before running db:seed."
                        .into(),
                )
            })?;
            let db = capy_db::connect(&config.database).await?;
            let context = AppContext {
                db,
                config: Arc::new(config),
            };
            seeds.run(&context).await?;
            println!("Development seeds committed. Migrations were not run automatically.");
            return Ok(());
        }
        // Validate declared contracts before starting HTTP or approving configuration.
        if matches!(command, "serve" | "check") {
            self.api_document(&config)?;
        }
        if command == "check" || (command == "serve" && config.app.environment == "production") {
            if let Some(directory) = &self.frontend {
                crate::frontend::validate(directory)?;
            }
        }
        if command == "check" {
            #[cfg(feature = "auth")]
            if self.auth_delivery.is_some()
                && config.app.environment == "production"
                && !config.auth.throttle.enabled
            {
                // Offline check has no tracing subscriber. Keep its warning visible
                // without contaminating JSON contract export on stdout.
                eprintln!("Warning [auth.throttle.disabled]: built-in auth abuse limits are disabled; enforce equivalent deployment-level protection.");
            }
            #[cfg(feature = "jobs")]
            {
                let jobs_enabled = self.jobs.is_some();
                #[cfg(feature = "mail")]
                let jobs_enabled = jobs_enabled || self.mail_enabled;
                if jobs_enabled {
                    config.jobs.validate_database(&config.database)?;
                }
            }
            #[cfg(feature = "scheduler")]
            if self.schedules.names().next().is_some() {
                let jobs = self.jobs.as_ref().ok_or_else(|| {
                    AppError::Configuration("Registered schedules require App::jobs.".into())
                })?;
                self.schedules.validate_jobs(jobs)?;
            }
            let migrations = M::migrations();
            let mut names = std::collections::BTreeSet::new();
            for migration in &migrations {
                if !names.insert(migration.name()) {
                    return Err(AppError::Configuration(
                        "Duplicate registered migration name.".into(),
                    ));
                }
            }
            println!(
                "Configuration valid; {} migrations registered. No database connection opened.",
                migrations.len()
            );
            return Ok(());
        }
        if command == "auth:prune" {
            #[cfg(feature = "auth")]
            if self.auth_delivery.is_some() {
                let db = capy_db::connect(&config.database).await?;
                let mut count = capy_auth::prune(&db).await?;
                if self.verification_delivery.is_some() {
                    count += capy_auth::verification::prune(&db).await?;
                }
                println!("Pruned {count} expired auth records.");
                return Ok(());
            }
            return Err(AppError::Configuration(
                "Install auth with capy make:auth before pruning.".into(),
            ));
        }
        init_logging(&config);
        let db = capy_db::connect(&config.database).await?;
        match command {
            "migrate" => {
                M::up(&db, None).await?;
                println!("Migrations applied.");
            }
            "migrate:rollback" => {
                M::down(&db, Some(1)).await?;
                println!("Rolled back the latest migration.");
            }
            "migrate:status" => {
                let statuses = capy_db::status::<M>(&db).await?;
                if statuses.is_empty() {
                    println!("No migrations registered.");
                }
                for status in statuses {
                    println!(
                        "{:<8} {}",
                        if status.applied { "Applied" } else { "Pending" },
                        status.name
                    );
                }
            }
            _ => {
                let listener =
                    tokio::net::TcpListener::bind((config.host(), config.port())).await?;
                let address = listener.local_addr()?;
                if config.app.environment == "production" {
                    tracing::info!(%address, environment = %config.app.environment, "Capy ready");
                } else if std::env::var_os("CAPY_DEV").is_some() {
                    println!(
                        "✓ Database connected\n✓ Backend ready\nServer running on http://{address}"
                    );
                } else {
                    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.",
                        env!("CARGO_PKG_VERSION"), config.app.environment,
                        if config.database.url.starts_with("sqlite:") { "SQLite" } else { "PostgreSQL" });
                }
                let shutdown_timeout = Duration::from_secs(config.server.shutdown_timeout_seconds);
                let context = AppContext {
                    config: Arc::new(config),
                    db,
                };
                serve(
                    listener,
                    self.into_router(context),
                    shutdown_timeout,
                    shutdown_signal(),
                )
                .await?;
            }
        }
        Ok(())
    }
}

// axum-server owns connection cancellation. Merely dropping axum::serve's
// graceful future leaves its detached connection tasks running in shared runtimes.
pub(crate) async fn serve(
    listener: tokio::net::TcpListener,
    router: axum::Router,
    timeout: Duration,
    signal: impl std::future::Future<Output = ()>,
) -> Result<()> {
    let handle = axum_server::Handle::new();
    let server = axum_server::from_tcp(listener.into_std()?)?
        .handle(handle.clone())
        .serve(router.into_make_service_with_connect_info::<std::net::SocketAddr>());
    tokio::pin!(server);
    tokio::select! {
        result = &mut server => { result?; }
        () = signal => {
            tracing::info!("shutdown requested");
            handle.graceful_shutdown(None);
            tracing::info!("waiting for active requests");
            match tokio::time::timeout(timeout, &mut server).await {
                Ok(result) => result?,
                Err(_) => {
                    tracing::warn!("shutdown deadline reached");
                    handle.shutdown();
                    server.await?;
                }
            }
        }
    }
    tracing::info!("server stopped");
    Ok(())
}

pub(crate) fn init_logging(config: &AppConfig) {
    let filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new(crate::diagnostics::DEFAULT_FILTER));
    if config.app.environment != "production"
        && std::env::var("CAPY_DEV_LOG").is_ok_and(|value| value == "1")
    {
        let _ = tracing_subscriber::fmt()
            .with_env_filter(filter)
            .with_ansi(false)
            .json()
            .with_writer(crate::dev_logging::writer)
            .try_init();
    } else if config.app.environment == "production" {
        let _ = tracing_subscriber::fmt()
            .with_env_filter(filter)
            .json()
            .try_init();
    } else {
        let _ = tracing_subscriber::fmt()
            .with_env_filter(filter)
            .compact()
            .try_init();
    }
}

pub(crate) async fn shutdown_signal() {
    let ctrl_c = async {
        let _ = tokio::signal::ctrl_c().await;
    };
    #[cfg(unix)]
    let terminate = async {
        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
            Ok(mut stream) => {
                stream.recv().await;
            }
            Err(_) => std::future::pending::<()>().await,
        }
    };
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();
    tokio::select! { () = ctrl_c => {}, () = terminate => {} }
}