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
use crate::console::ConsoleInternals as _;
use std::ffi::OsString;
use std::net::SocketAddr;
use std::process::ExitCode;
use std::sync::Arc;

use super::connections::LimitedListener;
use super::{Application, LoggingError, shutdown_signal};
use crate::config::dotenv;
use crate::console::markup::clean;
use crate::console::{CommandsInternals as _, Console};
use crate::context::{App, Context, Internals};
use crate::error::ErrorInternals as _;
use crate::errors::panic;
use axum::serve::ListenerExt as _;
use futures_util::{FutureExt, future::FusedFuture};

impl Application {
    /// Run the console command given on the command line, or serve the application when there's
    /// no command.
    ///
    /// Besides the commands that the application and its providers register, the framework's own
    /// commands are built in, such as `serve`, `route:list`, and `key:generate`. The `list` command
    /// shows them all. Commands run in the application's own binary, so they see its routes, as in
    /// `cargo run -- route:list`.
    ///
    /// `run` starts its own async runtime, so call it from a synchronous `main`, outside any
    /// runtime. Inside a runtime, `run` fails with exit status `1`, so use [`serve`](Self::serve)
    /// there instead.
    ///
    /// `run` first loads `.env` into the process's environment, for libraries that read the
    /// environment directly. Call it from `main` before you start threads of your own.
    ///
    /// `run` also installs the application's [logger](Self::init_logging). If a log channel can't
    /// be written, such as a `daily` channel whose directory isn't writable, `run` stops with exit
    /// status `1` rather than run without logs. If a `tracing` subscriber was installed before
    /// `run`, `run` keeps that subscriber.
    ///
    /// Once a command finishes, admitted [background work](crate::task::background) gets up to the
    /// `server` section's `shutdown_timeout` to finish before the process exits. `run` cuts the
    /// work off at that deadline, or on Ctrl+C or `SIGTERM`, and keeps the command's exit code
    /// either way. A second after that, the process exits without waiting for blocking work that's
    /// still running.
    pub fn run(self) -> ExitCode {
        let mut arguments = std::env::args_os();
        let program = arguments.next().unwrap_or_else(|| OsString::from("app"));

        self.run_with(program, arguments.collect())
    }

    fn run_with(self, program: OsString, arguments: Vec<OsString>) -> ExitCode {
        // Fail before exporting `.env`, which is only safe before any runtime thread starts...
        if tokio::runtime::Handle::try_current().is_ok() {
            Console::terminal().error(
                "`Application::run` starts its own async runtime, so call it from a synchronous `fn main`; \
                 inside a runtime, use `Application::serve`",
            );
            return ExitCode::FAILURE;
        }

        // Export `.env` for external libraries before the runtime and logging threads can read it...
        // SAFETY: the check above returned inside a runtime; the runtime and logging threads start later...
        unsafe { dotenv::export(&self.dotenv) };

        let _logs = match self.init_logging() {
            Ok(logs) => Some(logs),
            Err(LoggingError::AlreadyInstalled) => None,
            Err(error) => {
                let error: &(dyn std::error::Error + 'static) = &error;
                let causes = std::iter::successors(Some(error), |cause| cause.source());
                Console::terminal().error(clean(&crate::error::join_causes(causes)));
                return ExitCode::FAILURE;
            }
        };

        let runtime = match tokio::runtime::Runtime::new() {
            Ok(runtime) => runtime,
            Err(error) => {
                Console::terminal().error(format!("failed to start the async runtime: {error}"));
                return ExitCode::FAILURE;
            }
        };

        let mut console = Console::terminal();
        let code = runtime.block_on(self.run_and_finish(program, arguments, &mut console, shutdown_signal()));

        // Blocking work can't be cancelled, so stop waiting for it once its deadline has passed...
        runtime.shutdown_timeout(CLOSING);

        ExitCode::from(code)
    }

    async fn run_and_finish(
        &self,
        program: OsString,
        arguments: Vec<OsString>,
        console: &mut Console,
        interrupted: impl Future<Output = ()>,
    ) -> u8 {
        let code = self.run_command(program, arguments, console).await;
        finish(&self.shared, interrupted).await;
        code
    }

    pub(crate) async fn run_command(
        &self,
        program: OsString,
        mut arguments: Vec<OsString>,
        console: &mut Console,
    ) -> u8 {
        let started = std::time::Instant::now();
        let context = Context::new(Arc::clone(&self.shared), None);
        context
            .clone()
            .scope(async {
                let result = panic::catch(async {
                    self.boot().await?;
                    default_to_serve(&mut arguments);
                    let _ = context.local::<CommandApplication>().0.set(self.clone());
                    let _ = context.local::<crate::console::Invoker>().0.set(self.invoke());
                    let code = self
                        .shared
                        .part::<crate::console::Commands>()
                        .run(program, arguments, console)
                        .await?;
                    console.ensure_written()?;
                    Ok(code)
                })
                .await;

                let span = crate::console::command_span(&context).entered();
                let code = match result {
                    Ok(code) => {
                        if code != 0 {
                            crate::foundation::telemetry::fail(
                                &span,
                                &crate::foundation::telemetry::Summary::exit_code(i64::from(code)),
                            );
                        }
                        code
                    }
                    Err(error) => {
                        let code = self.command_failed(&error, console);
                        if code != 0 {
                            crate::foundation::telemetry::fail(&span, &error);
                        }
                        code
                    }
                };
                span.record("process.exit.code", i64::from(code));
                tracing::debug!(
                    target: super::telemetry::COMMAND_TARGET,
                    exit_code = code,
                    duration_ms = crate::foundation::telemetry::duration_ms(started.elapsed()),
                    "Command finished",
                );

                code
            })
            .await
    }

    fn command_failed(&self, error: &crate::Error, console: &mut Console) -> u8 {
        if matches!(
            error.downcast_ref::<crate::console::PromptError>(),
            Some(crate::console::PromptError::Cancelled)
        ) {
            return 130;
        }

        // A console reader that stopped reading, such as `head`, isn't a failure. 141 is SIGPIPE's status...
        if crate::console::OutputClosed::is(error) {
            return 141;
        }

        self.shared.reporter.report_for_console(error);
        console.error(clean(&format!("{error:#}")));
        1
    }

    /// Boot the application, then serve it until Ctrl+C or `SIGTERM` tells it to stop.
    ///
    /// Process managers and containers stop the application with `SIGTERM`. Stopping is graceful.
    /// The server stops accepting connections, and requests in progress get up to the `server`
    /// section's `shutdown_timeout` to finish, so a deploy doesn't cut them off. After that, the
    /// server answers requests that are still running with a `503`, even if the runtime keeps
    /// running other work.
    ///
    /// # Errors
    ///
    /// Returns an error when the application fails to boot, or when the server can't bind its address.
    pub async fn serve(self, address: impl tokio::net::ToSocketAddrs) -> std::io::Result<()> {
        self.serve_with_output(address, &mut Console::terminal()).await
    }

    pub(super) async fn serve_with_output(
        self,
        address: impl tokio::net::ToSocketAddrs,
        console: &mut Console,
    ) -> std::io::Result<()> {
        let shared = Arc::clone(&self.shared);
        let result = async {
            self.check_auth_pages().map_err(std::io::Error::other)?;
            self.boot()
                .await
                .map_err(|error| std::io::Error::other(error.for_boot("the application failed to boot")))?;

            let listener = tokio::net::TcpListener::bind(address).await?;
            self.serve_on(listener, console, shutdown_signal()).await
        }
        .await;
        finish(&shared, shutdown_signal()).await;
        result
    }

    async fn serve_on(
        self,
        listener: tokio::net::TcpListener,
        console: &mut Console,
        shutdown: impl Future<Output = ()> + Send + 'static,
    ) -> std::io::Result<()> {
        let address = listener.local_addr()?;
        let grace = self.config().server.shutdown_timeout;
        let max_connections = self.config().server.max_connections;
        let shared = Arc::clone(&self.shared);
        crate::task::ticks::start(
            &Context::new(Arc::clone(&self.shared), None),
            crate::foundation::Host::Server,
        );

        console.info(format!("Server running at `http://{address}`. Press Ctrl+C to stop."));

        let (stopping, stopped) = tokio::sync::oneshot::channel();
        // axum gives any `TapIo` listener `ConnectInfo<SocketAddr>`, which our own listener can't implement...
        let listener = LimitedListener::new(listener, max_connections).tap_io(|_| ());
        let server = axum::serve(
            listener,
            self.router.into_make_service_with_connect_info::<SocketAddr>(),
        )
        .with_graceful_shutdown(async move {
            shutdown.await;
            shared.shutdown.begin();
            let _ = stopping.send(());
        });

        let deadline = async {
            if stopped.await.is_ok() {
                console.info(format!("Stopping. Waiting up to {grace} for requests in progress."));
                tokio::time::sleep(*grace).await;
            } else {
                std::future::pending::<()>().await;
            }
        };

        let mut server = std::pin::pin!(server.into_future().fuse());
        tokio::select! {
            result = async {
                let result = server.as_mut().await;
                if result.is_err() { self.shared.shutdown.cut_off(); }
                // Background work and ticks in progress may buffer what the shutdown ticks flush...
                self.shared.shutdown.background_finished().await;
                self.shared.part::<crate::task::ticks::Ticking>().finish(&self.shared).await;
                close_database(&self.shared).await;
                result
            } => result,
            () = deadline => {
                console.warn(format!("Stopped with work still in progress after {grace}."));

                // Connections outlive the server future, so cut off requests before allowing connections to close...
                self.shared.shutdown.cut_off();
                let database = close_database(&self.shared);
                let _ = tokio::time::timeout(CLOSING, async {
                    let connections = async {
                        if !server.is_terminated() { let _ = server.await; }
                    };
                    let _ = tokio::join!(connections, self.shared.shutdown.background_finished(), database);
                }).await;
                Ok(())
            }
        }
    }
}

fn close_database(shared: &App) -> impl Future<Output = ()> + Send + use<> {
    #[cfg(feature = "database")]
    let closing = shared
        .services
        .built::<crate::db::DatabaseManager>()
        .map(|manager| manager.shutdown());
    #[cfg(not(feature = "database"))]
    let _ = shared;
    async move {
        #[cfg(feature = "database")]
        if let Some(closing) = closing {
            closing.await;
        }
    }
}

async fn finish(shared: &Arc<App>, interrupted: impl Future<Output = ()>) {
    if shared.shutdown.is_stopping() {
        return;
    }
    shared.shutdown.begin();

    let grace = shared.config.server.shutdown_timeout;
    let mut deadline = tokio::time::Instant::now() + *grace;
    let finished = tokio::select! {
        biased;
        () = shared.shutdown.background_finished() => true,
        () = tokio::time::sleep_until(deadline) => {
            tracing::warn!(target: super::telemetry::COMMAND_TARGET, "Cutting off background work still in progress after {grace}");
            false
        }
        () = interrupted => {
            tracing::warn!(target: super::telemetry::COMMAND_TARGET, "Interrupted: cutting off background work still in progress");
            false
        }
    };

    // A worker's or command's shutdown ticks flush what its jobs and background work buffered...
    let finished = finished
        && tokio::time::timeout_at(deadline, shared.part::<crate::task::ticks::Ticking>().finish(shared))
            .await
            .inspect_err(|_| {
                tracing::warn!(target: super::telemetry::COMMAND_TARGET, "Cutting off shutdown ticks still running after {grace}");
            })
            .is_ok();

    // Cut-off work ends at its next poll, so let it release connections before the pools close...
    if !finished {
        shared.shutdown.cut_off();
        deadline = tokio::time::Instant::now() + CLOSING;
        let _ = tokio::time::timeout_at(deadline, shared.shutdown.background_finished()).await;
    }

    if tokio::time::timeout_at(deadline, close_database(shared)).await.is_err() {
        tracing::warn!(target: "laravel::db", "Database shutdown deadline expired with connections still checked out");
    }
}

fn default_to_serve(arguments: &mut Vec<OsString>) {
    let input = arguments
        .iter()
        .position(|argument| !crate::console::is_global_option(argument));
    if input.is_none_or(|index| {
        arguments[index].to_str().is_some_and(|argument| {
            argument.starts_with('-') && !matches!(argument, "-h" | "--help" | "-V" | "--version")
        })
    }) {
        arguments.insert(input.unwrap_or(arguments.len()), OsString::from("serve"));
    }
}

const CLOSING: std::time::Duration = std::time::Duration::from_secs(1);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::logging::LogChannel;
    use crate::event::{self, Event};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::{Duration, Instant};
    use tokio::sync::Notify;

    use crate::console::clap;
    use crate::container::Inject;
    use futures_util::future::BoxFuture;

    struct Work(std::sync::Mutex<Option<BoxFuture<'static, crate::Result<()>>>>);

    #[derive(clap::Parser)]
    #[command(name = "work")]
    struct WorkCommand;

    #[crate::console::command]
    impl WorkCommand {
        async fn handle(self, work: Inject<Work>) -> crate::Result<()> {
            let work = work.0.lock().unwrap().take().expect("each test starts its work once");
            crate::task::background(work)?;
            Ok(())
        }
    }

    fn working(
        work: impl Future<Output = crate::Result<()>> + Send + 'static,
    ) -> crate::foundation::ApplicationBuilder {
        let work = Work(std::sync::Mutex::new(Some(Box::pin(work))));
        Application::configure()
            .replace_env(crate::config::Env::default())
            .with_services(|services| {
                services.instance(work);
            })
            .with_commands(|commands, _| {
                commands.add::<WorkCommand>();
            })
    }

    async fn run_and_finish(
        app: &Application,
        command: &str,
        interrupted: impl Future<Output = ()> + Send + 'static,
    ) -> (u8, Duration) {
        let app = app.clone();
        let command = OsString::from(command);
        let started = Instant::now();
        let mut run = tokio::spawn(async move {
            app.run_and_finish("app".into(), vec![command], &mut Console::captured(), interrupted)
                .await
        });
        let result = tokio::time::timeout(Duration::from_secs(5), &mut run).await;
        if result.is_err() {
            run.abort();
        }
        let code = result
            .expect("finishing a command is bounded")
            .expect("finishing did not panic");
        (code, started.elapsed())
    }

    struct Dropped(Arc<AtomicUsize>);

    impl Drop for Dropped {
        fn drop(&mut self) {
            self.0.fetch_add(1, Ordering::SeqCst);
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_command_waits_for_its_background_work_before_finishing() {
        let finished = Arc::new(AtomicUsize::new(0));
        let app = working({
            let finished = Arc::clone(&finished);
            async move {
                tokio::time::sleep(Duration::from_millis(100)).await;
                assert_eq!(crate::config().app.name, "Laravel");
                finished.store(1, Ordering::SeqCst);
                Ok(())
            }
        })
        .create();

        let (code, _) = run_and_finish(&app, "work", std::future::pending()).await;

        assert_eq!(code, 0);
        assert_eq!(finished.load(Ordering::SeqCst), 1);
        let error = app
            .scope(async || crate::task::background(async { Ok(()) }))
            .await
            .unwrap_err();
        assert!(error.to_string().contains("shutting down"));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn background_failures_are_reported_without_changing_the_exit_code() {
        let reported = Arc::new(std::sync::Mutex::new(Vec::new()));
        let app = working(async {
            tokio::task::yield_now().await;
            Err(anyhow::anyhow!("metrics are down").into())
        })
        .with_errors({
            let reported = Arc::clone(&reported);
            move |errors, _| {
                errors.report_all(move |error| reported.lock().unwrap().push(error.to_string()));
            }
        })
        .create();

        let (code, _) = run_and_finish(&app, "work", std::future::pending()).await;

        assert_eq!(code, 0);
        assert_eq!(*reported.lock().unwrap(), ["metrics are down"]);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn hung_background_work_is_cut_off_at_the_deadline_or_when_interrupted() {
        for interrupt in [false, true] {
            let dropped = Arc::new(AtomicUsize::new(0));
            let payload = Dropped(Arc::clone(&dropped));
            let app = working(async move {
                let _payload = payload;
                std::future::pending::<crate::Result<()>>().await
            })
            .with_config(move |config, _| {
                config.server.shutdown_timeout = if interrupt {
                    Duration::from_secs(60).into()
                } else {
                    Duration::from_millis(200).into()
                };
            })
            .create();
            let interrupted = async move {
                if interrupt {
                    tokio::time::sleep(Duration::from_millis(100)).await;
                } else {
                    std::future::pending::<()>().await;
                }
            };

            let (code, elapsed) = run_and_finish(&app, "work", interrupted).await;

            assert_eq!(code, 0);
            assert_eq!(dropped.load(Ordering::SeqCst), 1, "cut-off work is dropped");
            assert!(
                elapsed >= Duration::from_millis(100),
                "waits until cut off: {elapsed:?}"
            );
            assert!(elapsed < Duration::from_secs(2), "cuts off promptly: {elapsed:?}");
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn commands_without_background_work_finish_immediately() {
        let app = Application::configure()
            .replace_env(crate::config::Env::default())
            .with_config(|config, _| config.server.shutdown_timeout = Duration::from_secs(60).into())
            .with_routing(|routing, _| {
                routing.web(|route| {
                    route.get("/", || async { "Home" });
                });
            })
            .create();

        let (code, elapsed) = run_and_finish(&app, "route:list", std::future::pending()).await;

        assert_eq!(code, 0);
        assert!(elapsed < Duration::from_secs(1), "{elapsed:?}");
    }

    #[tokio::test]
    async fn commands_end_quietly_once_nothing_reads_their_output() {
        let app = Application::configure()
            .replace_env(crate::config::Env::default())
            .create();

        let mut console = Console::with_closed_stdout();
        let code = app
            .run_command("app".into(), vec!["route:list".into(), "--json".into()], &mut console)
            .await;

        assert_eq!(code, 141);
        assert_eq!(console.into_output().1, "", "nothing is written to stderr");
    }

    #[test]
    fn failures_after_stdout_closes_still_print_their_message() {
        let app = Application::configure()
            .replace_env(crate::config::Env::default())
            .create();
        let mut console = Console::with_closed_stdout();
        console.line("a row nobody reads");

        let failure = crate::Error::from(std::io::Error::other("The import failed."));
        assert_eq!(app.command_failed(&failure, &mut console), 1);
        assert_eq!(console.into_output().1, "The import failed.\n");
    }

    #[test]
    fn other_broken_pipes_are_failures() {
        let app = Application::configure()
            .replace_env(crate::config::Env::default())
            .create();
        let mut console = Console::captured();
        let child = std::io::Error::from(std::io::ErrorKind::BrokenPipe);

        assert_eq!(app.command_failed(&crate::Error::from(child), &mut console), 1);
        assert!(console.into_output().1.to_lowercase().contains("broken pipe"));
    }

    #[test]
    fn a_builder_whose_application_cant_start_exits_with_a_failure() {
        let code = Application::configure()
            .replace_env(crate::config::Env::from_iter([("APP_DEBUG", "maybe")]))
            .run();

        assert_eq!(code, ExitCode::FAILURE);
    }

    #[test]
    fn the_process_stops_when_its_log_files_cant_be_written() {
        let file = std::env::temp_dir().join(format!("laravel-unwritable-logs-{}", std::process::id()));
        std::fs::write(&file, "").unwrap();
        let app = Application::configure()
            .replace_env(crate::config::Env::default())
            .with_config({
                let file = file.clone();
                move |config, _| {
                    config.app.base_path = file;
                    config.logging.channels = vec![LogChannel::stderr(), LogChannel::daily()];
                }
            })
            .create();

        let code = app.run_with("app".into(), vec!["route:list".into()]);

        let _ = std::fs::remove_file(file);
        assert_eq!(code, ExitCode::FAILURE);
    }

    #[derive(clap::Parser)]
    #[command(name = "block")]
    struct BlockCommand;

    #[crate::console::command]
    impl BlockCommand {
        async fn handle(self) {
            drop(tokio::task::spawn_blocking(|| {
                loop {
                    std::thread::park();
                }
            }));
        }
    }

    #[test]
    fn the_process_exits_without_waiting_for_blocking_work_that_never_returns() {
        if std::env::var_os("LARAVEL_TEST_BLOCKING_EXIT").is_some() {
            std::thread::spawn(|| {
                std::thread::sleep(Duration::from_secs(30));
                std::process::exit(101);
            });
            let app = Application::configure()
                .replace_env(crate::config::Env::default())
                .with_config(|config, _| config.logging.channels = Vec::new())
                .with_commands(|commands, _| {
                    commands.add::<BlockCommand>();
                })
                .create();
            assert_eq!(app.run_with("app".into(), vec!["block".into()]), ExitCode::SUCCESS);
            return;
        }

        let output = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "foundation::console::tests::the_process_exits_without_waiting_for_blocking_work_that_never_returns",
            ])
            .env("LARAVEL_TEST_BLOCKING_EXIT", "1")
            .output()
            .unwrap();

        assert!(output.status.success(), "{output:?}");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn nested_and_test_commands_leave_background_work_running() {
        let release = Arc::new(Notify::new());
        let finished = Arc::new(AtomicUsize::new(0));
        let app = working({
            let release = Arc::clone(&release);
            let finished = Arc::clone(&finished);
            async move {
                release.notified().await;
                finished.store(1, Ordering::SeqCst);
                Ok(())
            }
        })
        .create();

        let code = tokio::time::timeout(
            Duration::from_secs(5),
            app.run_command("app".into(), vec!["work".into()], &mut Console::captured()),
        )
        .await
        .expect("nested commands do not wait for background work");

        assert_eq!(code, 0);
        assert_eq!(finished.load(Ordering::SeqCst), 0);
        assert!(!app.shared.shutdown.is_stopping());
        release.notify_one();
    }

    #[cfg(feature = "database-sqlite")]
    #[tokio::test]
    async fn server_drains_database_work_before_closing_pools_and_bounds_external_leases() -> crate::Result<()> {
        use crate::config::database::ConnectionConfig;
        use crate::db::{DatabaseManager, sqlx::Sqlite};

        for held_lease in [false, true] {
            let app = Application::configure()
                .replace_env(crate::config::Env::default())
                .with_config(|config, _| {
                    config.server.shutdown_timeout = Duration::from_millis(200).into();
                    config
                        .database
                        .connections
                        .insert("sqlite".into(), ConnectionConfig::new("sqlite::memory:"));
                    config.database.default = "sqlite".into();
                })
                .create();
            let manager = app.resolve::<DatabaseManager>().await;
            let connection = manager.default_connection()?.typed::<Sqlite>()?;
            let pool = connection.native_pool().await?;
            let lease = if held_lease { Some(pool.acquire().await?) } else { None };
            let entered = Arc::new(Notify::new());
            let release = Arc::new(Notify::new());
            let finished = Arc::new(AtomicUsize::new(0));
            app.scope({
                let entered = Arc::clone(&entered);
                let release = Arc::clone(&release);
                let finished = Arc::clone(&finished);
                async move || {
                    crate::task::background(async move {
                        let mut tx = connection.begin().await?;
                        entered.notify_one();
                        release.notified().await;
                        assert_eq!(tx.query("SELECT 42").scalar::<i64>().await?, Some(42));
                        tx.commit().await?;
                        assert_eq!(connection.query("SELECT 17").scalar::<i64>().await?, Some(17));
                        finished.store(1, Ordering::SeqCst);
                        Ok(())
                    })
                }
            })
            .await?;
            tokio::time::timeout(Duration::from_secs(5), entered.notified())
                .await
                .unwrap();
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
            let observer = app.clone();
            let (stop, stopped) = tokio::sync::oneshot::channel();
            let mut server = tokio::spawn(async move {
                app.serve_on(listener, &mut Console::captured(), async {
                    let _ = stopped.await;
                })
                .await
            });
            stop.send(()).unwrap();
            tokio::time::timeout(Duration::from_secs(5), observer.shared.shutdown.begun())
                .await
                .unwrap();
            assert!(
                !pool.is_closed(),
                "in-flight work may still acquire database connections"
            );
            release.notify_one();
            let result = tokio::time::timeout(Duration::from_secs(4), &mut server).await;
            if result.is_err() {
                server.abort();
            }
            result
                .expect("held native leases cannot hang server shutdown")
                .unwrap()?;
            assert_eq!(finished.load(Ordering::SeqCst), 1);
            assert!(pool.is_closed());
            drop(lease);
            tokio::time::timeout(Duration::from_secs(5), manager.shutdown())
                .await
                .unwrap();
            assert_eq!(pool.size(), 0);
        }
        Ok(())
    }

    #[cfg(feature = "database-sqlite")]
    #[tokio::test(flavor = "multi_thread")]
    async fn a_command_closes_database_pools_after_its_background_work() -> crate::Result<()> {
        use crate::config::database::ConnectionConfig;
        use crate::db::{DatabaseManager, sqlx::Sqlite};

        let entered = Arc::new(Notify::new());
        let release = Arc::new(Notify::new());
        let finished = Arc::new(AtomicUsize::new(0));
        let app = working({
            let entered = Arc::clone(&entered);
            let release = Arc::clone(&release);
            let finished = Arc::clone(&finished);
            async move {
                let connection = crate::resolve::<DatabaseManager>()
                    .await?
                    .default_connection()?
                    .typed::<Sqlite>()?;
                let mut tx = connection.begin().await?;
                entered.notify_one();
                release.notified().await;
                assert_eq!(tx.query("SELECT 42").scalar::<i64>().await?, Some(42));
                tx.commit().await?;
                assert_eq!(connection.query("SELECT 17").scalar::<i64>().await?, Some(17));
                finished.store(1, Ordering::SeqCst);
                Ok(())
            }
        })
        .with_config(|config, _| {
            config
                .database
                .connections
                .insert("sqlite".into(), ConnectionConfig::new("sqlite::memory:"));
            config.database.default = "sqlite".into();
        })
        .create();
        let pool = app
            .resolve::<DatabaseManager>()
            .await
            .default_connection()?
            .typed::<Sqlite>()?
            .native_pool()
            .await?;

        let finishing = run_and_finish(&app, "work", std::future::pending());
        let ((code, _), ()) = tokio::join!(finishing, async {
            tokio::time::timeout(Duration::from_secs(5), entered.notified())
                .await
                .unwrap();
            tokio::time::timeout(Duration::from_secs(5), app.shared.shutdown.begun())
                .await
                .unwrap();
            assert!(
                !pool.is_closed(),
                "background work may still acquire database connections"
            );
            release.notify_one();
        });

        assert_eq!(code, 0);
        assert_eq!(finished.load(Ordering::SeqCst), 1);
        assert!(pool.is_closed());
        Ok(())
    }

    #[tokio::test]
    async fn an_idle_server_waits_for_background_work_then_enforces_its_deadline() {
        for (complete, event) in [(true, true), (false, true), (true, false), (false, false)] {
            struct Payload(Arc<AtomicUsize>);
            impl Drop for Payload {
                fn drop(&mut self) {
                    self.0.fetch_add(1, Ordering::SeqCst);
                }
            }
            let entered = Arc::new(Notify::new());
            let release = Arc::new(Notify::new());
            let dropped = Arc::new(AtomicUsize::new(0));
            let app = Application::configure()
                .replace_env(crate::config::Env::default())
                .with_config(|config, _| {
                    config.server.shutdown_timeout = Duration::from_millis(200).into();
                })
                .with_events({
                    let entered = Arc::clone(&entered);
                    let release = Arc::clone(&release);
                    move |events, _| {
                        events.listen(move |event: Event<Payload>| {
                            let entered = Arc::clone(&entered);
                            let release = Arc::clone(&release);
                            async move {
                                entered.notify_one();
                                release.notified().await;
                                drop(event);
                            }
                        });
                    }
                })
                .create();
            app.scope(async || {
                let payload = Payload(Arc::clone(&dropped));
                if event {
                    event::dispatch_background(payload).unwrap();
                } else {
                    let entered = Arc::clone(&entered);
                    let release = Arc::clone(&release);
                    crate::task::background(async move {
                        entered.notify_one();
                        release.notified().await;
                        drop(payload);
                        Ok(())
                    })
                    .unwrap();
                }
            })
            .await;
            tokio::time::timeout(Duration::from_secs(5), entered.notified())
                .await
                .unwrap();
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let observer = app.clone();
            let (stop, stopped) = tokio::sync::oneshot::channel();
            let mut server = tokio::spawn(async move {
                app.serve_on(listener, &mut Console::captured(), async {
                    let _ = stopped.await;
                })
                .await
            });
            stop.send(()).unwrap();
            tokio::time::timeout(Duration::from_secs(5), observer.shared.shutdown.begun())
                .await
                .unwrap();
            let error = observer
                .scope(async || crate::task::background(async { Ok(()) }))
                .await
                .unwrap_err();
            assert!(error.to_string().contains("shutting down"));
            assert!(!server.is_finished(), "background work holds the idle server open");
            if complete {
                release.notify_one();
            }
            let result = tokio::time::timeout(Duration::from_secs(5), &mut server).await;
            if result.is_err() {
                server.abort();
            }
            result
                .expect("shutdown is bounded")
                .expect("server did not panic")
                .unwrap();
            assert_eq!(dropped.load(Ordering::SeqCst), 1);
        }
    }

    fn serving(
        app: Application,
    ) -> (
        tokio::sync::oneshot::Sender<()>,
        tokio::task::JoinHandle<std::io::Result<()>>,
    ) {
        let (stop, stopped) = tokio::sync::oneshot::channel();
        let server = tokio::spawn(async move {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
            app.serve_on(listener, &mut Console::captured(), async {
                let _ = stopped.await;
            })
            .await
        });
        (stop, server)
    }

    async fn stopped(server: tokio::task::JoinHandle<std::io::Result<()>>) -> std::io::Result<()> {
        tokio::time::timeout(Duration::from_secs(5), server)
            .await
            .expect("shutdown is bounded")
            .expect("server did not panic")
    }

    #[tokio::test]
    async fn connections_past_the_limit_wait_until_an_open_one_closes() {
        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};

        async fn request(address: SocketAddr) -> tokio::net::TcpStream {
            let mut stream = tokio::net::TcpStream::connect(address).await.unwrap();
            stream
                .write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")
                .await
                .unwrap();
            stream
        }

        async fn status_line(stream: &mut tokio::net::TcpStream, wait: Duration) -> Option<String> {
            let mut buffer = [0; 12];
            tokio::time::timeout(wait, stream.read_exact(&mut buffer))
                .await
                .ok()?
                .unwrap();
            Some(String::from_utf8_lossy(&buffer).into_owned())
        }

        for (max, waits) in [(1, true), (0, false)] {
            let app = Application::configure()
                .replace_env(crate::config::Env::default())
                .with_config(move |config, _| config.server.max_connections = max)
                .create();
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let address = listener.local_addr().unwrap();
            let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
            let server = tokio::spawn(async move {
                app.serve_on(listener, &mut Console::captured(), async {
                    let _ = stopped.await;
                })
                .await
            });

            // The first connection stays open after its response, as a keep-alive connection does...
            let mut first = request(address).await;
            let status = status_line(&mut first, Duration::from_secs(5)).await;
            assert_eq!(status.as_deref(), Some("HTTP/1.1 404"));

            let mut second = request(address).await;
            let early = status_line(&mut second, Duration::from_millis(300)).await;
            assert_eq!(early.is_none(), waits, "max_connections = {max}");

            if waits {
                drop(first);
                let status = status_line(&mut second, Duration::from_secs(5)).await;
                assert_eq!(status.as_deref(), Some("HTTP/1.1 404"));
            }

            drop(second);
            stop.send(()).unwrap();
            tokio::time::timeout(Duration::from_secs(5), server)
                .await
                .expect("shutdown is bounded")
                .unwrap()
                .unwrap();
        }
    }

    #[tokio::test]
    async fn serving_repeats_ticks_through_failures_then_runs_shutdown_ticks_once() {
        use crate::time::ToSpan;

        struct Ticked(AtomicUsize);
        let reported = Arc::new(AtomicUsize::new(0));
        let flushed = Arc::new(AtomicUsize::new(0));
        let app = Application::configure()
            .replace_env(crate::config::Env::default())
            .with_services(|services| {
                services.instance(Ticked(AtomicUsize::new(0)));
            })
            .with_errors({
                let reported = Arc::clone(&reported);
                move |errors, _| {
                    errors.report_all(move |error| {
                        assert!(error.to_string().contains("tick error"));
                        assert_eq!(
                            crate::context::get::<String>("job").as_deref(),
                            Some("count"),
                            "reported in the tick's context"
                        );
                        reported.fetch_add(1, Ordering::SeqCst);
                    });
                }
            })
            .with_ticks({
                let flushed = Arc::clone(&flushed);
                move |ticks, _| {
                    ticks
                        .every(20.milliseconds(), |ticked: Inject<Ticked>| async move {
                            crate::context::add("job", "count");
                            ticked.0.fetch_add(1, Ordering::SeqCst);
                            Err::<(), _>(crate::error::fail("tick error"))
                        })
                        .immediately();
                    ticks
                        .every(1.hour(), move || {
                            let flushed = Arc::clone(&flushed);
                            async move {
                                flushed.fetch_add(1, Ordering::SeqCst);
                            }
                        })
                        .run_on_shutdown();
                }
            })
            .create();
        let ticked = app.resolve::<Ticked>().await;
        let (stop, server) = serving(app);

        tokio::time::timeout(Duration::from_secs(5), async {
            while reported.load(Ordering::SeqCst) < 3 {
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        })
        .await
        .expect("failing ticks keep repeating");
        assert_eq!(flushed.load(Ordering::SeqCst), 0);
        stop.send(()).unwrap();
        stopped(server).await.unwrap();
        assert_eq!(flushed.load(Ordering::SeqCst), 1);

        let total = ticked.0.load(Ordering::SeqCst);
        tokio::time::sleep(Duration::from_millis(60)).await;
        assert_eq!(ticked.0.load(Ordering::SeqCst), total, "ticks stop with the server");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_worker_runs_the_ticks_its_host_allows_then_their_shutdown_ticks() {
        use crate::foundation::Host;
        use crate::time::ToSpan;

        #[derive(clap::Parser)]
        #[command(name = "hosting")]
        struct Hosting;

        #[crate::console::command]
        impl Hosting {
            async fn handle(self, events: Inject<Events>) {
                crate::task::ticks::start(
                    &Context::expect("hosting"),
                    Host::Worker {
                        connection: "redis".to_owned(),
                        queues: vec!["high".to_owned()],
                    },
                );
                while events.0.lock().unwrap().is_empty() {
                    tokio::time::sleep(Duration::from_millis(5)).await;
                }
            }
        }

        #[derive(Default)]
        struct Events(std::sync::Mutex<Vec<String>>);
        impl Events {
            fn push(&self, event: impl Into<String>) {
                self.0.lock().unwrap().push(event.into());
            }
        }

        let app = Application::configure()
            .replace_env(crate::config::Env::default())
            .with_services(|services| {
                services.instance(Events::default());
            })
            .with_commands(|commands, _| {
                commands.add::<Hosting>();
            })
            .with_ticks(|ticks, _| {
                ticks
                    .every(1.hour(), |events: Inject<Events>| async move { events.push("server") })
                    .immediately()
                    .when(Host::is_server)
                    .run_on_shutdown();
                ticks
                    .every(1.hour(), |events: Inject<Events>| async move {
                        events.push(format!("{:?}", crate::foundation::host()))
                    })
                    .immediately()
                    .when(Host::is_worker);
                ticks
                    .every(1.hour(), |events: Inject<Events>| async move {
                        events.push("high worker stopping")
                    })
                    .when(|host| matches!(host, Host::Worker { queues, .. } if queues == &["high"]))
                    .run_on_shutdown();
            })
            .create();

        let (code, _) = run_and_finish(&app, "hosting", std::future::pending()).await;

        assert_eq!(code, 0);
        let events = app.resolve::<Events>().await;
        assert_eq!(
            *events.0.lock().unwrap(),
            [
                r#"Some(Worker { connection: "redis", queues: ["high"] })"#,
                "high worker stopping"
            ],
        );
        assert!(app.host().is_some_and(|host| host.is_worker()));
    }

    #[tokio::test]
    async fn shutdown_ticks_flush_what_background_work_from_requests_buffered() {
        use crate::time::ToSpan;

        struct Buffer(AtomicUsize);
        let flushed = Arc::new(std::sync::Mutex::new(Vec::new()));
        let app = Application::configure()
            .replace_env(crate::config::Env::default())
            .with_services(|services| {
                services.instance(Buffer(AtomicUsize::new(0)));
            })
            .with_ticks({
                let flushed = Arc::clone(&flushed);
                move |ticks, _| {
                    ticks
                        .every(1.hour(), move |buffer: Inject<Buffer>| {
                            let flushed = Arc::clone(&flushed);
                            async move { flushed.lock().unwrap().push(buffer.0.swap(0, Ordering::SeqCst)) }
                        })
                        .run_on_shutdown();
                }
            })
            .create();
        let buffer = app.resolve::<Buffer>().await;
        app.scope(async || {
            crate::task::background(async {
                tokio::time::sleep(Duration::from_millis(100)).await;
                crate::resolve::<Buffer>().await?.0.fetch_add(1, Ordering::SeqCst);
                Ok(())
            })
            .unwrap();
        })
        .await;
        let (stop, server) = serving(app);

        tokio::time::sleep(Duration::from_millis(20)).await;
        stop.send(()).unwrap();
        stopped(server).await.unwrap();
        assert_eq!(
            *flushed.lock().unwrap(),
            [1],
            "the shutdown tick flushed the background work's count"
        );
        assert_eq!(buffer.0.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn shutdown_waits_for_a_tick_in_progress_within_its_deadline() {
        use crate::time::ToSpan;

        for complete in [true, false] {
            let entered = Arc::new(Notify::new());
            let release = Arc::new(Notify::new());
            let events = Arc::new(std::sync::Mutex::new(Vec::new()));
            let app = Application::configure()
                .replace_env(crate::config::Env::default())
                .with_config(|config, _| {
                    config.server.shutdown_timeout = Duration::from_millis(200).into();
                })
                .with_ticks({
                    let (entered, release, events) = (Arc::clone(&entered), Arc::clone(&release), Arc::clone(&events));
                    move |ticks, _| {
                        let held = Arc::clone(&events);
                        ticks
                            .every(1.hour(), move || {
                                let (entered, release, events) =
                                    (Arc::clone(&entered), Arc::clone(&release), Arc::clone(&held));
                                async move {
                                    entered.notify_one();
                                    release.notified().await;
                                    events.lock().unwrap().push("held");
                                }
                            })
                            .immediately();
                        ticks
                            .every(1.hour(), move || {
                                let events = Arc::clone(&events);
                                async move { events.lock().unwrap().push("final") }
                            })
                            .run_on_shutdown();
                    }
                })
                .create();
            let (stop, mut server) = serving(app);
            tokio::time::timeout(Duration::from_secs(5), entered.notified())
                .await
                .unwrap();

            stop.send(()).unwrap();
            tokio::time::sleep(Duration::from_millis(50)).await;
            assert!(!server.is_finished(), "a tick in progress holds the server open");
            if complete {
                release.notify_one();
            }
            let result = tokio::time::timeout(Duration::from_secs(5), &mut server).await;
            if result.is_err() {
                server.abort();
            }
            result.expect("shutdown is bounded").unwrap().unwrap();
            let expected: &[&str] = if complete { &["held", "final"] } else { &[] };
            assert_eq!(*events.lock().unwrap(), expected);
        }
    }
}

/// The application a command runs in, for a command that takes `&Application`.
#[derive(Default)]
struct CommandApplication(std::sync::OnceLock<Application>);

impl Application {
    /// How a command runs another command in this application, as the scheduler does.
    fn invoke(&self) -> crate::console::Invoke {
        let app = self.clone();

        crate::console::Invoke(Arc::new(move |arguments, console| {
            let app = app.clone();
            Box::pin(async move { app.run_command(OsString::from("app"), arguments, console).await })
        }))
    }

    /// The application of the running command.
    ///
    /// `#[command]` passes this application to a handler that takes `&Application`.
    ///
    /// # Panics
    ///
    /// Panics outside a console command.
    #[doc(hidden)]
    #[must_use]
    #[track_caller]
    pub fn __of_command() -> Self {
        Context::expect("a command's `&Application` argument")
            .local::<CommandApplication>()
            .0
            .get()
            .cloned()
            .expect("a command takes `&Application` only when the application runs it")
    }
}