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
use std::time::Duration;

use laravel::Application;
use laravel::config::database::ConnectionConfig;
use laravel::config::{Config, Env};
use laravel::container::Inject;
use laravel::db;
use laravel::event::Event;
use laravel::queue::Queueable;
use laravel::queue::events::{JobFailed, JobProcessed};
use laravel::queue::{Attempt, JobId, QueueSizes, job};
use laravel::rate_limit::{self, Limit};
use laravel::testing::{MakesConsoleRequests, TestCommandResult};
use laravel::time::{Timestamp, ToSpan};
use serde_json::json;

use crate::queue::Records;
use crate::queue::database::{create_failed_table, create_table};

#[derive(Queueable)]
struct Flaky {
    id: u32,
    failures: u32,
}

#[job(tries = 3, backoff = [10.seconds(), 1.minutes()])]
impl Flaky {
    async fn handle(self, records: Inject<Records>, attempt: &Attempt) -> laravel::Result<()> {
        records.push(format!("flaky {} ran as attempt {}", self.id, attempt.number()));
        if attempt.number() <= self.failures {
            return Err(laravel::abort_with(500, format!("flaky {} broke", self.id)));
        }

        Ok(())
    }

    async fn failed(self, error: &laravel::Error, records: Inject<Records>) {
        records.push(format!("failed hook for flaky {}: {error}", self.id));
    }
}

#[derive(Queueable)]
struct Reject;

#[job]
impl Reject {
    async fn handle(self) -> laravel::Result<()> {
        Err(std::io::Error::other("payload \x1b]0;pwned\x07 rejected").into())
    }
}

#[derive(Queueable)]
struct Transcode;

#[job(tries = 2)]
impl Transcode {
    async fn handle(self) -> laravel::Result<()> {
        laravel::context::add("step", "transcoding");

        Err(laravel::abort_with(500, "the codec is missing"))
    }
}

#[derive(Queueable)]
struct Poll;

#[job(queue = "polls")]
impl Poll {
    async fn handle(self, records: Inject<Records>, attempt: &Attempt) {
        records.push(format!("poll ran as attempt {}", attempt.number()));
        attempt.release(30.seconds());
    }
}

#[derive(Queueable)]
struct PollForAnHour;

#[job(queue = "polls", retry_for = 1.hours())]
impl PollForAnHour {
    async fn handle(self, attempt: &Attempt) {
        attempt.release(30.seconds());
    }
}

#[derive(Queueable)]
struct SendNewsletter;

#[job(queue = "newsletters", retry_for = 1.hours())]
impl SendNewsletter {
    async fn handle(self, records: Inject<Records>) -> laravel::Result<()> {
        rate_limit::attempt("newsletter", Limit::per_minute(1)).await??;
        records.push("newsletter sent");

        Ok(())
    }
}

#[derive(Queueable)]
struct SendNewsletterSoon;

#[job(queue = "newsletters", retry_for = 30.seconds())]
impl SendNewsletterSoon {
    async fn handle(self) -> laravel::Result<()> {
        rate_limit::attempt("newsletter", Limit::per_minute(1)).await??;

        Ok(())
    }
}

#[derive(Queueable)]
struct ChargeCard;

#[job(retry_for = 1.minutes(), backoff = 45.seconds())]
impl ChargeCard {
    async fn handle(self) -> laravel::Result<()> {
        Err(laravel::abort_with(503, "the payment gateway is down"))
    }
}

#[derive(Queueable)]
struct Unsteady(u32);

#[job(tries = 10, max_errors = 2)]
impl Unsteady {
    async fn handle(self, records: Inject<Records>, attempt: &Attempt) -> laravel::Result<()> {
        records.push(format!("unsteady {} ran as attempt {}", self.0, attempt.number()));
        if attempt.number() == 1 {
            attempt.release(30.seconds());
            return Ok(());
        }

        Err(laravel::abort_with(500, format!("unsteady {} broke", self.0)))
    }
}

#[derive(Queueable)]
struct Note(String);

#[job]
impl Note {
    async fn handle(self, records: Inject<Records>) {
        records.push(self.0);
    }
}

#[derive(Queueable)]
struct Slow;

#[job(timeout = 100.milliseconds())]
impl Slow {
    async fn handle(self) {
        tokio::time::sleep(Duration::from_secs(30)).await;
    }
}

#[derive(Queueable)]
struct Meet(u32);

#[derive(Default)]
struct Meeting(tokio::sync::watch::Sender<(usize, bool)>);

struct Present<'a>(&'a Meeting);

impl Drop for Present<'_> {
    fn drop(&mut self) {
        self.0.0.send_modify(|(present, _)| *present -= 1);
    }
}

#[job(timeout = 1.seconds())]
impl Meet {
    async fn handle(self, meeting: Inject<Meeting>, records: Inject<Records>) {
        meeting.0.send_modify(|(present, met)| {
            *present += 1;
            *met |= *present >= 2;
        });
        let _present = Present(&meeting);
        let _ = meeting.0.subscribe().wait_for(|(_, met)| *met).await;
        records.push(format!("met {}", self.0));
    }
}

#[derive(Queueable)]
struct Hold;

#[derive(Default)]
struct Gate(tokio::sync::watch::Sender<bool>);

#[job(timeout = 30.seconds())]
impl Hold {
    async fn handle(self, gate: Inject<Gate>) {
        let _ = gate.0.subscribe().wait_for(|open| *open).await;
    }
}

#[derive(Default)]
struct Seen(Records);

/// The errors the application reported, each with the `step` context value it was reported with.
#[derive(Clone, Default)]
struct Reported(std::sync::Arc<Records>);

const NOW: i64 = 1_800_000_000;

/// The time `seconds` after the epoch.
fn at(seconds: i64) -> Timestamp {
    Timestamp::from_second(seconds).unwrap()
}

/// The time `seconds` after the epoch as an SQL literal.
fn sql_at(seconds: i64) -> String {
    format!("'{}'", at(seconds).strftime("%Y-%m-%dT%H:%M:%S+00:00"))
}

async fn application(url: impl Into<String>) -> Application {
    application_with(url, |_| {}).await
}

async fn application_with(url: impl Into<String>, configure: impl FnOnce(&mut Config) + 'static) -> Application {
    let url = url.into();
    let reported = Reported::default();
    let app = Application::configure()
        .replace_env(Env::default())
        .with_config(move |config, _| {
            configure(config);
            config.queue.default = "database".into();
            config.database.default = "primary".into();
            config
                .database
                .connections
                .insert("primary".into(), ConnectionConfig::new(url));
        })
        .with_services({
            let reported = reported.clone();
            move |services| {
                services.instance(Records::default());
                services.instance(Seen::default());
                services.instance(Meeting::default());
                services.instance(Gate::default());
                services.instance(reported);
            }
        })
        .with_errors(move |errors, _| {
            errors.report_all(move |error| {
                let step = laravel::context::get::<String>("step");
                reported.0.push(format!("{error} with step {step:?}"));
            });
        })
        .with_events(|events, _| {
            events.listen(|event: Event<JobProcessed>, seen: Inject<Seen>| async move {
                seen.0.push(format!("{} {}", event.job.name, event.outcome));
            });
            events.listen(|event: Event<JobFailed>, seen: Inject<Seen>| async move {
                seen.0
                    .push(format!("{} failed for good: {}", event.job.name, event.error));
            });
        })
        .create();
    app.scope(async || {
        let connection = db::default_connection()?;
        for table in ["jobs", "failed_jobs"] {
            connection
                .query(db::sqlx::AssertSqlSafe(format!("DROP TABLE IF EXISTS {table}")))
                .statement()
                .await?;
        }
        connection.query(create_table(connection.driver())).statement().await?;
        connection
            .query(create_failed_table(connection.driver()))
            .statement()
            .await
    })
    .await
    .unwrap();
    app.travel_to(Timestamp::from_second(NOW).unwrap());

    app
}

#[cfg(feature = "database-sqlite")]
fn sqlite(name: &str) -> (crate::support::TempDir, String) {
    let directory = crate::support::TempDir::new(name);
    let url = format!("sqlite://{}?mode=rwc", directory.join("queue.sqlite").display());

    (directory, url)
}

async fn work(app: &Application, options: &str) -> TestCommandResult {
    tokio::time::timeout(
        Duration::from_secs(30),
        app.command(&format!("queue:work --stop-when-empty {options}")),
    )
    .await
    .expect("the worker should stop once no job is available")
}

async fn dispatch<J: laravel::queue::Job>(app: &Application, job: J) -> JobId {
    app.scope(async || laravel::queue::dispatch(job).await).await.unwrap()
}

async fn statement(app: &Application, sql: &str) {
    app.scope(async || {
        db::default_connection()?
            .query(db::sqlx::AssertSqlSafe(sql.to_owned()))
            .statement()
            .await
    })
    .await
    .unwrap();
}

#[derive(Debug, PartialEq, Eq, db::FromRow)]
struct Row {
    queue: String,
    attempts: i64,
    reserved_at: Option<Timestamp>,
    available_at: Timestamp,
}

async fn rows(app: &Application) -> Vec<Row> {
    app.scope(async || {
        db::default_connection()?
            .query("SELECT queue, attempts, reserved_at, available_at FROM jobs ORDER BY id")
            .select_as()
            .await
    })
    .await
    .unwrap()
}

#[derive(Debug, db::FromRow)]
struct FailedRow {
    job_id: String,
    connection: String,
    queue: String,
    error: String,
}

async fn failed(app: &Application) -> Vec<FailedRow> {
    app.scope(async || {
        db::default_connection()?
            .query("SELECT job_id, connection, queue, error FROM failed_jobs ORDER BY id")
            .select_as()
            .await
    })
    .await
    .unwrap()
}

async fn records(app: &Application) -> Vec<String> {
    app.resolve::<Records>().await.all()
}

async fn reported(app: &Application) -> Vec<String> {
    app.resolve::<Reported>().await.0.all()
}

async fn seen(app: &Application) -> Vec<String> {
    app.resolve::<Seen>().await.0.all()
}

fn row(queue: &str, attempts: i64, available_in: i64) -> Row {
    Row {
        queue: queue.into(),
        attempts,
        reserved_at: None,
        available_at: at(NOW + available_in),
    }
}

async fn worker_contract(app: &Application) {
    let flaky = "integration::queue_worker::Flaky";
    let first = dispatch(app, Flaky { id: 1, failures: 2 }).await;
    let second = dispatch(app, Flaky { id: 2, failures: 5 }).await;

    let result = work(app, "").await;
    result.assert_successful();
    assert_eq!(
        result.error_output().matches(" retrying  ").count(),
        2,
        "{}",
        result.error_output()
    );
    assert_eq!(
        rows(app).await,
        [row("default", 1, 10), row("default", 1, 10)],
        "a failure waits out the first backoff"
    );

    app.travel(10.seconds());
    work(app, "").await.assert_successful();
    assert_eq!(
        rows(app).await,
        [row("default", 2, 10 + 60), row("default", 2, 10 + 60)],
        "the second failure waits out the second backoff"
    );

    app.travel(1.minutes());
    let result = work(app, "").await;
    assert!(
        crate::support::outcomes(result.error_output()).contains(&"done"),
        "{}",
        result.error_output()
    );
    assert!(result.error_output().contains(" failed  "), "{}", result.error_output());
    assert!(rows(app).await.is_empty());
    assert_eq!(
        records(app).await,
        [
            "flaky 1 ran as attempt 1",
            "flaky 2 ran as attempt 1",
            "flaky 1 ran as attempt 2",
            "flaky 2 ran as attempt 2",
            "flaky 1 ran as attempt 3",
            "flaky 2 ran as attempt 3",
            "failed hook for flaky 2: flaky 2 broke",
        ]
    );
    assert_eq!(
        seen(app).await,
        [
            format!("{flaky} retrying"),
            format!("{flaky} retrying"),
            format!("{flaky} retrying"),
            format!("{flaky} retrying"),
            format!("{flaky} succeeded"),
            format!("{flaky} failed for good: flaky 2 broke"),
            format!("{flaky} failed"),
        ]
    );
    let failures = failed(app).await;
    assert_eq!(failures.len(), 1);
    assert_eq!(
        (
            failures[0].job_id.as_str(),
            failures[0].connection.as_str(),
            failures[0].queue.as_str()
        ),
        (second.to_string().as_str(), "database", "default")
    );
    assert_eq!(failures[0].error, "flaky 2 broke");
    assert_ne!(first, second);

    app.command("queue:failed")
        .await
        .assert_successful()
        .assert_output_contains(&second.to_string())
        .assert_output_contains(flaky);
    app.command(&format!("queue:retry {second}"))
        .await
        .assert_successful()
        .assert_error_output_contains("` retried.");
    assert!(failed(app).await.is_empty());
    assert_eq!(rows(app).await, [row("default", 0, 70)], "a retried job starts over");
    app.command("queue:clear").await.assert_successful();

    dispatch(app, Flaky { id: 3, failures: 0 }).await;
    dispatch(app, Poll).await;
    statement(
        app,
        &format!("UPDATE jobs SET attempts = 1, reserved_at = {}", sql_at(NOW - 120)),
    )
    .await;
    let result = work(app, "--queue=default,polls").await;
    result.assert_successful();
    let records = records(app).await;
    assert_eq!(records.last().unwrap(), "flaky 3 ran as attempt 2", "{records:?}");
    assert!(
        !records.iter().any(|record| record.starts_with("poll")),
        "a job without tries left doesn't run again"
    );
    let failures = failed(app).await;
    assert_eq!(failures.len(), 1);
    assert!(
        failures[0]
            .error
            .contains("has been attempted more than its 1 `tries` allow"),
        "{}",
        failures[0].error
    );

    dispatch(app, Hold).await;
    let held = async {
        let reserved_at = wait_for_reservation(app, |_| true).await;
        app.travel(45.seconds());
        wait_for_reservation(app, |renewed| renewed == reserved_at + 45).await;
        app.travel(30.seconds());
        work(app, "").await.assert_successful();
        assert_eq!(rows(app).await[0].attempts, 1, "another worker took the running job");
        app.resolve::<Gate>().await.0.send_replace(true);
    };
    let (holding, ()) = tokio::join!(work(app, ""), held);
    holding.assert_successful().assert_error_output_contains("Hold  ");

    for note in 0..40 {
        dispatch(app, Note(format!("note {note:02}"))).await;
    }
    let (first, second) = tokio::join!(work(app, "--concurrency=4"), work(app, "--concurrency=4"));
    first.assert_successful();
    second.assert_successful();
    let mut notes: Vec<_> = records_after(app, "note").await;
    notes.sort();
    assert_eq!(notes, (0..40).map(|note| format!("note {note:02}")).collect::<Vec<_>>());
    assert!(rows(app).await.is_empty());
}

async fn wait_for_reservation(app: &Application, expected: impl Fn(i64) -> bool) -> i64 {
    let reserved_at = async {
        loop {
            if let Some(reserved_at) = rows(app)
                .await
                .first()
                .and_then(|row| row.reserved_at)
                .map(Timestamp::as_second)
                && expected(reserved_at)
            {
                return reserved_at;
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    };

    tokio::time::timeout(Duration::from_secs(20), reserved_at)
        .await
        .expect("the worker should renew the job's reservation")
}

async fn records_after(app: &Application, prefix: &str) -> Vec<String> {
    records(app)
        .await
        .into_iter()
        .filter(|record| record.starts_with(prefix))
        .collect()
}

async fn sizes(app: &Application) -> QueueSizes {
    app.scope(async || {
        let manager = laravel::queue::manager();
        manager.sizes("database", "default").await
    })
    .await
    .unwrap()
    .expect("the database driver counts its jobs")
}

async fn sizes_contract(app: &Application) {
    dispatch(app, Note("now".into())).await;
    app.scope(async || Note("later".into()).dispatch().delay(30.seconds()).await)
        .await
        .unwrap();
    dispatch(app, Note("running".into())).await;
    dispatch(app, Note("abandoned".into())).await;
    statement(
        app,
        &format!(
            "UPDATE jobs SET attempts = 1, reserved_at = {} WHERE payload LIKE '%running%'",
            sql_at(NOW)
        ),
    )
    .await;
    statement(
        app,
        &format!(
            "UPDATE jobs SET attempts = 1, reserved_at = {} WHERE payload LIKE '%abandoned%'",
            sql_at(NOW - 120)
        ),
    )
    .await;

    assert_eq!(
        sizes(app).await,
        QueueSizes {
            pending: 2,
            delayed: 1,
            reserved: 1,
            oldest_pending: Some(Timestamp::from_second(NOW).unwrap()),
            approximate: false,
        }
    );
    app.travel(30.seconds());
    let due = sizes(app).await;
    assert_eq!((due.pending, due.delayed, due.reserved), (3, 0, 1));
    app.travel(1.minutes());
    assert_eq!(sizes(app).await.pending, 4);

    statement(app, "DELETE FROM jobs").await;
    app.travel_to(Timestamp::from_second(NOW).unwrap());
    assert_eq!(sizes(app).await, QueueSizes::default());
}

#[cfg(feature = "database-sqlite")]
#[tokio::test]
async fn sqlite_workers_retry_fail_and_recover_jobs() {
    let (_directory, url) = sqlite("queue-worker");
    let app = application(url).await;
    sizes_contract(&app).await;
    worker_contract(&app).await;
}

#[cfg(feature = "database-postgres")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
async fn postgres_queues_push_and_work_jobs() {
    let url = std::env::var("LARAVEL_TEST_POSTGRES_URL").unwrap();
    database_contracts(url).await;
}

#[cfg(feature = "database-mysql")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable database"]
async fn mysql_queues_push_and_work_jobs() {
    let url = std::env::var("LARAVEL_TEST_MYSQL_URL").unwrap();
    database_contracts(url).await;
}

#[cfg(any(feature = "database-postgres", feature = "database-mysql"))]
async fn database_contracts(url: String) {
    let app = crate::queue::database::application(url.clone()).await;
    crate::queue::database::push_contract(&app).await;
    crate::queue::database::transaction_contract(&app).await;
    crate::queue::database::bulk_contract(&app).await;
    let app = application(url.clone()).await;
    sizes_contract(&app).await;
    worker_contract(&app).await;
    #[cfg(feature = "database-sqlite")]
    crate::queue_batches::concurrent_completion_contract(&crate::queue_batches::application(url, "database").await)
        .await;
}

#[cfg(feature = "database-sqlite")]
mod sqlite {
    use super::*;

    #[tokio::test]
    async fn workers_take_queues_in_priority_order_and_stop_after_max_jobs() {
        let (_directory, url) = sqlite("queue-priority");
        let app = application(url).await;
        for (name, queue) in [
            ("low 1", "low"),
            ("high 1", "high"),
            ("low 2", "low"),
            ("high 2", "high"),
        ] {
            app.scope(async || Note(name.into()).dispatch().on_queue(queue).await)
                .await
                .unwrap();
        }

        let result = work(&app, "--queue=high,low --max-jobs=3").await;
        result.assert_successful().assert_error_output_contains(
            "Processing jobs from `database:high`, `database:low`. Press Ctrl+C to stop.",
        );
        assert_eq!(records(&app).await, ["high 1", "high 2", "low 1"]);
        assert_eq!(
            result
                .error_output()
                .matches("integration::queue_worker::Note  ")
                .count(),
            3
        );
        assert_eq!(rows(&app).await, [row("low", 0, 0)]);
    }

    #[tokio::test]
    async fn a_job_running_past_its_timeout_fails() {
        let (_directory, url) = sqlite("queue-timeout");
        let app = application(url).await;
        dispatch(&app, Slow).await;

        work(&app, "")
            .await
            .assert_successful()
            .assert_error_output_contains(" failed  ");
        let failures = failed(&app).await;
        assert_eq!(failures.len(), 1);
        assert_eq!(failures[0].error, "the job ran longer than its timeout of 100ms");
    }

    /// An attempt that will retry logs a warning with the job and its error, and only the last
    /// failure is reported, with the context values the job added.
    #[tokio::test]
    async fn a_job_warns_on_each_retry_and_reports_only_its_last_failure() {
        let (_directory, url) = sqlite("queue-reported-context");
        let app = application(url).await;
        dispatch(&app, Transcode).await;

        let (lines, _guard) = crate::logging::Lines::capture();
        work(&app, "").await.assert_successful();
        assert_eq!(
            reported(&app).await,
            ["the codec is missing with step Some(\"transcoding\")"]
        );
        let retries: Vec<_> = lines
            .json()
            .into_iter()
            .filter(|line| line["target"] == "laravel::queue" && line["level"] == "WARN")
            .map(|line| {
                (
                    line["fields"]["message"].clone(),
                    line["fields"]["job"].clone(),
                    line["fields"]["attempt"].clone(),
                    line["fields"]["retry_in_ms"].clone(),
                )
            })
            .collect();
        assert_eq!(
            retries,
            [(
                json!("The job failed and will be retried: the codec is missing"),
                json!("integration::queue_worker::Transcode"),
                json!(1),
                json!(0),
            )]
        );
    }

    #[tokio::test]
    async fn job_failures_remove_terminal_escapes_from_the_error() {
        let (_directory, url) = sqlite("queue-escapes");
        let app = application(url).await;
        dispatch(&app, Reject).await;

        let result = work(&app, "").await;
        let output = result.error_output();
        let (before, after) = output.split_once(" failed  ").expect(output);
        let (_duration, error) = after.split_once('\n').expect(output);
        assert_eq!(
            before,
            "Processing jobs from `database:default`. Press Ctrl+C to stop.\nintegration::queue_worker::Reject"
        );
        assert_eq!(error, "payload  rejected\n");
    }

    #[tokio::test]
    async fn concurrent_workers_run_jobs_at_the_same_time() {
        let (_directory, url) = sqlite("queue-concurrency");
        let app = application(url).await;
        dispatch(&app, Meet(1)).await;
        dispatch(&app, Meet(2)).await;

        work(&app, "--concurrency=2").await.assert_successful();
        let mut met = records(&app).await;
        met.sort();
        assert_eq!(met, ["met 1", "met 2"]);
        assert!(failed(&app).await.is_empty());
    }

    #[tokio::test]
    async fn a_single_worker_runs_one_job_at_a_time() {
        let (_directory, url) = sqlite("queue-sequential");
        let app = application(url).await;
        dispatch(&app, Meet(1)).await;
        dispatch(&app, Meet(2)).await;

        work(&app, "").await.assert_successful();
        assert!(records(&app).await.is_empty(), "neither job met the other");
        assert_eq!(failed(&app).await.len(), 2);
    }

    #[tokio::test]
    async fn releases_use_tries_unless_the_job_retries_for_a_while() {
        let (_directory, url) = sqlite("queue-releases");
        let app = application(url).await;
        dispatch(&app, Poll).await;

        work(&app, "--queue=polls")
            .await
            .assert_error_output_contains(" released  ");
        assert_eq!(rows(&app).await, [row("polls", 1, 30)], "the job keeps its row");
        app.travel(30.seconds());
        work(&app, "--queue=polls")
            .await
            .assert_error_output_contains(" failed  ");
        assert_eq!(
            records(&app).await,
            ["poll ran as attempt 1"],
            "its one try was the release"
        );
        let failures = failed(&app).await;
        assert_eq!(failures.len(), 1);
        assert!(
            failures[0].error.contains("attempted more than its 1 `tries` allow"),
            "{}",
            failures[0].error
        );

        dispatch(&app, PollForAnHour).await;
        statement(&app, "UPDATE jobs SET attempts = 500").await;
        work(&app, "--queue=polls")
            .await
            .assert_error_output_contains(" released  ");
        app.travel(2.hours());
        work(&app, "--queue=polls")
            .await
            .assert_error_output_contains(" failed  ");
        let failures = failed(&app).await;
        assert_eq!(failures.len(), 2);
        assert!(
            failures[1].error.contains("has run past its `retry_for`"),
            "{}",
            failures[1].error
        );
    }

    /// A failure whose retry would come back past `retry_for` fails now, so the failed job keeps
    /// the attempt's error instead of one saying the window has passed.
    #[tokio::test]
    async fn a_job_that_would_retry_past_its_retry_for_fails_with_its_error() {
        let (_directory, url) = sqlite("queue-retry-for-cause");
        let app = application(url).await;
        dispatch(&app, ChargeCard).await;

        work(&app, "").await.assert_error_output_contains(" retrying  ");
        app.travel(45.seconds());
        work(&app, "").await.assert_error_output_contains(" failed  ");
        let failures = failed(&app).await;
        assert_eq!(failures.len(), 1);
        let error = "`integration::queue_worker::ChargeCard` has run out of its `retry_for`, so it won't be retried: \
                     the payment gateway is down";
        assert_eq!(failures[0].error, error);
        assert_eq!(reported(&app).await, [format!("{error} with step None")]);
    }

    #[tokio::test]
    async fn jobs_over_a_rate_limit_are_released_until_the_limit_allows_them() {
        let (_directory, url) = sqlite("queue-rate-limited");
        let app = application(url).await;
        app.scope(async || rate_limit::hit("newsletter", Limit::per_minute(1)).await)
            .await
            .unwrap();
        dispatch(&app, SendNewsletter).await;

        work(&app, "--queue=newsletters")
            .await
            .assert_error_output_contains(" released  ");
        assert_eq!(rows(&app).await, [row("newsletters", 1, 60)]);
        assert!(reported(&app).await.is_empty(), "a release isn't an error");

        app.travel(1.minutes());
        work(&app, "--queue=newsletters").await.assert_successful();
        assert_eq!(records(&app).await, ["newsletter sent"]);
        assert!(rows(&app).await.is_empty());
        assert!(failed(&app).await.is_empty());
    }

    #[tokio::test]
    async fn jobs_that_would_wait_past_their_retry_for_fail_over_the_rate_limit() {
        let (_directory, url) = sqlite("queue-rate-limited-expiring");
        let app = application(url).await;
        app.scope(async || rate_limit::hit("newsletter", Limit::per_minute(1)).await)
            .await
            .unwrap();
        dispatch(&app, SendNewsletterSoon).await;

        work(&app, "--queue=newsletters")
            .await
            .assert_error_output_contains(" failed  ");
        assert!(rows(&app).await.is_empty());
        let failures = failed(&app).await;
        assert_eq!(failures.len(), 1);
        assert!(failures[0].error.contains("Too Many Attempts"), "{}", failures[0].error);
    }

    #[tokio::test]
    async fn quiet_workers_print_no_job_lines_even_for_failures() {
        use crate::queue_middleware::{Decision, Guarded};

        let (_directory, url) = sqlite("queue-quiet");
        let app = application(url).await;
        for decision in [Decision::Run, Decision::Error, Decision::Fail] {
            dispatch(&app, Guarded::new(decision)).await;
        }

        work(&app, "-q").await.assert_successful().assert_no_output();
        assert_eq!(rows(&app).await, [row("default", 1, 10)], "the error still retries");
        assert_eq!(failed(&app).await.len(), 1, "the failure is still kept");
    }

    #[tokio::test]
    async fn the_worker_runs_jobs_through_their_middleware() {
        use crate::queue_middleware::{Decision, Guarded, WRAPPED};

        let (_directory, url) = sqlite("queue-middleware");
        let app = application(url).await;
        for decision in [
            Decision::Run,
            Decision::Skip,
            Decision::Release,
            Decision::Error,
            Decision::Fail,
        ] {
            dispatch(&app, Guarded::new(decision)).await;
        }

        let result = work(&app, "").await;
        result.assert_successful();
        assert_eq!(
            crate::support::outcomes(result.error_output()),
            ["done", "done", "released", "retrying", "failed"],
            "{}",
            result.error_output()
        );
        assert_eq!(
            rows(&app).await,
            [row("default", 1, 30), row("default", 1, 10)],
            "the release waits its delay, and the error its backoff"
        );
        let failures = failed(&app).await;
        assert_eq!(failures.len(), 1);
        assert_eq!(failures[0].error, "the middleware refused");

        let skipped = ["outer before", "outer after"];
        assert_eq!(
            records(&app).await,
            [
                &WRAPPED[..],
                &skipped,
                &skipped,
                &["outer before", "outer after: the middleware refused"],
                &skipped,
                &["failed hook: the middleware refused"],
            ]
            .concat()
        );
    }

    #[tokio::test]
    async fn max_errors_fails_a_job_after_its_errors_not_its_releases() {
        let (_directory, url) = sqlite("queue-max-errors");
        let app = application(url).await;
        let id = dispatch(&app, Unsteady(1)).await;

        work(&app, "").await.assert_error_output_contains(" released  ");
        app.travel(30.seconds());
        work(&app, "")
            .await
            .assert_error_output_contains(" retrying  ")
            .assert_error_output_contains(" failed  ");
        assert_eq!(
            records(&app).await,
            [
                "unsteady 1 ran as attempt 1",
                "unsteady 1 ran as attempt 2",
                "unsteady 1 ran as attempt 3",
            ]
        );
        let failures = failed(&app).await;
        assert_eq!(
            (failures.len(), failures[0].job_id.as_str()),
            (1, id.to_string().as_str())
        );
        assert_eq!(failures[0].error, "unsteady 1 broke");

        app.command(&format!("queue:retry {id}")).await.assert_successful();
        work(&app, "").await.assert_successful();
        assert_eq!(
            rows(&app).await,
            [row("default", 1, 60)],
            "its first run released it again"
        );

        app.scope(async || {
            laravel::cache::put(&format!("laravel:job-running:{id}"), true, 1.hours()).await?;
            laravel::cache::put(&format!("laravel:job-errors:{id}"), 1, 1.hours()).await
        })
        .await
        .unwrap();
        app.travel(30.seconds());
        work(&app, "").await.assert_error_output_contains(" failed  ");
        assert_eq!(records(&app).await.len(), 4, "the job didn't run again");
        let failures = failed(&app).await;
        assert!(
            failures[0].error.contains("stopped its worker"),
            "{}",
            failures[0].error
        );
    }

    #[tokio::test]
    async fn unreadable_jobs_fail_for_good() {
        let (_directory, url) = sqlite("queue-unreadable");
        let app = application(url).await;
        let id = "0199f3c2-0000-7000-8000-000000000000";
        statement(
            &app,
            &format!(
                "INSERT INTO jobs (queue, payload, attempts, available_at, created_at) VALUES \
                 ('default', 'not json', 0, {epoch}, {epoch}), \
                 ('default', '{{\"version\":1,\"id\":\"{id}\",\"job\":\"removed.job\",\"data\":null,\"dispatched_at\":0}}', 0, {epoch}, {epoch})",
                epoch = sql_at(0)
            ),
        )
        .await;

        let result = work(&app, "").await;
        result
            .assert_successful()
            .assert_error_output_contains("removed.job failed  ")
            .assert_error_output_contains("an unreadable job failed  ");
        assert!(rows(&app).await.is_empty());
        let failures = failed(&app).await;
        assert_eq!(failures.len(), 2);
        assert!(failures[0].error.contains("couldn't be read"), "{}", failures[0].error);
        assert_eq!(failures[1].job_id, id);
        assert!(
            failures[1].error.contains("no job named `removed.job`"),
            "{}",
            failures[1].error
        );

        app.command("queue:retry all")
            .await
            .assert_exit_code(1)
            .assert_error_output_contains(&format!("failed job `{}` couldn't be retried", failures[0].job_id))
            .assert_error_output_contains(&format!("Failed job `{id}` retried."));
        assert_eq!(rows(&app).await.len(), 1);
        assert_eq!(failed(&app).await.len(), 1);
    }

    #[tokio::test]
    async fn failed_jobs_can_be_listed_retried_forgotten_and_flushed() {
        let (_directory, url) = sqlite("queue-failed");
        let app = application(url).await;
        app.command("queue:failed")
            .await
            .assert_successful()
            .assert_error_output_contains("No failed jobs found.");

        let ids = [
            dispatch(&app, Flaky { id: 1, failures: 9 }).await,
            dispatch(&app, Flaky { id: 2, failures: 9 }).await,
            dispatch(&app, Flaky { id: 3, failures: 9 }).await,
        ];
        statement(&app, "UPDATE jobs SET attempts = 2").await;
        work(&app, "").await.assert_successful();
        statement(
            &app,
            &format!("UPDATE failed_jobs SET failed_at = {}", sql_at(NOW - 7200)),
        )
        .await;
        statement(
            &app,
            &format!(
                "UPDATE failed_jobs SET failed_at = {} WHERE job_id = '{}'",
                sql_at(NOW),
                ids[2]
            ),
        )
        .await;
        assert_eq!(failed(&app).await.len(), 3);

        app.command(&format!("queue:forget {}", ids[0]))
            .await
            .assert_successful()
            .assert_error_output_contains(format!("Failed job `{}` deleted.", ids[0]).as_str());
        app.command(&format!("queue:forget {}", ids[0]))
            .await
            .assert_exit_code(1)
            .assert_error_output_contains("no failed job has the ID");
        app.command("queue:flush --hours=1")
            .await
            .assert_successful()
            .assert_error_output_contains("1 failed job deleted.");
        assert_eq!(failed(&app).await[0].job_id, ids[2].to_string());

        app.command("queue:retry nonsense all")
            .await
            .assert_successful()
            .assert_error_output_contains(format!("Failed job `{}` retried.", ids[2]).as_str());
        assert!(failed(&app).await.is_empty());
        assert_eq!(rows(&app).await.len(), 1);
        app.command("queue:retry nonsense")
            .await
            .assert_exit_code(1)
            .assert_error_output_contains("no failed job has the ID `nonsense`");

        app.command("queue:clear")
            .await
            .assert_successful()
            .assert_error_output_contains("1 job cleared from `database:default`.");
        assert!(rows(&app).await.is_empty());
        app.command("queue:flush").await.assert_successful();
    }

    #[tokio::test]
    async fn without_a_failed_jobs_table_failures_are_discarded() {
        let (_directory, url) = sqlite("queue-discard");
        drop(application(url.clone()).await);
        let app = Application::configure()
            .replace_env(Env::default())
            .with_config(move |config, _| {
                config.queue.failed = laravel::config::queue::FailedJobs::Discard;
                config.database.default = "primary".into();
                config
                    .database
                    .connections
                    .insert("primary".into(), ConnectionConfig::new(url));
            })
            .with_services(|services| {
                services.instance(Records::default());
            })
            .create();
        dispatch(&app, Flaky { id: 1, failures: 9 }).await;
        statement(&app, "UPDATE jobs SET attempts = 2").await;

        work(&app, "")
            .await
            .assert_successful()
            .assert_error_output_contains(" failed  ");
        assert!(rows(&app).await.is_empty());
        app.command("queue:failed")
            .await
            .assert_successful()
            .assert_error_output_contains("Failed jobs aren't kept");
        app.command("queue:forget 1")
            .await
            .assert_exit_code(1)
            .assert_error_output_contains("failed jobs aren't kept; `config.queue.failed` is `FailedJobs::Discard`");
    }

    #[tokio::test]
    async fn only_database_connections_can_be_worked() {
        let (_directory, url) = sqlite("queue-sync");
        let app = application(url).await;

        app.command("queue:work sync --stop-when-empty")
            .await
            .assert_exit_code(1)
            .assert_error_output_contains(
                "queue connection `sync` uses the `sync` driver, which keeps no jobs to work",
            );
    }

    #[tokio::test]
    async fn a_missing_table_stops_a_worker_that_stops_when_empty() {
        let (_directory, url) = sqlite("queue-missing");
        let app = application(url).await;
        statement(&app, "DROP TABLE jobs").await;

        work(&app, "").await.assert_exit_code(1);
    }

    #[tokio::test]
    async fn workers_skip_paused_queues_until_they_are_resumed() {
        let (_directory, url) = sqlite("queue-pause");
        let app = application(url).await;
        for (name, queue) in [("high", "high"), ("low", "low")] {
            app.scope(async || Note(name.into()).dispatch().on_queue(queue).await)
                .await
                .unwrap();
        }

        app.command("queue:pause database:high")
            .await
            .assert_successful()
            .assert_error_output_contains("Queue `database:high` paused.")
            .assert_error_output_contains("Cache store `memory` only reaches this process.");
        work(&app, "--queue=high,low")
            .await
            .assert_successful()
            .assert_error_output_contains("Queue `high` paused.");
        assert_eq!(records(&app).await, ["low"]);

        app.command("queue:continue high")
            .await
            .assert_successful()
            .assert_error_output_contains("Queue `database:high` resumed.");
        work(&app, "--queue=high,low").await.assert_successful();
        assert_eq!(records(&app).await, ["low", "high"]);

        dispatch(&app, Note("default".into())).await;
        app.command("queue:pause --all")
            .await
            .assert_successful()
            .assert_error_output_contains("All queues paused.");
        work(&app, "").await.assert_successful();
        assert_eq!(records(&app).await, ["low", "high"]);
        app.command("queue:continue database:default")
            .await
            .assert_successful()
            .assert_error_output_contains("Queue `database:default` isn't paused.")
            .assert_error_output_contains("All queues are still paused. Continue them with `queue:continue --all`.");
        app.command("queue:continue --all")
            .await
            .assert_successful()
            .assert_error_output_contains("All queues resumed.");
        work(&app, "").await.assert_successful();
        assert_eq!(records(&app).await, ["low", "high", "default"]);

        app.command("queue:pause reports:high")
            .await
            .assert_exit_code(1)
            .assert_error_output_contains("queue connection `reports` isn't defined");
        app.command("queue:pause").await.assert_exit_code(2);
    }

    #[tokio::test]
    async fn a_waiting_worker_notices_pauses_and_restarts() {
        let (_directory, url) = sqlite("queue-idle-signals");
        let app = application(url).await;

        let worker = serve(&app, "--sleep=1");
        let signals = async {
            app.command("queue:pause default").await.assert_successful();
            // Wait for any reservation that began before the pause...
            tokio::time::sleep(Duration::from_millis(200)).await;
            dispatch(&app, Note("while paused".into())).await;
            tokio::time::sleep(Duration::from_millis(1500)).await;
            assert!(
                records(&app).await.is_empty(),
                "the worker took a job from a paused queue"
            );

            app.command("queue:continue default").await.assert_successful();
            tokio::time::timeout(Duration::from_secs(10), async {
                while records(&app).await.is_empty() {
                    tokio::time::sleep(Duration::from_millis(50)).await;
                }
            })
            .await
            .expect("the worker should take jobs once the queue is resumed");
            app.command("queue:restart")
                .await
                .assert_successful()
                .assert_error_output_contains("Restart signal sent.");
        };

        let (worker, ()) = tokio::join!(worker, signals);
        worker
            .assert_successful()
            .assert_error_output_contains("Queue `default` paused.")
            .assert_error_output_contains("Queue `default` resumed.")
            .assert_error_output_contains("Restart signal received.");
        assert_eq!(records(&app).await, ["while paused"]);
    }

    #[tokio::test]
    async fn a_restarting_worker_finishes_its_running_job_and_takes_no_more() {
        let (_directory, url) = sqlite("queue-restart");
        let app = application(url).await;
        dispatch(&app, Hold).await;

        let worker = serve(&app, "");
        let restart = async {
            wait_for_reservation(&app, |_| true).await;
            app.command("queue:restart").await.assert_successful();
            dispatch(&app, Note("after the restart".into())).await;
            app.resolve::<Gate>().await.0.send_replace(true);
        };

        let (worker, ()) = tokio::join!(worker, restart);
        worker
            .assert_successful()
            .assert_error_output_contains("Hold  ")
            .assert_error_output_contains("Restart signal received.");
        assert!(!worker.error_output().contains("Note"), "{}", worker.error_output());
        assert_eq!(rows(&app).await, [row("default", 0, 0)]);

        work(&app, "").await.assert_successful();
        assert_eq!(records(&app).await, ["after the restart"]);
    }

    #[tokio::test]
    async fn workers_keep_working_while_the_cache_is_unavailable() {
        let (_directory, url) = sqlite("queue-signals-unavailable");
        let app = application_with(url, |config| config.cache.default = "database".into()).await;
        dispatch(&app, Note("cache unavailable".into())).await;

        app.command("queue:pause default").await.assert_exit_code(1);
        work(&app, "").await.assert_successful();
        assert_eq!(records(&app).await, ["cache unavailable"]);
    }

    #[tokio::test]
    async fn signals_need_a_cache_store_that_keeps_them() {
        let (_directory, url) = sqlite("queue-signals-discard");
        let app = application_with(url, |config| config.cache.default = "discard".into()).await;

        for command in ["queue:restart", "queue:pause default", "queue:continue default"] {
            app.command(command)
                .await
                .assert_exit_code(1)
                .assert_error_output_contains("the default cache store `discard` keeps nothing");
        }
    }
}

async fn serve(app: &Application, options: &str) -> TestCommandResult {
    tokio::time::timeout(Duration::from_secs(30), app.command(&format!("queue:work {options}")))
        .await
        .expect("the worker should restart")
}