laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
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
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
//! The application: configuring, building, and running it.
//!
//! Every Laravel application starts in `src/app.rs` with [`Application::configure`]. The
//! [`ApplicationBuilder`] it returns collects your providers, routes, middleware, and other
//! settings. [`run`](ApplicationBuilder::run) then serves the application or runs a console
//! command, and [`create`](ApplicationBuilder::create) builds the application for tests. A
//! package registers services and routes of its own with a [`ServiceProvider`].
//!
//! To learn more, check out the
//! [request lifecycle guide](https://github.com/laravel/rust-framework/blob/0.x/docs/lifecycle.md)
//! and the [package development guide](https://github.com/laravel/rust-framework/blob/0.x/docs/packages.md).

mod boot;
mod commands;
mod connections;
mod console;
mod inspiring;
pub(crate) use crate::console::signals::shutdown_signal;
mod kernel;
pub(crate) mod logging;
#[cfg(feature = "opentelemetry")]
pub(crate) mod opentelemetry;
mod provider;
mod providers;
pub(crate) use laravel_core::foundation::{cloud, shutdown, telemetry};

use crate::cache::CacheManagerInternals as _;
use crate::console::ConsoleInternals as _;
use crate::schedule::ScheduleInternals as _;
use std::future::Future;
use std::path::Path;
use std::process::ExitCode;
use std::sync::{Arc, Mutex, Weak};

use futures_util::FutureExt;

pub(crate) use self::boot::Boot;
pub use self::inspiring::Inspiring;
use self::kernel::Kernel;
pub(crate) use self::kernel::RecordRoot;
pub use self::logging::{LogGuard, LogLayers, LoggingError};
pub use self::provider::{Providers, ServiceProvider};
pub(crate) use self::shutdown::Shutdown;
use crate::cache::CacheManager;
use crate::clock::Clock;
use crate::config::{Config, Env, EnvInternals as _, InvalidEnv};
use crate::console::{Commands, CommandsInternals as _};
use crate::container::{CallbackResult, Container, Inject, Registrar, Services};
use crate::context::{App, Context, Internals};
use crate::crypt::{Cipher, Encrypter, KeyError};
use crate::error::Result;
use crate::errors::{ErrorHandler, Errors, ResponseBoundary};
use crate::event::Dispatcher;
use crate::head::HeadConfig;
use crate::http::MiddlewareConfig;
use crate::queue::QueueManagerInternals as _;
use crate::routing::assets::Assets;
use crate::routing::{RouteTable, Routing, table};
use crate::schedule::Schedule;
use crate::task::Ticks;
use crate::view::{ViewConfig, ViewConfigInternals as _};
#[doc(inline)]
pub use laravel_core::foundation::Host;

/// Returns the kind of process that runs the application.
///
/// Returns `None` in one-off console commands, such as `migrate` or `schedule:run`, and in tests.
/// The [`Host`] example shows how to check it.
///
/// # Panics
///
/// Panics outside an application context.
#[must_use]
#[track_caller]
pub fn host() -> Option<Host> {
    Context::expect("laravel::foundation::host()").host().cloned()
}

/// A built application, with its configuration, services, routes, and providers.
///
/// Clones of an application share the same configuration, services, routes, and providers.
///
/// ```no_run
/// use std::process::ExitCode;
///
/// use laravel::Application;
/// use laravel::routing::Router;
///
/// fn web(route: &mut Router) {
///     route.get("/", || async { "Hello from Laravel for Rust" });
/// }
///
/// fn main() -> ExitCode {
///     Application::configure()
///         .with_routing(|routing, _| {
///             routing.web(web);
///         })
///         .run()
/// }
/// ```
///
/// [`Application::run`] serves the application, or runs a console command such as
/// `route:list`. In tests, send requests to the application directly with `get` and the other
/// request methods of [`MakesHttpRequests`](crate::testing::MakesHttpRequests).
#[derive(Debug, Clone)]
pub struct Application {
    router: axum::Router,
    shared: Arc<App>,
    providers: Providers,
    /// The layers that [`init_logging`](Self::init_logging) installs, until it takes them.
    log_layers: Arc<Mutex<Option<LogLayers>>>,
    dotenv: DotEnv,
}

impl Application {
    /// Start configuring an application.
    ///
    /// The application reads its configuration from the environment and `.env` when it's created.
    pub fn configure() -> ApplicationBuilder {
        ApplicationBuilder {
            env: None,
            env_vars: Vec::new(),
            config_files: Vec::new(),
            registrations: Vec::new(),
            booted: Vec::new(),
            providers: Providers::default(),
            framework_providers: provider::framework(),
        }
    }

    /// Boot the application by running every provider's `boot` hook, then the application's
    /// `booted` callbacks.
    ///
    /// Booting doesn't build services. Each service is built the first time something resolves it.
    /// Serving the application boots it first, and so does the first test request. Call `boot`
    /// yourself when you serve the application from [`Application::into_router`].
    ///
    /// The application boots once, and later calls return the result of the first boot.
    ///
    /// # Errors
    ///
    /// Returns an error when a boot hook fails, when a service that a hook resolves fails to build,
    /// or when the default cache store isn't defined after every provider and `booted` callback has
    /// run.
    pub async fn boot(&self) -> Result<()> {
        self.shared.part::<Boot>().run().await
    }

    /// Run work inside the application, the way the application runs a request.
    ///
    /// Helpers such as [`resolve`](crate::resolve), [`url::route`](crate::url::route), and
    /// [`once`](crate::once()) work inside the async closure or function, and `once` keeps its
    /// results until the closure returns. There's no request, so URLs start with `APP_URL`, and
    /// request helpers such as [`laravel::cookie`](crate::cookie) aren't available.
    ///
    /// ```no_run
    /// # pub struct Teams;
    /// # impl Teams { async fn current(&self) -> Option<String> { None } }
    /// pub async fn current_team() -> laravel::Result<Option<String>> {
    ///     laravel::once(|| async { Ok(laravel::resolve::<Teams>().await?.current().await) }).await
    /// }
    ///
    /// # async fn test(app: laravel::Application) {
    /// let team = app.scope(current_team).await;
    /// # }
    /// ```
    ///
    /// `scope` boots the application first if it hasn't booted yet.
    ///
    /// # Panics
    ///
    /// Panics when the application fails to boot. To handle the error instead, call
    /// [`Application::boot`] first.
    pub async fn scope<T>(&self, callback: impl AsyncFnOnce() -> T) -> T {
        self.boot_or_panic().await;

        Context::new(Arc::clone(&self.shared), None).scope(callback()).await
    }

    /// Resolve one of the application's services, using its binding's lifetime.
    ///
    /// Use this in code that holds the application instead of handling a request, such as a test
    /// that seeds data.
    ///
    /// ```no_run
    /// # pub struct Posts;
    /// # impl Posts { async fn create(&self, title: &str) {} }
    /// # async fn test(app: laravel::Application) {
    /// let posts = app.resolve::<Posts>().await;
    /// posts.create("Hello").await;
    /// # }
    /// ```
    ///
    /// `resolve` boots the application first if it hasn't booted yet. A singleton is built once,
    /// and a transient binding is built on every resolution. Resolving needs no scope. If a
    /// service's methods use helpers such as [`url::route`](crate::url::route),
    /// [`once`](crate::once()), or cache stores, call those methods inside [`scope`](Self::scope).
    /// Tests that take an `Application` argument already run in a scope.
    ///
    /// # Panics
    ///
    /// Panics when the application fails to boot, when no service provider registered the
    /// service, or when building the service fails.
    pub async fn resolve<T: ?Sized + Send + Sync + 'static>(&self) -> Inject<T> {
        self.boot_or_panic().await;

        match self.shared.services.resolve().await.map(Inject::from) {
            Ok(service) => service,
            Err(error) => panic!("{error:#}"),
        }
    }

    /// Run the [tick](crate::task::Ticks) named `name` once and return its result.
    ///
    /// The tick runs in a context of its own, the way the server runs it, without checking its
    /// [`when`](crate::task::Tick::when) condition. Ticks don't run on their own in tests, so call
    /// this to run one.
    ///
    /// # Errors
    ///
    /// Returns the tick's error, a panic in the tick as an error, or an error from resolving a
    /// service the tick injects.
    ///
    /// # Panics
    ///
    /// Panics if the application fails to boot, or if no tick has this name.
    ///
    /// ```
    /// use laravel::time::ToSpan;
    ///
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() -> laravel::Result<()> {
    /// let app = laravel::Application::configure()
    ///     .with_ticks(|ticks, _| {
    ///         ticks.every(1.minute(), || async {}).name("prune-cache");
    ///     })
    ///     .create();
    ///
    /// app.tick("prune-cache").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn tick(&self, name: &str) -> crate::Result<()> {
        self.boot_or_panic().await;

        match crate::task::ticks::run_named(&self.shared, name).await {
            Some(result) => result,
            None => panic!("no tick is named `{name}`"),
        }
    }

    /// Returns the kind of process that runs the application, as
    /// [`foundation::host`](crate::foundation::host) does inside it.
    ///
    /// Returns `None` until the server, a queue worker, or a command with the `with_ticks` option
    /// starts, and always in tests.
    #[must_use]
    pub fn host(&self) -> Option<Host> {
        self.shared.host.get().cloned()
    }

    async fn boot_or_panic(&self) {
        if let Err(error) = self.boot().await {
            panic!("the application failed to boot: {error:#}");
        }
    }

    /// The service providers the application registered, in order, without the framework's internal providers.
    #[must_use]
    pub const fn providers(&self) -> &Providers {
        &self.providers
    }

    /// The application's routes.
    #[must_use]
    pub fn routes(&self) -> &RouteTable {
        self.shared.part()
    }

    /// The application's configuration.
    #[must_use]
    pub fn config(&self) -> &Config {
        &self.shared.config
    }

    pub(crate) fn services(&self) -> &Services {
        &self.shared.services
    }

    pub(crate) fn clock(&self) -> &Clock {
        &self.shared.clock
    }

    #[cfg(feature = "database")]
    pub(crate) fn seed_faker_default(&self, name: &str) {
        self.shared.part::<crate::model::Factories>().seed_faker_default(name);
    }

    #[cfg(feature = "inertia")]
    pub(crate) fn head(&self) -> &HeadConfig {
        self.shared.part()
    }

    #[cfg(test)]
    pub(crate) fn begin_shutdown(&self) {
        self.shared.shutdown.begin();
    }

    #[cfg(test)]
    pub(crate) fn cut_off_requests(&self) {
        self.shared.shutdown.cut_off();
    }

    /// The application's encrypter, built from `APP_KEY`, `APP_CIPHER`, and `APP_PREVIOUS_KEYS`.
    ///
    /// # Errors
    ///
    /// Returns an error when the application has no encryption key, or when a key isn't valid for
    /// the cipher.
    pub fn encrypter(&self) -> Result<&Encrypter, KeyError> {
        self.shared.encrypter.as_ref().map_err(Clone::clone)
    }

    /// Convert the application into its Axum router, to serve the application yourself.
    ///
    /// Call [`boot`](Self::boot) before serving the router.
    pub fn into_router(self) -> axum::Router {
        self.router
    }

    pub(crate) const fn router(&self) -> &axum::Router {
        &self.router
    }

    /// The problems with the `#[laravel::auth::page(..)]` handlers.
    ///
    /// These problems stop the application from serving requests. Console commands run without
    /// checking them, so `migrate` works before the pages exist.
    pub(crate) fn check_auth_pages(&self) -> Result<(), StartupError> {
        match self.shared.part::<AuthProblems>().0.as_slice() {
            [] => Ok(()),
            problems => Err(StartupError::Auth(problems.to_vec())),
        }
    }
}

/// The `.env` file's variables, which [`Application::run`] exports to the process.
type DotEnv = Arc<[(String, String)]>;
type ConfigFile = Box<dyn FnOnce(&mut Config, &Env)>;
type Registration = Box<dyn FnOnce(&mut Registrar, &Config)>;

/// Configures an [`Application`].
#[must_use = "an application builder does nothing until `.create()` is called"]
pub struct ApplicationBuilder {
    env: Option<Env>,
    env_vars: Vec<(String, String)>,
    config_files: Vec<ConfigFile>,
    /// The application's own registrations, in the order it added them.
    ///
    /// They run after every provider's `register` hook and after the `app` crate's discovery.
    registrations: Vec<Registration>,
    booted: Vec<boot::Booted>,
    providers: Providers,
    framework_providers: Providers,
}

impl ApplicationBuilder {
    /// Read configuration from this environment alone, instead of the process's environment and
    /// `.env`.
    ///
    /// Use this in tests that need full control over the variables. To add variables instead, use
    /// [`with_env`](Self::with_env) or [`with_envs`](Self::with_envs).
    pub fn replace_env(mut self, env: Env) -> Self {
        self.env = Some(env);
        self
    }

    /// Configure the application for tests.
    ///
    /// Reads `.env.testing` in `base_path` when present, or `.env` in `base_path` otherwise,
    /// with process environment variables taking precedence over the file. Sets `APP_ENV` to
    /// `testing` and `APP_BASE_PATH` to `base_path`, and fills in fast, in-memory fallbacks for
    /// any of the variables below that aren't already set (including a generated `APP_KEY` when
    /// `APP_KEY` is unset or empty).
    ///
    /// ```
    /// use laravel::config::app::Environment;
    ///
    /// let app = laravel::Application::configure()
    ///     .for_testing(env!("CARGO_MANIFEST_DIR"))
    ///     .with_envs([("APP_NAME", "Bookings")])
    ///     .create();
    ///
    /// assert!(matches!(app.config().app.env, Environment::Testing));
    /// assert_eq!(app.config().app.name, "Bookings");
    /// ```
    ///
    /// | Variable | Fallback when unset |
    /// | --- | --- |
    /// | `APP_DEBUG` | `true` |
    /// | `APP_KEY` | A new key for each application |
    /// | `BCRYPT_ROUNDS` | `4` |
    /// | `BROADCAST_CONNECTION` | `discard` |
    /// | `CACHE_STORE` | `memory` |
    /// | `FEATURE_STORE` | `memory` |
    /// | `INERTIA_SSR` | `false` |
    /// | `MAIL_MAILER` | `log` |
    /// | `OTEL_SDK_DISABLED` | `true` |
    /// | `QUEUE_CONNECTION` | `sync` |
    /// | `SESSION_DRIVER` | `memory` |
    /// | `SMS_SENDER` | `log` |
    /// | `WORKFLOW_STORE` | `memory` |
    ///
    /// Because those entries are fallbacks, values set in `.env` or `.env.testing` take effect
    /// unless overridden with [`with_env`](Self::with_env) or [`with_envs`](Self::with_envs) (for
    /// example, in `src/testing.rs`).
    ///
    /// The `testing` environment also sends every queued job to the default connection, even a
    /// job that names its own, so queued work runs during the test.
    pub fn for_testing(self, base_path: impl AsRef<Path>) -> Self {
        let base_path = base_path.as_ref();
        let mut env = Env::from_testing_dir(base_path);
        env.set(vec![
            ("APP_ENV".to_owned(), "testing".to_owned()),
            ("APP_BASE_PATH".to_owned(), base_path.to_string_lossy().into_owned()),
        ]);
        if !env.is_set("APP_KEY") {
            env.set(vec![("APP_KEY".to_owned(), Encrypter::generate_key(Cipher::Aes256Cbc))]);
        }
        env.set_fallbacks([
            ("APP_DEBUG", "true"),
            ("BCRYPT_ROUNDS", "4"),
            ("BROADCAST_CONNECTION", "discard"),
            ("CACHE_STORE", "memory"),
            ("FEATURE_STORE", "memory"),
            ("INERTIA_SSR", "false"),
            ("MAIL_MAILER", "log"),
            ("OTEL_SDK_DISABLED", "true"),
            ("QUEUE_CONNECTION", "sync"),
            ("SESSION_DRIVER", "memory"),
            ("SMS_SENDER", "log"),
            ("WORKFLOW_STORE", "memory"),
        ]);

        self.replace_env(env)
    }

    /// Set an environment variable on top of the variables the application reads.
    ///
    /// The value replaces any variable with the same name, as [`with_envs`](Self::with_envs) does:
    ///
    /// ```
    /// let app = laravel::Application::configure()
    ///     .for_testing(env!("CARGO_MANIFEST_DIR"))
    ///     .with_env("APP_NAME", "Bookings")
    ///     .create();
    ///
    /// assert_eq!(app.config().app.name, "Bookings");
    /// ```
    pub fn with_env(self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.with_envs([(key, value)])
    }

    /// Set environment variables on top of the variables the application reads.
    ///
    /// Each value replaces any variable with the same name. The values apply to whichever
    /// environment the application reads, whether that's the one from
    /// [`for_testing`](Self::for_testing), the one from [`replace_env`](Self::replace_env), or the
    /// process's environment and `.env`. The order of the calls doesn't matter:
    ///
    /// ```
    /// use laravel::config::Env;
    ///
    /// let app = laravel::Application::configure()
    ///     .with_envs([("APP_DEBUG", "true")])
    ///     .replace_env(Env::from_iter([("APP_DEBUG", "false")]))
    ///     .create();
    ///
    /// assert!(app.config().app.debug);
    /// ```
    pub fn with_envs<K: Into<String>, V: Into<String>>(mut self, vars: impl IntoIterator<Item = (K, V)>) -> Self {
        self.env_vars
            .extend(vars.into_iter().map(|(key, value)| (key.into(), value.into())));
        self
    }

    /// Adjust the configuration read from the environment.
    ///
    /// The callbacks run after every service provider has set its config defaults and after the
    /// application's [`#[config::section]`](macro@crate::config::section) functions, so they can
    /// replace both. They run before providers register services.
    pub fn with_config(mut self, configure: impl FnOnce(&mut Config, &Env) + 'static) -> Self {
        self.config_files.push(Box::new(configure));
        self
    }

    /// Add service providers, from packages or the application itself.
    ///
    /// The providers run in the order you add them, after the framework's internal providers.
    pub fn with_providers(mut self, configure: impl FnOnce(&mut Providers)) -> Self {
        configure(&mut self.providers);
        self
    }

    /// Register the application's services, as a provider's `register` hook does.
    ///
    /// The callback runs after every service provider has registered its services, and after
    /// Laravel discovers the `app` crate's [`#[singleton]`](crate::container::singleton) and
    /// [`#[bind]`](crate::container::bind) services. Registering one of those types again replaces
    /// it. Register drivers here too, such as [cache drivers](crate::cache::Drivers) with
    /// `app.cache().extend(..)`.
    ///
    /// ```
    /// use laravel::Application;
    /// # pub struct Clock;
    /// # impl Clock { fn system() -> Self { Clock } }
    ///
    /// Application::configure()
    ///     .with_services(|app| {
    ///         app.instance(Clock::system());
    ///     })
    ///     # ;
    /// ```
    pub fn with_services(self, register: impl FnOnce(&mut Registrar) + 'static) -> Self {
        self.registration(|app, _| register(app))
    }

    /// Register event listeners with the final configuration.
    ///
    /// The callback runs after every provider's registrations and after Laravel discovers the
    /// tagged listeners in the `app` crate. Listeners run in the order they're registered.
    ///
    /// ```
    /// use laravel::{Application, event::Event};
    /// struct OrderPlaced;
    /// async fn record(_: Event<OrderPlaced>) {}
    /// Application::configure().with_events(|events, _| { events.listen(record); });
    /// ```
    pub fn with_events(self, configure: impl FnOnce(&mut Dispatcher, &Config) + 'static) -> Self {
        self.registration(|app, config| configure(app.events(), config))
    }

    /// Register the application's [session guard](crate::auth::AuthConfig), which logs users in and out.
    ///
    /// ```
    /// # use laravel::auth::{Authenticatable, UserProvider};
    /// # use laravel::hash::PasswordHash;
    /// # #[derive(Clone)] struct User;
    /// # impl Authenticatable for User {
    /// #     type Id = u64;
    /// #     fn auth_id(&self) -> u64 { 1 }
    /// #     fn auth_password(&self) -> Option<&PasswordHash> { None }
    /// #     fn remember_token(&self) -> Option<&str> { None }
    /// # }
    /// # struct Users;
    /// # impl UserProvider for Users {
    /// #     type User = User;
    /// #     async fn find(&self, _: &u64) -> laravel::Result<Option<User>> { Ok(None) }
    /// #     async fn find_for_login(&self, _: &str) -> laravel::Result<Option<User>> { Ok(None) }
    /// #     async fn update_password(&self, _: &User, _: &PasswordHash) -> laravel::Result<()> { Ok(()) }
    /// #     async fn update_remember_token(&self, _: &User, _: &str) -> laravel::Result<()> { Ok(()) }
    /// # }
    /// laravel::Application::configure().with_auth(|auth, _| {
    ///     auth.session::<Users>();
    /// });
    /// ```
    pub fn with_auth(self, configure: impl FnOnce(&mut crate::auth::AuthConfig, &Config) + 'static) -> Self {
        self.registration(|app, config| configure(&mut app.auth, config))
    }

    /// Validate shared services and initialize integrations when the application boots.
    ///
    /// The callbacks run once, in registration order, after every provider's `boot` hook. Resolving
    /// a service in a callback builds the service if it isn't built yet, so configure services in
    /// their factories rather than here.
    ///
    /// A callback's future returns nothing, or a [`laravel::Result`](crate::Result) when it can
    /// fail. An error stops the application from booting.
    ///
    /// ```
    /// use laravel::Application;
    /// # pub struct Search;
    /// # impl Search { fn validate(&self) -> laravel::Result<()> { Ok(()) } }
    ///
    /// Application::configure()
    ///     .booted(|app| async move {
    ///         app.resolve::<Search>().await?.validate()?;
    ///         Ok(())
    ///     })
    ///     # ;
    /// ```
    pub fn booted<F, Fut, R>(mut self, booted: F) -> Self
    where
        F: FnOnce(Container) -> Fut + Send + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: CallbackResult + 'static,
    {
        self.booted
            .push(Box::new(|app| Box::pin(booted(app).map(CallbackResult::into_result))));
        self
    }

    /// Register the route files and the health check.
    ///
    /// The callback runs after every service provider has added its routes. It receives the final
    /// configuration, so it can decide which routes to add.
    pub fn with_routing(self, configure: impl FnOnce(&mut Routing, &Config) + 'static) -> Self {
        self.registration(|app, config| configure(app.routing(), config))
    }

    /// Configure global middleware and the `web` and `api` groups.
    ///
    /// The callback runs after every service provider has added its middleware, so it can remove
    /// middleware a provider added. It receives the final configuration, so it can decide which
    /// middleware to add.
    ///
    /// ```
    /// use laravel::Application;
    /// # use laravel::http::{Middleware, Next, Response};
    /// # struct Debugbar;
    /// # impl Middleware for Debugbar {
    /// #     async fn handle(&self, request: laravel::http::Request, next: Next) -> laravel::Result<Response> {
    /// #         Ok(next.run(request).await)
    /// #     }
    /// # }
    ///
    /// Application::configure()
    ///     .with_middleware(|middleware, config| {
    ///         if config.app.debug {
    ///             middleware.web(|web| {
    ///                 web.append(Debugbar);
    ///             });
    ///         }
    ///     })
    ///     # ;
    /// ```
    pub fn with_middleware(self, configure: impl FnOnce(&mut MiddlewareConfig, &Config) + 'static) -> Self {
        self.registration(|app, config| configure(app.middleware(), config))
    }

    /// Send log events to any `tracing` layer, such as Sentry's, alongside the configured channels.
    ///
    /// The callback runs after every service provider has added its own layers, and it receives the
    /// final configuration.
    pub fn with_logging(self, configure: impl FnOnce(&mut LogLayers, &Config) + 'static) -> Self {
        self.registration(|app, config| configure(app.logging(), config))
    }

    /// Configure views, including template engines, namespaces, and data shared with every view.
    ///
    /// The callback runs after every service provider's registrations.
    pub fn with_views(self, configure: impl FnOnce(&mut ViewConfig, &Config) + 'static) -> Self {
        self.registration(|app, config| configure(app.views(), config))
    }

    /// Configure how errors are reported and rendered.
    ///
    /// The callback runs after every service provider's registrations and receives the final
    /// configuration. The statuses and renderers it sets replace a package's.
    pub fn with_errors(self, configure: impl FnOnce(&mut Errors, &Config) + 'static) -> Self {
        self.registration(|app, config| configure(app.errors(), config))
    }

    /// Configure the document head, with defaults for every page and metadata for error pages.
    ///
    /// The callback runs after every service provider's registrations and receives the final
    /// configuration, so its settings win over a package's.
    ///
    /// ```
    /// use laravel::Application;
    /// use laravel::head::{Head, Robots};
    ///
    /// Application::configure()
    ///     .with_head(|head, config| {
    ///         let name = &config.app.name;
    ///
    ///         head.defaults(Head::new().title(name).title_template(format!("%s · {name}")).canonical());
    ///         head.errors(Head::new().robots([Robots::NoIndex, Robots::Follow]));
    ///         head.error(404, Head::new().description("The page you are looking for could not be found."));
    ///     })
    ///     # ;
    /// ```
    pub fn with_head(self, configure: impl FnOnce(&mut HeadConfig, &Config) + 'static) -> Self {
        self.registration(|app, config| configure(app.head(), config))
    }

    /// Register console commands with the final configuration.
    ///
    /// The callback runs after every service provider's [`register`](ServiceProvider::register)
    /// hook, so the application's commands replace package commands with the same name.
    pub fn with_commands(self, configure: impl FnOnce(&mut Commands, &Config) + 'static) -> Self {
        self.registration(|app, config| configure(app.commands(), config))
    }

    /// Add seeders that `db:seed` can run by name, with the final configuration.
    ///
    /// Applications usually discover the seeders in their `app` crate. Package providers can't add
    /// seeders.
    ///
    /// ```
    /// laravel::Application::configure().with_seeders(|seeders, _| {
    ///     seeders.discover(env!("CARGO_CRATE_NAME"));
    /// });
    /// ```
    #[cfg(feature = "database")]
    pub fn with_seeders(self, configure: impl FnOnce(&mut crate::db::Seeders, &Config) + 'static) -> Self {
        self.registration(|app, config| configure(&mut app.seeders, config))
    }

    /// Add scheduled tasks with the final configuration.
    ///
    /// The tasks come after every provider's tasks and the tasks from the application's
    /// [`#[schedule::tasks]`](macro@crate::schedule::tasks) function. The `schedule:run` command runs
    /// due tasks concurrently, unless they're marked [`blocking`](crate::schedule::Task::blocking).
    ///
    /// ```
    /// laravel::Application::configure().with_schedule(|schedule, _| {
    ///     schedule.call(|| async {}).name("prune").daily();
    /// });
    /// ```
    pub fn with_schedule(self, configure: impl FnOnce(&mut Schedule, &Config) + 'static) -> Self {
        self.registration(|app, config| configure(app.schedule(), config))
    }

    /// Add ticks, which repeat in the server and in queue workers.
    ///
    /// The callback runs after every provider has added its ticks, and it receives the final
    /// configuration.
    ///
    /// ```
    /// use laravel::time::ToSpan;
    ///
    /// laravel::Application::configure().with_ticks(|ticks, _| {
    ///     ticks.every(30.seconds(), || async {}).name("refresh-flags").immediately();
    /// });
    /// ```
    pub fn with_ticks(self, configure: impl FnOnce(&mut Ticks, &Config) + 'static) -> Self {
        self.registration(|app, config| configure(app.ticks(), config))
    }

    /// Register the application's migrations.
    ///
    /// The `migrate` commands run these migrations and every package's migrations, in name order.
    ///
    /// ```ignore
    /// laravel::Application::configure().with_migrations(laravel::db::migrations!("database/migrations"));
    /// ```
    #[cfg(feature = "database")]
    pub fn with_migrations(self, migrations: crate::db::Migrations) -> Self {
        self.registration(|app, _| {
            app.migrations().add(migrations);
        })
    }

    /// Register the application's schema dumps, which `schema:dump` writes.
    ///
    /// When no migration has run on a connection's database, `migrate`, `migrate:fresh`, and
    /// [`refresh_database`](Self::refresh_database) load the connection's dump first, then run the
    /// migrations that are still pending. Without an embedded dump, they read the connection's
    /// dump from `database/schema` on disk.
    ///
    /// ```ignore
    /// laravel::Application::configure()
    ///     .with_migrations(laravel::db::migrations!("database/migrations"))
    ///     .with_schema(laravel::db::schema!("database/schema"));
    /// ```
    #[cfg(feature = "database")]
    pub fn with_schema(self, dumps: crate::db::SchemaDumps) -> Self {
        self.registration(|app, _| {
            app.instance(dumps);
        })
    }

    /// Give each test a database of its own, built by the migrations, and roll back what the test
    /// changed.
    ///
    /// Call this on a test application, which runs with `APP_ENV=testing`:
    ///
    /// ```no_run
    /// use laravel::foundation::ApplicationBuilder;
    ///
    /// pub fn configure() -> ApplicationBuilder {
    ///     laravel::Application::configure()
    ///         .for_testing(env!("CARGO_MANIFEST_DIR"))
    ///         .with_env("DATABASE_URL", "postgres://postgres@127.0.0.1/laravel_test")
    ///         .refresh_database()
    /// }
    /// ```
    ///
    /// When the application boots, it borrows a numbered copy of the default connection's
    /// database, such as `laravel_test_1`, that no other running test uses. Laravel creates the
    /// copy if it doesn't exist. Laravel rebuilds the copy, as `migrate:fresh` does, when the
    /// application has recompiled since the copy was built or when a previous test committed to it.
    /// Each connection runs the test on one physical connection, inside a transaction that's never
    /// committed. The application's own transactions become savepoints in that transaction, and
    /// `db::after_commit` callbacks run when the savepoints commit. An in-memory SQLite database
    /// starts empty, so each test migrates its own.
    ///
    /// Lock files in the temporary directory mark the copies in use, so tests in other threads and
    /// processes borrow other copies, under both `cargo test` and `cargo nextest`. Each
    /// [`migrations!`](crate::db::migrations!) call records a number that changes each time its
    /// crate compiles. Any change to the application's code or to a dependency therefore rebuilds
    /// the copies on the next run, but editing only the tests doesn't. To rebuild the copies anyway,
    /// such as after you change a file that a migration reads, touch a source file such as
    /// `src/app.rs`.
    ///
    /// Inside the transaction:
    ///
    /// - A query waits for the connection while another query or a transaction holds it, such as
    ///   in a spawned task, and fails after 5 seconds.
    /// - Other processes, such as a queue worker started separately, don't see the test's rows.
    /// - Only the default connection gets a copy of its own. Other connections run in a
    ///   transaction on the database they're configured with, which isn't migrated, and tests
    ///   running at the same time share it.
    /// - A handle from `outside_transaction()` runs apart from the test's transaction. On
    ///   PostgreSQL and MySQL it uses a second connection to the test's database, which doesn't
    ///   see the test's rows. On SQLite it uses the test's connection, so its writes roll back
    ///   with the test.
    /// - Auto-increment IDs keep counting between tests on PostgreSQL and MySQL.
    /// - If a query is canceled before the database answers, such as by a timeout, Laravel
    ///   discards the connection and what the test wrote, and later queries start a new
    ///   transaction.
    /// - On MySQL, a DDL statement such as `CREATE TABLE` commits the transaction. Later statements
    ///   then commit as they run, and the application's transactions fail. Laravel rebuilds the copy
    ///   before the next test uses it.
    #[cfg(feature = "database")]
    pub fn refresh_database(self) -> Self {
        self.registration(|app, _| {
            app.instance(crate::db::migrations::refresh::RefreshDatabase);
        })
    }

    /// Run a seeder in each test's transaction when the application boots.
    ///
    /// Call this together with [`refresh_database`](Self::refresh_database) on a test application:
    ///
    /// ```no_run
    /// # use laravel::Application;
    /// # #[laravel::db::seeder] async fn roles() -> laravel::Result<()> { Ok(()) }
    /// # fn configure() -> laravel::foundation::ApplicationBuilder {
    /// #     Application::configure().for_testing(env!("CARGO_MANIFEST_DIR")).refresh_database()
    /// # }
    /// fn app_with_roles() -> Application {
    ///     configure().seed(roles).create()
    /// }
    /// ```
    ///
    /// The seeder's rows roll back with the rest of the test. Any `async fn` that returns
    /// [`laravel::Result<()>`](crate::Result) works as a seeder. A
    /// [`#[seeder]`](macro@crate::db::seeder) that the database's [`seed_once`](Self::seed_once)
    /// seeder already ran doesn't run again. Without `refresh_database`, the application fails to
    /// boot rather than seed a database that isn't a test's.
    #[cfg(feature = "database")]
    pub fn seed<S, F>(self, seeder: S) -> Self
    where
        S: FnOnce() -> F + Send + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.booted(move |app| async move {
            let manager = app.resolve::<crate::db::DatabaseManager>().await?;
            crate::db::seeders::seed_test(&manager, Box::pin(seeder())).await
        })
    }

    /// Seed each test database once, when [`refresh_database`](Self::refresh_database) builds it.
    ///
    /// Every test then starts with the seeder's rows in place:
    ///
    /// ```no_run
    /// # use laravel::Application;
    /// use laravel::foundation::ApplicationBuilder;
    /// # #[laravel::db::seeder] async fn database() -> laravel::Result<()> { Ok(()) }
    ///
    /// pub fn configure() -> ApplicationBuilder {
    ///     Application::configure()
    ///         .for_testing(env!("CARGO_MANIFEST_DIR"))
    ///         .refresh_database()
    ///         .seed_once(database)
    /// }
    /// ```
    ///
    /// The seeder runs after the migrations and commits its rows, and each test rolls back only its
    /// own changes. Laravel rebuilds and seeds a test database again when the application has
    /// recompiled, as `refresh_database` describes. Each seeder gets test databases of its own,
    /// named after the seeder, such as `laravel_test_database_1`. Tests that use different seeders
    /// can then run at the same time without rebuilding each other's databases. A later `seed_once`
    /// call replaces an earlier one.
    ///
    /// Without `refresh_database`, the application doesn't start.
    ///
    /// # Panics
    ///
    /// Panics when `seeder` isn't a function marked [`#[seeder]`](macro@crate::db::seeder). The
    /// attribute provides the name that the test databases use.
    #[cfg(feature = "database")]
    #[track_caller]
    pub fn seed_once<S, F>(self, seeder: S) -> Self
    where
        S: Fn() -> F,
        F: Future<Output = Result<()>>,
    {
        let Some(seeder) = crate::db::seeders::registered(&seeder) else {
            panic!(
                "`seed_once` takes a function marked `#[seeder]`, not `{}`",
                std::any::type_name::<S>()
            );
        };
        self.registration(move |app, _| {
            app.instance(crate::db::seeders::SeedOnce(seeder));
        })
    }

    fn registration(mut self, register: impl FnOnce(&mut Registrar, &Config) + 'static) -> Self {
        self.registrations.push(Box::new(register));
        self
    }

    /// Build the application, then run the console command given on the command line.
    ///
    /// With no command, the application serves requests, as [`Application::run`] does. Call this
    /// from a binary's `main`:
    ///
    /// ```no_run
    /// use std::process::ExitCode;
    ///
    /// fn main() -> ExitCode {
    ///     laravel::Application::configure().run()
    /// }
    /// ```
    ///
    /// When the application can't be built, `run` prints the [`StartupError`], and the process
    /// exits with status `1`.
    #[must_use = "return the exit code from `main`, or the process exits with status 0 when startup fails"]
    pub fn run(self) -> ExitCode {
        match self.try_create() {
            Ok(application) => application.run(),
            Err(error) => {
                crate::console::Console::terminal().error(error.to_string());
                ExitCode::FAILURE
            }
        }
    }

    /// Build the application, panicking if it can't start.
    ///
    /// Use this in tests and anywhere else a startup failure may panic. A binary's `main` uses
    /// [`ApplicationBuilder::run`], which prints the failure instead.
    ///
    /// # Panics
    ///
    /// Panics with the [`StartupError`] when the application can't be built. The panic happens at
    /// startup and in every test, never in the middle of a request.
    #[track_caller]
    pub fn create(self) -> Application {
        match self.try_create() {
            Ok(application) => application,
            Err(error) => panic!("{error}"),
        }
    }

    /// Build the application, or return why it can't be built.
    ///
    /// For example, a test may check that a mistake stops the application from starting:
    ///
    /// ```
    /// use laravel::config::Env;
    /// use laravel::foundation::StartupError;
    ///
    /// let error = laravel::Application::configure()
    ///     .replace_env(Env::from_iter([("APP_DEBUG", "maybe")]))
    ///     .try_create()
    ///     .unwrap_err();
    ///
    /// assert!(matches!(error, StartupError::Env(_)));
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error when environment variables are invalid for their settings, such as
    /// `APP_DEBUG=maybe`, or when routes are invalid, such as two routes for the same method and
    /// URI. Each error lists every problem of its kind. Building also checks console commands,
    /// scheduled tasks, ticks, log channels, drivers, and queue and mail settings, among others.
    /// Each [`StartupError`] variant names one check.
    pub fn try_create(self) -> Result<Application, StartupError> {
        crate::errors::panic::capture_locations();
        crate::tls::install_crypto_provider();

        let Self {
            env,
            env_vars,
            config_files,
            registrations,
            booted,
            providers: application_providers,
            framework_providers: mut providers,
        } = self;
        providers.extend(application_providers.clone());

        let mut env = env.unwrap_or_else(Env::from_process);
        env.set(env_vars);
        let (config, dotenv) = read_config(env, config_files, &providers)?;
        let registered = register(registrations, &providers, &config)?;

        assemble(registered, providers, application_providers, booted, config, dotenv)
    }
}

fn read_config(
    mut env: Env,
    config_files: Vec<ConfigFile>,
    providers: &Providers,
) -> Result<(Arc<Config>, DotEnv), StartupError> {
    let mut config = Config::from_env(&env);
    for provider in providers.iter() {
        provider.provider.config(&mut config, &env);
    }
    config.discover("app", &env);
    for configure in config_files {
        configure(&mut config, &env);
    }

    config.validate_env(&env)?;
    if let Some(destination) = config.logging.duplicate_destination() {
        return Err(StartupError::DuplicateLogChannel(destination.name()));
    }

    Ok((Arc::new(config), env.take_dotenv().into()))
}

fn register(
    registrations: Vec<Registration>,
    providers: &Providers,
    config: &Arc<Config>,
) -> Result<Registered, StartupError> {
    let mut registrar = Registrar::new(Arc::clone(config));
    for provider in providers.iter() {
        registrar.provider(Some(provider.name));
        provider.provider.register(&mut registrar);
    }
    registrar.provider(None);
    registrar.discover("app");
    registrar.auth.discover("app");
    #[cfg(feature = "database")]
    registrar.seeders.discover("app");
    for register in registrations {
        register(&mut registrar, config);
    }
    if !registrar.services.conflicts.is_empty() {
        return Err(StartupError::Services(std::mem::take(
            &mut registrar.services.conflicts,
        )));
    }

    let (auth, auth_problems) = std::mem::take(&mut registrar.auth)
        .finish()
        .map_err(StartupError::Auth)?;
    let auth_pages = auth.pages;
    let auth = Arc::new(auth);
    registrar.instance_as::<dyn crate::http::identity::Identify>(Arc::clone(&auth) as _);
    registrar.instance_as(auth);

    #[cfg(feature = "database")]
    crate::session::database::validate(&config.session).map_err(|error| StartupError::Session(error.to_string()))?;
    std::mem::take(&mut registrar.sessions)
        .register(&mut registrar.services)
        .map_err(|error| StartupError::Session(error.to_string()))?;
    std::mem::take(&mut registrar.features)
        .register(&mut registrar.services)
        .map_err(|error| StartupError::Features(error.to_string()))?;
    let cache_drivers = std::mem::take(&mut registrar.cache)
        .register(&registrar.services)
        .map_err(|error| StartupError::Cache(error.to_string()))?;
    #[cfg(feature = "search")]
    {
        let settings = config
            .get::<crate::config::search::Search>()
            .cloned()
            .unwrap_or_default();
        let engines = laravel_search::search::engines(std::mem::take(&mut registrar.search), &settings)
            .map_err(|error| StartupError::Search(error.to_string()))?;
        registrar.part(engines);
    }
    let queue_drivers = std::mem::take(&mut registrar.queue)
        .register(&registrar.services)
        .map_err(StartupError::Queue)?;
    crate::queue::validate(&config.queue).map_err(StartupError::Queue)?;
    let workflow_drivers = std::mem::take(&mut registrar.workflow)
        .register(config)
        .map_err(StartupError::Workflow)?;
    crate::broadcast::validate(config).map_err(StartupError::Broadcast)?;
    let mail_drivers = std::mem::take(&mut registrar.mail)
        .register(config)
        .map_err(StartupError::Mail)?;
    crate::sms::validate(config).map_err(StartupError::Sms)?;
    let social = std::mem::take(&mut registrar.social).build(config);
    registrar.part(social);
    crate::hash::valid_rounds(config.hashing.rounds).map_err(StartupError::Hashing)?;

    registrar.commands.validate().map_err(StartupError::Commands)?;
    let schedule = std::mem::take(&mut registrar.schedule);
    registrar.instance(schedule);
    registrar.ticks.validate().map_err(StartupError::Ticks)?;
    let ticks = std::mem::take(&mut registrar.ticks);
    registrar.instance(ticks);
    #[cfg(feature = "database")]
    register_database(&mut registrar, config)?;
    let events = std::mem::take(&mut registrar.events);
    registrar.instance(events);

    Ok(Registered {
        registrar,
        auth_pages,
        auth_problems,
        cache: cache_drivers,
        mail: mail_drivers,
        queue: queue_drivers,
        workflow: workflow_drivers,
    })
}

/// Bind the migrations, schema dumps, and seeders, and check that the test database options fit
/// the environment.
#[cfg(feature = "database")]
fn register_database(registrar: &mut Registrar, config: &Config) -> Result<(), StartupError> {
    let migrations = std::mem::take(&mut registrar.migrations);
    migrations.validate().map_err(StartupError::Migrations)?;
    registrar.instance(migrations);
    if !registrar.is_bound::<crate::db::SchemaDumps>() {
        registrar.instance(crate::db::SchemaDumps::default());
    }

    let refreshes = registrar.is_bound::<crate::db::migrations::refresh::RefreshDatabase>();
    if refreshes && config.app.env != crate::config::app::Environment::Testing {
        return Err(StartupError::RefreshDatabase(config.app.env.as_str().to_owned()));
    }
    if !refreshes && registrar.is_bound::<crate::db::seeders::SeedOnce>() {
        return Err(StartupError::SeedOnce);
    }

    let seeders = std::mem::take(&mut registrar.seeders);
    seeders.validate().map_err(StartupError::Seeders)?;
    registrar.instance(seeders);

    Ok(())
}

fn assemble(
    registered: Registered,
    providers: Providers,
    application_providers: Providers,
    booted: Vec<boot::Booted>,
    config: Arc<Config>,
    dotenv: DotEnv,
) -> Result<Application, StartupError> {
    let Registered {
        registrar,
        auth_pages,
        mut auth_problems,
        cache,
        mail,
        queue,
        workflow,
    } = registered;
    let queue_bound = registrar.is_bound::<crate::queue::QueueManager>();
    let Registrar {
        services: crate::container::Bindings { bindings, .. },
        middleware,
        mut routing,
        views,
        logging: log_layers,
        errors,
        head,
        commands,
        mut parts,
        ..
    } = registrar;
    let views = views.build(&config);

    let encrypter = Encrypter::from_config(&config.app);
    let handler = Arc::new(ErrorHandler::new(errors, &config));
    let boundary = ResponseBoundary::new(Arc::clone(&handler));

    let health_path = routing.health.clone();
    let assets = Arc::new(Assets::new(std::mem::take(&mut routing.assets), config.app.debug));
    crate::storage::web::validate(&config.filesystems).map_err(StartupError::Routes)?;
    routing.routes(crate::workflow::routes);
    let files = routing.collect();
    let serving = table::Serving {
        boundary: &|route| route.route_layer(boundary.clone()),
        unmatched: |request| {
            Box::pin(async move {
                crate::storage::web::serve(request)
                    .await
                    .map(crate::http::Response::into_http)
            })
        },
    };
    let (router, table) = table::compile(
        files,
        health_path.as_deref(),
        &middleware,
        &serving,
        &config.app.public_path(""),
        &assets,
    )
    .map_err(StartupError::Routes)?;
    auth_problems.extend(auth_pages.check_routes(&table));

    let shared = Arc::new_cyclic(|shared| {
        parts.insert(commands);
        parts.insert(table);
        parts.insert(Boot::new(Weak::clone(shared), providers, booted));
        parts.insert(views);
        parts.insert_shared(assets);
        parts.insert(head);
        parts.insert(crate::task::ticks::Ticking::default());
        parts.insert(AuthProblems(auth_problems));

        App {
            services: Services::new(Weak::clone(shared), Arc::clone(&config), bindings),
            reporter: Arc::clone(handler.reporter()),
            encrypter,
            config,
            shutdown: Shutdown::default(),
            clock: Clock::default(),
            lottery_draws: crate::lottery::Draws::default(),
            host: std::sync::OnceLock::new(),
            parts: {
                parts.insert_shared(handler);
                parts
            },
        }
    });
    if let Some(factories) = cache {
        let manager = CacheManager::new(
            &shared.config.cache,
            factories,
            shared.services.container(),
            crate::cache::DATABASE_STORE,
        );
        shared.services.insert(Arc::new(manager));
    }
    let mail = crate::mail::MailManager::new(&shared.config.mail, &mail, &shared.services.container());
    shared.services.insert(Arc::new(mail));
    if !queue_bound {
        let manager = crate::queue::QueueManager::new(
            &shared.config.queue,
            queue,
            shared.services.container(),
            shared.config.app.env == crate::config::app::Environment::Testing,
        );
        shared.services.insert(Arc::new(manager));
    }
    let workflows = crate::workflow::Manager::new(&shared.config.workflow, workflow, shared.services.container());
    shared.services.insert(Arc::new(workflows));
    crate::task::ticks::check_dependencies(&shared).map_err(StartupError::Ticks)?;
    shared
        .services
        .built::<Schedule>()
        .expect("the application registers its schedule")
        .check(&shared)
        .map_err(StartupError::Schedule)?;
    let router = middleware.global.apply_to_router(router);
    let kernel = Kernel {
        app: Arc::clone(&shared),
        proxies: middleware.proxies.on_laravel_cloud(shared.config.app.laravel_cloud),
        health: health_path,
    };
    let router = kernel::wrap(router, kernel, boundary);

    Ok(Application {
        router,
        shared,
        providers: application_providers,
        log_layers: Arc::new(Mutex::new(Some(log_layers))),
        dotenv,
    })
}

/// The problems with the `#[laravel::auth::page(..)]` handlers.
///
/// These problems stop the application from serving requests, but not from running console
/// commands.
struct AuthProblems(Vec<String>);

/// What the providers and the application registered, checked and ready to assemble.
struct Registered {
    registrar: Registrar,
    auth_pages: crate::auth::Pages,
    auth_problems: Vec<String>,
    cache: Option<crate::cache::Factories>,
    mail: crate::mail::Factories,
    queue: crate::queue::Factories,
    workflow: crate::workflow::Factories,
}

/// Why an application couldn't be created.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum StartupError {
    /// Console command definitions conflict or contain invalid argument declarations.
    #[error("the application's console commands are invalid: {0}")]
    Commands(String),
    /// A scheduled task has an invalid frequency or option or names an unknown command, or one of
    /// its callbacks injects a service that isn't registered.
    #[error("the application's schedule is invalid: {0}")]
    Schedule(String),
    /// A tick's name, interval, or jitter is invalid, two ticks have the same name, or a tick
    /// injects a service that isn't registered.
    #[error("the application's ticks are invalid: {0}")]
    Ticks(String),
    /// The selected session driver isn't registered.
    #[error("the application's session driver is invalid: {0}")]
    Session(String),
    /// The selected feature store isn't registered.
    #[error("the application's feature store is invalid: {0}")]
    Features(String),
    /// A cache store uses a driver that isn't registered.
    #[error("the application's cache stores are invalid: {0}")]
    Cache(String),
    /// The configured search engine names a driver that isn't registered.
    #[error("the application's search engine is invalid: {0}")]
    Search(String),
    /// The default queue connection isn't defined, a connection is invalid, or two jobs share a name.
    #[error("the application's queue is invalid: {0}")]
    Queue(String),
    /// The default workflow store isn't defined, a store uses a driver that isn't registered, or
    /// two workflows share a name.
    #[error("the application's workflows are invalid: {0}")]
    Workflow(String),
    /// Two migrations have the same name.
    #[error("the application's migrations are invalid: {0}")]
    Migrations(String),
    /// The application refreshes the database outside the `testing` environment, where it could
    /// drop the tables of a database that isn't a test's.
    #[error("`refresh_database` drops tables, so it only runs when `APP_ENV` is `testing`, not `{0}`")]
    RefreshDatabase(String),
    /// Two seeders have the same name, or more than one is the default.
    #[error("the application's seeders are invalid: {0}")]
    Seeders(String),
    /// The application calls `seed_once` without `refresh_database`.
    #[error("`seed_once` seeds the databases that `refresh_database` builds, so it needs `refresh_database` too")]
    SeedOnce,
    /// Broadcasting selects a connection that isn't defined, or its Reverb settings are invalid.
    #[error("the application's broadcasting is invalid: {0}")]
    Broadcast(String),
    /// The default mailer isn't defined, a mailer uses a driver that isn't registered, a failover
    /// mailer's list is invalid, or the mail queue connection isn't defined.
    #[error("the application's mailers are invalid: {0}")]
    Mail(String),
    /// The default SMS sender isn't defined, or the SMS queue connection isn't defined.
    #[error("the application's SMS senders are invalid: {0}")]
    Sms(String),
    /// Bcrypt's rounds are out of the range it accepts.
    #[error("the application's password hashing is invalid: {0}")]
    Hashing(String),
    /// Environment variables are set to values that are invalid for their settings.
    #[error(transparent)]
    Env(#[from] InvalidEnv),
    /// Two handlers are marked as the same `#[laravel::auth::page(..)]`.
    ///
    /// Serving requests also fails when no route uses a marked handler, or when a page's route lacks
    /// a parameter that its links fill. It also fails when the application has a verification page
    /// but its user type doesn't derive `MustVerifyEmail`, or derives it without a verification page.
    #[error("the application's authentication pages are invalid:\n  - {}", .0.join("\n  - "))]
    Auth(Vec<String>),
    /// Routes are invalid, such as two for the same method and URI.
    #[error("the application's routes are invalid:\n  - {}", .0.join("\n  - "))]
    Routes(Vec<String>),
    /// Two discovered services in one crate are registered under the same type.
    #[error("the application's services are invalid:\n  - {}", .0.join("\n  - "))]
    Services(Vec<String>),
    /// Two log channels write to the same destination, such as `stderr`.
    #[error("the `{0}` log channel is listed twice: each destination may have one channel")]
    DuplicateLogChannel(&'static str),
}

impl std::fmt::Debug for ApplicationBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ApplicationBuilder")
            .field("env", &self.env)
            .field("providers", &self.providers)
            .finish_non_exhaustive()
    }
}