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
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use laravel::Application;
use laravel::config::Env;
use laravel::config::database::ConnectionConfig as DatabaseConnection;
use laravel::container::Inject;
use laravel::db::{self, Driver};
use laravel::queue::Queueable;
use laravel::queue::{self, Attempt, Batch, BatchId, Callback, Job, callback, job};
use laravel::testing::{MakesConsoleRequests, RunsJobs, TestCommandResult};
use laravel::time::ToSpan;

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

#[derive(Debug, Queueable)]
struct Item {
    name: String,
    then: Option<String>,
}

fn item(name: &str) -> Item {
    Item {
        name: name.into(),
        then: None,
    }
}

fn item_then(name: &str, then: &str) -> Item {
    Item {
        name: name.into(),
        then: Some(then.into()),
    }
}

#[derive(Default)]
struct Repaired(AtomicBool);

struct Gate(tokio::sync::watch::Sender<bool>);

impl Default for Gate {
    fn default() -> Self {
        Self(tokio::sync::watch::channel(false).0)
    }
}

#[job]
impl Item {
    async fn handle(
        self,
        records: Inject<Records>,
        repaired: Inject<Repaired>,
        attempt: &Attempt,
    ) -> laravel::Result<()> {
        records.push(self.name.clone());
        let then = self.then.as_deref().unwrap_or_default();
        let then = match then.strip_prefix("fail") {
            Some(_) if !repaired.0.load(Ordering::SeqCst) => {
                return Err(laravel::abort_with(500, format!("{} broke", self.name)));
            }
            Some(rest) => rest.trim_start_matches(','),
            None => then,
        };
        match then {
            "cancel" => attempt.cancel_batch(),
            "tenant" => records.push(format!("tenant {:?}", laravel::context::get::<String>("tenant"))),
            then => {
                if let Some(names) = then.strip_prefix("add:") {
                    attempt.add_to_batch(names.split(',').map(item));
                }
                if let Some(names) = then.strip_prefix("append:") {
                    attempt.append_to_chain(names.split(',').map(item));
                }
            }
        }

        Ok(())
    }

    async fn failed(self, records: Inject<Records>) {
        records.push(format!("failed {}", self.name));
    }
}

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

#[job(tries = 2)]
impl Hold {
    async fn handle(self, records: Inject<Records>, gate: Inject<Gate>, attempt: &Attempt) {
        records.push(self.0);
        if attempt.number() == 1 {
            let mut open = gate.0.subscribe();
            let _ = tokio::time::timeout(Duration::from_secs(20), open.wait_for(|open| *open)).await;
        }
    }
}

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

#[callback]
impl Note {
    async fn then(self, batch: &Batch, records: Inject<Records>, notes: Inject<Notes>) {
        records.push(self.0);
        notes.batches.lock().unwrap().push(batch.id());
    }

    async fn catch(self, error: &laravel::Error, records: Inject<Records>, notes: Inject<Notes>) {
        records.push(self.0);
        notes.errors.lock().unwrap().push(error.to_string());
    }

    async fn finally(self, batch: &Batch, records: Inject<Records>, notes: Inject<Notes>) {
        records.push(self.0);
        notes.batches.lock().unwrap().push(batch.id());
    }
}

#[derive(Default)]
struct Notes {
    batches: std::sync::Mutex<Vec<BatchId>>,
    errors: std::sync::Mutex<Vec<String>>,
}

pub(crate) fn create_batch_tables(driver: Driver) -> [&'static str; 2] {
    match driver {
        Driver::MySql | Driver::MariaDb => [
            "CREATE TABLE job_batches (
                id VARCHAR(36) PRIMARY KEY,
                name VARCHAR(255) NULL,
                total_jobs INT NOT NULL,
                pending_jobs INT NOT NULL,
                failed_jobs INT NOT NULL,
                options LONGTEXT NOT NULL,
                created_at DATETIME(6) NOT NULL,
                cancelled_at DATETIME(6) NULL,
                finished_at DATETIME(6) NULL
            )",
            "CREATE TABLE job_batch_jobs (
                batch_id VARCHAR(36) NOT NULL,
                job_id VARCHAR(36) NOT NULL,
                status VARCHAR(16) NOT NULL,
                PRIMARY KEY (batch_id, job_id)
            )",
        ],
        _ => [
            "CREATE TABLE job_batches (
                id VARCHAR(36) PRIMARY KEY,
                name VARCHAR(255),
                total_jobs INTEGER NOT NULL,
                pending_jobs INTEGER NOT NULL,
                failed_jobs INTEGER NOT NULL,
                options TEXT NOT NULL,
                created_at TIMESTAMP(6) NOT NULL,
                cancelled_at TIMESTAMP(6),
                finished_at TIMESTAMP(6)
            )",
            "CREATE TABLE job_batch_jobs (
                batch_id VARCHAR(36) NOT NULL,
                job_id VARCHAR(36) NOT NULL,
                status VARCHAR(16) NOT NULL,
                PRIMARY KEY (batch_id, job_id)
            )",
        ],
    }
}

pub(crate) async fn application(url: String, default: &'static str) -> Application {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_config(move |config, _| {
            config.queue.default = default.into();
            config.database.default = "primary".into();
            config
                .database
                .connections
                .insert("primary".into(), DatabaseConnection::new(url));
        })
        .with_services(|services| {
            services.instance(Records::default());
            services.instance(Repaired::default());
            services.instance(Gate::default());
            services.instance(Notes::default());
        })
        .create();
    app.scope(async || {
        let connection = db::default_connection()?;
        for table in ["job_batch_jobs", "job_batches", "failed_jobs", "jobs"] {
            connection
                .query(db::sqlx::AssertSqlSafe(format!("DROP TABLE IF EXISTS {table}")))
                .statement()
                .await?;
        }
        let driver = connection.driver();
        for sql in [create_table(driver), create_failed_table(driver)]
            .into_iter()
            .chain(create_batch_tables(driver))
        {
            connection.query(sql).statement().await?;
        }
        Ok::<_, laravel::Error>(())
    })
    .await
    .unwrap();

    app
}

async fn sqlite(directory: &crate::support::TempDir, default: &'static str) -> Application {
    let url = format!("sqlite://{}?mode=rwc", directory.join("batches.sqlite").display());

    application(url, default).await
}

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

async fn clear(app: &Application) {
    app.resolve::<Records>().await.clear();
}

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

async fn dispatch(app: &Application, batch: queue::PendingBatch) -> BatchId {
    app.scope(async || batch.await).await.unwrap()
}

async fn find(app: &Application, id: BatchId) -> queue::Batch {
    app.scope(async || queue::find_batch(id).await)
        .await
        .unwrap()
        .expect("the batch is stored")
}

async fn counts(app: &Application, id: BatchId) -> (i64, i64, i64) {
    app.scope(async || {
        let row = db::default_connection()?
            .query(db::sqlx::AssertSqlSafe(format!(
                "SELECT total_jobs, pending_jobs, failed_jobs FROM job_batches WHERE id = '{id}'"
            )))
            .select_one()
            .await?
            .unwrap();
        Ok::<_, laravel::Error>((row.try_get(0_usize)?, row.try_get(1_usize)?, row.try_get(2_usize)?))
    })
    .await
    .unwrap()
}

#[tokio::test]
async fn sync_batches_run_their_jobs_then_call_their_callbacks() {
    let directory = crate::support::TempDir::new("queue-batches-sync");
    let app = sqlite(&directory, "sync").await;

    let id = dispatch(
        &app,
        queue::batch([item("a"), item("b")])
            .name("letters")
            .then(Note("then".into()))
            .catch(Note("catch".into()))
            .finally(Note("finally".into())),
    )
    .await;
    assert_eq!(records(&app).await, ["a", "b", "then", "finally"]);
    let batch = find(&app, id).await;
    assert_eq!(batch.name(), Some("letters"));
    assert_eq!(
        (
            batch.total_jobs(),
            batch.pending_jobs(),
            batch.processed_jobs(),
            batch.progress()
        ),
        (2, 0, 2, 100)
    );
    assert!(batch.is_finished() && !batch.is_cancelled());
    assert_eq!(
        *app.resolve::<Notes>().await.batches.lock().unwrap(),
        [id, id],
        "callbacks receive their batch"
    );

    clear(&app).await;
    let id = dispatch(
        &app,
        queue::batch([item("a"), item_then("b", "fail"), item("c")])
            .then(Note("then".into()))
            .catch(Note("catch".into()))
            .finally(Note("finally".into())),
    )
    .await;
    assert_eq!(records(&app).await, ["a", "b", "catch", "failed b", "finally"]);
    assert_eq!(*app.resolve::<Notes>().await.errors.lock().unwrap(), ["b broke"]);
    let batch = find(&app, id).await;
    assert_eq!(
        (batch.total_jobs(), batch.pending_jobs(), batch.failed_jobs()),
        (3, 1, 1)
    );
    assert!(batch.is_cancelled() && batch.is_finished() && batch.has_failures());

    clear(&app).await;
    let id = dispatch(
        &app,
        queue::batch([item("a"), item_then("b", "fail"), item("c")])
            .allow_failures()
            .then(Note("then".into()))
            .catch(Note("catch".into()))
            .finally(Note("finally".into())),
    )
    .await;
    assert_eq!(records(&app).await, ["a", "b", "catch", "failed b", "c", "finally"]);
    assert!(!find(&app, id).await.is_cancelled());

    clear(&app).await;
    let id = dispatch(
        &app,
        queue::batch(Vec::<Item>::new())
            .then(Note("then".into()))
            .finally(Note("finally".into())),
    )
    .await;
    assert_eq!(records(&app).await, ["then", "finally"]);
    assert!(find(&app, id).await.is_finished());
}

#[tokio::test]
async fn chains_in_batches_and_batches_in_chains_run_in_order_and_count_as_their_jobs() {
    let directory = crate::support::TempDir::new("queue-batches-nested");
    let app = sqlite(&directory, "database").await;

    let inner = queue::batch([item("bb1"), item("bb2")]).then(Note("inner then".into()));
    let outer = queue::batch((item("b1"), queue::chain(item("bc1")).then(inner).then(item("bc2"))))
        .then(Note("outer then".into()));
    app.scope(async || queue::chain(item("c1")).then(outer).then(item("c2")).await)
        .await
        .unwrap();
    work(&app, "").await.assert_successful();

    assert_eq!(
        records(&app).await,
        ["c1", "b1", "bc1", "bb1", "bb2", "inner then", "bc2", "outer then", "c2"],
        "each batch waits for its chains, and each chain waits for its batches",
    );
    let totals: Vec<(i64, i64, i64)> = app
        .scope(async || {
            db::default_connection()?
                .query("SELECT total_jobs, pending_jobs, failed_jobs FROM job_batches ORDER BY total_jobs DESC")
                .select()
                .await?
                .iter()
                .map(|row| Ok((row.try_get(0_usize)?, row.try_get(1_usize)?, row.try_get(2_usize)?)))
                .collect::<laravel::Result<_>>()
        })
        .await
        .unwrap();
    assert_eq!(
        totals,
        [(4, 0, 0), (2, 0, 0)],
        "the inner batch counts as one job of the outer one"
    );
}

#[tokio::test]
async fn a_chain_can_start_with_a_batch_and_waits_for_it_to_finish() {
    let directory = crate::support::TempDir::new("queue-batches-chain-start");
    let app = sqlite(&directory, "database").await;

    let start = app
        .scope(async || {
            queue::chain(queue::batch(["first", "second"].into_iter().map(item)))
                .then(item("after"))
                .await
        })
        .await
        .unwrap();
    let queue::ChainDispatched::Batch(id) = start else {
        panic!("the chain should return its first batch's ID");
    };

    assert!(records(&app).await.is_empty());
    assert_eq!(find(&app, id).await.total_jobs(), 2);
    work(&app, "--max-jobs=1").await.assert_successful();
    assert_eq!(records(&app).await, ["first"]);
    work(&app, "").await.assert_successful();
    assert_eq!(records(&app).await, ["first", "second", "after"]);
    assert!(find(&app, id).await.is_finished());
}

#[tokio::test]
async fn an_empty_leading_batch_continues_but_a_delayed_leading_batch_is_rejected() {
    let directory = crate::support::TempDir::new("queue-batches-chain-empty");
    let app = sqlite(&directory, "sync").await;

    app.scope(async || {
        queue::chain(queue::batch(std::iter::empty::<Item>()))
            .then(item("after empty"))
            .await
    })
    .await
    .unwrap();
    assert_eq!(records(&app).await, ["after empty"]);

    app.scope(async || {
        let fake = queue::fake();
        let error = queue::chain(queue::batch([item("never")]))
            .delay(0.seconds())
            .await
            .unwrap_err();
        assert_eq!(error.to_string(), "a chain starting with a batch can't have a delay");
        fake.assert_nothing_pushed().assert_nothing_batched();
    })
    .await;
}

#[tokio::test]
async fn a_failing_batch_in_a_chain_stops_the_chain_unless_it_allows_failures() {
    let directory = crate::support::TempDir::new("queue-batches-chain-failure");
    let app = sqlite(&directory, "database").await;

    let chain = |batch: queue::PendingBatch| {
        queue::chain(item("c1"))
            .then(batch.catch(Note("batch catch".into())))
            .then(item("c2"))
            .catch(Note("chain catch".into()))
    };
    let failing = || queue::batch([item("b1"), item_then("b2", "fail"), item("b3")]);

    app.scope(async || chain(failing()).await).await.unwrap();
    work(&app, "").await.assert_successful();
    assert_eq!(
        records(&app).await,
        ["c1", "b1", "b2", "batch catch", "chain catch", "failed b2"],
        "the failing worker calls both catch callbacks, and the cancelled batch skips b3 and stops the chain",
    );

    clear(&app).await;
    app.scope(async || chain(failing().allow_failures()).await)
        .await
        .unwrap();
    work(&app, "").await.assert_successful();
    assert_eq!(
        records(&app).await,
        ["c1", "b1", "b2", "batch catch", "failed b2", "b3", "c2"],
    );

    clear(&app).await;
    app.scope(async || {
        queue::chain(failing().catch(Note("batch catch".into())))
            .then(item("never"))
            .catch(Note("chain catch".into()))
            .await
    })
    .await
    .unwrap();
    work(&app, "").await.assert_successful();
    assert_eq!(
        records(&app).await,
        ["b1", "b2", "batch catch", "chain catch", "failed b2"]
    );

    clear(&app).await;
    app.scope(async || queue::chain(failing().allow_failures()).then(item("after")).await)
        .await
        .unwrap();
    work(&app, "").await.assert_successful();
    assert_eq!(records(&app).await, ["b1", "b2", "failed b2", "b3", "after"]);
}

#[tokio::test]
async fn a_batch_that_cant_dispatch_a_job_is_cancelled_and_stops_its_chain_once() {
    let directory = crate::support::TempDir::new("queue-batches-undispatchable");
    let app = sqlite(&directory, "database").await;

    let error = app
        .scope(async || {
            queue::batch((item("a"), queue::chain(item("b")).on_connection("missing")))
                .finally(Note("finally".into()))
                .await
        })
        .await
        .unwrap_err();
    assert!(error.to_string().contains("`missing`"), "{error}");
    work(&app, "").await.assert_successful();
    assert_eq!(
        records(&app).await,
        ["finally"],
        "the batch is cancelled, and its jobs are skipped"
    );

    clear(&app).await;
    app.scope(async || {
        queue::chain(item("x"))
            .then(queue::batch([item("a")]).on_connection("missing"))
            .catch(Note("catch".into()))
            .await
    })
    .await
    .unwrap();
    work(&app, "").await.assert_successful();
    assert_eq!(
        records(&app).await,
        ["x", "catch"],
        "the cancelled batch stops the chain, and x succeeded"
    );
}

#[tokio::test]
async fn a_chain_that_cant_go_on_after_its_batch_fails_and_finishes_its_own_batch() {
    let directory = crate::support::TempDir::new("queue-batches-stuck-continuation");
    let app = sqlite(&directory, "database").await;

    let id = dispatch(
        &app,
        queue::batch(
            queue::chain(queue::batch([item("inner")]))
                .then(item("never"))
                .on_connection("missing")
                .catch(Note("catch".into())),
        )
        .finally(Note("finally".into())),
    )
    .await;
    work(&app, "").await.assert_successful();

    assert_eq!(records(&app).await, ["inner", "catch", "finally"]);
    let (_, pending, failed) = counts(&app, id).await;
    assert_eq!((pending, failed), (1, 1), "the chain's steps settle as one failure");
}

#[tokio::test]
async fn jobs_add_to_and_cancel_their_batch_and_a_retry_clears_a_failure() {
    let directory = crate::support::TempDir::new("queue-batches-running");
    let app = sqlite(&directory, "database").await;

    let id = dispatch(
        &app,
        queue::batch([item_then("loader", "add:x,y")]).then(Note("then".into())),
    )
    .await;
    work(&app, "").await.assert_successful();
    assert_eq!(records(&app).await, ["loader", "x", "y", "then"]);
    assert_eq!(counts(&app, id).await, (3, 0, 0));

    clear(&app).await;
    let id = dispatch(
        &app,
        queue::batch([item_then("a", "cancel"), item("b")])
            .then(Note("then".into()))
            .finally(Note("finally".into())),
    )
    .await;
    work(&app, "")
        .await
        .assert_successful()
        .assert_error_output_contains(" deleted  ");
    assert_eq!(
        records(&app).await,
        ["a", "finally"],
        "b is skipped, and `then` never runs"
    );
    assert!(find(&app, id).await.is_cancelled());

    clear(&app).await;
    let id = dispatch(
        &app,
        queue::batch([item("a"), item_then("b", "fail")])
            .allow_failures()
            .then(Note("then".into()))
            .finally(Note("finally".into())),
    )
    .await;
    work(&app, "").await.assert_successful();
    assert_eq!(records(&app).await, ["a", "b", "finally", "failed b"]);
    assert_eq!(counts(&app, id).await, (2, 1, 1));

    clear(&app).await;
    app.resolve::<Repaired>().await.0.store(true, Ordering::SeqCst);
    app.command("queue:retry all").await.assert_successful();
    work(&app, "").await.assert_successful();
    assert_eq!(
        records(&app).await,
        ["b", "then"],
        "the retry succeeds, so every job has"
    );
    assert_eq!(counts(&app, id).await, (2, 0, 0));
}

#[tokio::test]
async fn jobs_a_batch_job_adds_to_its_chain_and_a_retried_chain_count_as_the_batchs_jobs() {
    let directory = crate::support::TempDir::new("queue-batches-chain-grows");
    let app = sqlite(&directory, "database").await;

    let id = dispatch(
        &app,
        queue::batch([item_then("a", "append:b,c")]).then(Note("then".into())),
    )
    .await;
    work(&app, "").await.assert_successful();
    assert_eq!(records(&app).await, ["a", "b", "c", "then"]);
    assert_eq!(counts(&app, id).await, (3, 0, 0));

    clear(&app).await;
    let id = dispatch(
        &app,
        queue::batch([queue::chain(item_then("x", "fail")).then(item("y"))])
            .allow_failures()
            .then(Note("then".into()))
            .finally(Note("finally".into())),
    )
    .await;
    work(&app, "").await.assert_successful();
    assert_eq!(records(&app).await, ["x", "finally", "failed x"]);
    assert_eq!(counts(&app, id).await, (2, 1, 1));

    clear(&app).await;
    app.resolve::<Repaired>().await.0.store(true, Ordering::SeqCst);
    app.command(&format!("queue:retry-batch {id}"))
        .await
        .assert_successful();
    work(&app, "--max-jobs=1").await.assert_successful();
    assert_eq!(records(&app).await, ["x"]);
    assert_eq!(counts(&app, id).await, (2, 1, 0));
    assert!(
        !find(&app, id).await.is_finished(),
        "the retry revived y, so the batch has work left"
    );

    work(&app, "").await.assert_successful();
    assert!(find(&app, id).await.is_finished());
    assert_eq!(
        records(&app).await,
        ["x", "y", "then", "finally"],
        "the retried job's chain runs before `then`, and `finally` runs again as the batch finishes again"
    );
    assert_eq!(counts(&app, id).await, (2, 0, 0));
}

#[tokio::test]
async fn a_retried_job_that_adds_jobs_reopens_its_finished_batch() {
    let directory = crate::support::TempDir::new("queue-batches-retry-adds");
    let app = sqlite(&directory, "database").await;
    let id = dispatch(
        &app,
        queue::batch([item_then("a", "fail,add:b")])
            .allow_failures()
            .then(Note("then".into()))
            .finally(Note("finally".into())),
    )
    .await;
    work(&app, "").await.assert_successful();
    assert_eq!(records(&app).await, ["a", "finally", "failed a"]);
    assert!(find(&app, id).await.is_finished());

    clear(&app).await;
    app.resolve::<Repaired>().await.0.store(true, Ordering::SeqCst);
    app.command(&format!("queue:retry-batch {id}"))
        .await
        .assert_successful();
    work(&app, "--max-jobs=1").await.assert_successful();
    assert_eq!(records(&app).await, ["a"]);
    assert_eq!(counts(&app, id).await, (2, 1, 0));
    assert!(
        !find(&app, id).await.is_finished(),
        "a added b, so the batch has work left"
    );

    work(&app, "").await.assert_successful();
    assert_eq!(records(&app).await, ["a", "b", "then", "finally"]);
    assert!(find(&app, id).await.is_finished());
}

#[tokio::test]
async fn a_job_that_runs_twice_is_counted_once() {
    let directory = crate::support::TempDir::new("queue-batches-twice");
    let app = sqlite(&directory, "database").await;
    let id = dispatch(&app, queue::batch([Hold("twice".into())]).then(Note("then".into()))).await;

    let second = async {
        while !records(&app).await.contains(&"twice".to_owned()) {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        app.travel(2.minutes());
        work(&app, "").await.assert_successful();
        app.resolve::<Gate>().await.0.send_replace(true);
    };
    let (first, ()) = tokio::join!(work(&app, ""), second);
    first.assert_successful();

    assert_eq!(records(&app).await, ["twice", "twice", "then"]);
    assert_eq!(
        counts(&app, id).await,
        (1, 0, 0),
        "the second success of the same job isn't counted"
    );
}

pub(crate) async fn concurrent_completion_contract(app: &Application) {
    let id = dispatch(
        app,
        queue::batch((0..30).map(|n| item(&format!("job {n:02}"))).collect::<Vec<_>>())
            .then(Note("then".into()))
            .finally(Note("finally".into())),
    )
    .await;
    let (first, second) = tokio::join!(work(app, "--concurrency=8"), work(app, "--concurrency=8"));
    first.assert_successful();
    second.assert_successful();

    let records = records(app).await;
    assert_eq!(records.iter().filter(|record| record.starts_with("job")).count(), 30);
    assert_eq!(
        records.iter().filter(|record| *record == "then").count(),
        1,
        "{records:?}"
    );
    assert_eq!(
        records.iter().filter(|record| *record == "finally").count(),
        1,
        "{records:?}"
    );
    assert_eq!(counts(app, id).await, (30, 0, 0));
}

#[tokio::test]
async fn sqlite_batches_finish_once_when_jobs_finish_concurrently() {
    let directory = crate::support::TempDir::new("queue-batches-concurrent");
    concurrent_completion_contract(&sqlite(&directory, "database").await).await;
}

#[tokio::test]
async fn a_batch_dispatched_in_a_transaction_waits_for_the_commit() {
    let directory = crate::support::TempDir::new("queue-batches-transaction");
    let app = sqlite(&directory, "database").await;

    let (during, committed) = app
        .scope(async || {
            let connection = db::default_connection().unwrap();
            let rolled_back = connection
                .transaction(async |_| {
                    queue::batch([item("never")]).await?;
                    Err::<(), _>(laravel::abort_with(500, "rolled back"))
                })
                .await;
            assert!(rolled_back.is_err());
            let mut id = None;
            let during = connection
                .transaction(async |tx| {
                    laravel::context::add("tenant", "acme");
                    id = Some(queue::batch([item_then("a", "tenant")]).await?);
                    laravel::context::add("tenant", "added after the dispatch");
                    tx.query("SELECT COUNT(*) FROM job_batches").scalar::<i64>().await
                })
                .await
                .unwrap();
            (during, id.unwrap())
        })
        .await;

    assert_eq!(during, Some(0));
    work(&app, "").await.assert_successful();
    assert_eq!(records(&app).await, ["a", "tenant Some(\"acme\")"]);
    assert!(find(&app, committed).await.is_finished());
}

#[tokio::test]
async fn a_leading_batch_and_its_continuation_wait_for_commit_and_are_discarded_on_rollback() {
    let directory = crate::support::TempDir::new("queue-batches-leading-transaction");
    let app = sqlite(&directory, "sync").await;

    app.scope(async || {
        let connection = db::default_connection().unwrap();
        let rollback = connection
            .transaction(async |_| {
                queue::chain(queue::batch([item("never")]))
                    .then(item("also never"))
                    .await?;
                Err::<(), _>(laravel::abort_with(500, "rolled back"))
            })
            .await;
        assert!(rollback.is_err());

        connection
            .transaction(async |tx| {
                queue::chain(queue::batch(std::iter::empty::<Item>()).then(Note("then".into())))
                    .then(item("after"))
                    .await?;
                assert_eq!(
                    tx.query("SELECT COUNT(*) FROM job_batches").scalar::<i64>().await?,
                    Some(0)
                );
                assert!(laravel::resolve::<Records>().await?.all().is_empty());
                Ok(())
            })
            .await
            .unwrap();

        let fake = queue::fake();
        connection
            .transaction(async |_| {
                let start = queue::chain(queue::batch([item("faked")]))
                    .then(item("not run"))
                    .await?;
                assert!(matches!(start, queue::ChainDispatched::Batch(_)));
                fake.assert_nothing_batched();
                Ok(())
            })
            .await
            .unwrap();
        fake.assert_batch_count(1).assert_nothing_pushed();
    })
    .await;

    assert_eq!(records(&app).await, ["then", "after"]);
}

fn fake_application() -> Application {
    Application::configure()
        .replace_env(Env::default())
        .with_services(|services| {
            services.instance(Records::default());
            services.instance(Repaired::default());
            services.instance(Notes::default());
        })
        .create()
}

#[tokio::test]
async fn the_fake_records_batches_without_running_them() {
    let app = fake_application();

    app.scope(async || {
        let queue = queue::fake();
        queue.assert_nothing_batched();

        let id = queue::batch((item("a"), queue::chain(item("b")).then(item("c"))))
            .name("letters")
            .on_queue("letters")
            .allow_failures()
            .then(Note("then".into()))
            .await
            .unwrap();
        queue::chain(item("first"))
            .then(queue::batch([item("x"), item("y")]))
            .await
            .unwrap();

        queue.assert_batch_count(1).assert_batched(|batch| {
            batch.id() == id
                && batch.name() == Some("letters")
                && batch.jobs().names() == [Item::NAME, Item::NAME]
                && batch.jobs().get::<Item>(1).is_some_and(|job| job.name == "b")
                && batch.chain(1).get::<Item>(0).is_some_and(|job| job.name == "c")
                && batch.chain(0).is_empty()
                && batch.then().names() == [Note::NAME]
                && batch.allows_failures()
                && batch.queue() == Some("letters")
        });
        queue.assert_pushed_where::<Item>(|job| {
            job.name == "first"
                && job.chain().names() == ["batch"]
                && job.chain().batch(0).is_some_and(|batch| batch.jobs().len() == 2)
        });
        queue.assert_not_pushed_where::<Item>(|job| job.name == "a");

        let batch = queue::find_batch(id).await.unwrap().unwrap();
        assert_eq!((batch.total_jobs(), batch.pending_jobs(), batch.progress()), (3, 3, 0));
        assert_eq!(
            serde_json::to_value(&batch).unwrap()["total_jobs"],
            serde_json::json!(3),
            "a batch serializes for a route to return"
        );

        queue::cancel_batch(id).await.unwrap();
        assert!(
            queue::find_batch(id).await.unwrap().unwrap().is_cancelled(),
            "the fake cancels a batch it recorded"
        );
    })
    .await;
}

#[tokio::test]
async fn test_callbacks_run_against_a_batch_shaped_for_their_point() {
    let app = fake_application();

    app.callback(Note("then".into())).then().await.unwrap();
    app.callback(Note("catch".into()))
        .catch(laravel::abort_with(500, "row 812 is invalid"))
        .await
        .unwrap();
    app.callback(Note("finally".into()))
        .total_jobs(3)
        .failed_jobs(1)
        .cancelled()
        .finally()
        .await
        .unwrap();

    assert_eq!(app.resolve::<Records>().await.all(), ["then", "catch", "finally"]);
    let notes = app.resolve::<Notes>().await;
    assert_eq!(*notes.errors.lock().unwrap(), ["row 812 is invalid"]);
    assert_eq!(notes.batches.lock().unwrap().len(), 2);

    app.callback(Picky).then().await.unwrap();
    let error = app
        .callback(Picky)
        .total_jobs(4)
        .pending_jobs(1)
        .then()
        .await
        .unwrap_err();
    assert_eq!(error.to_string(), "3 of 4 jobs processed, unfinished");
    assert!(app.callback(Picky).cancelled().then().await.is_err());
}

#[derive(Queueable)]
struct Picky;

#[callback]
impl Picky {
    async fn then(self, batch: &Batch) -> laravel::Result<()> {
        assert!(!batch.is_cancelled(), "a cancelled batch never calls then");
        if !batch.is_finished() {
            return Err(laravel::abort_with(
                500,
                format!(
                    "{} of {} jobs processed, unfinished",
                    batch.processed_jobs(),
                    batch.total_jobs()
                ),
            ));
        }
        Ok(())
    }
}

#[tokio::test]
async fn test_attempts_in_a_batch_report_what_the_job_asked_of_it() {
    let app = fake_application();

    let result = app.job(item_then("loader", "add:x,y")).in_batch().await;
    result.assert_succeeded();
    assert_eq!(result.added_to_batch().names(), [Item::NAME, Item::NAME]);
    assert_eq!(result.added_to_batch().get::<Item>(1).unwrap().name, "y");

    app.job(item_then("a", "cancel"))
        .in_batch()
        .await
        .assert_batch_cancelled();

    let outside = app.job(item_then("loader", "add:x")).await;
    outside.assert_failed();
    assert!(
        outside
            .error()
            .unwrap()
            .to_string()
            .contains("isn't one of a batch's jobs")
    );
}

#[tokio::test]
async fn retry_batch_pushes_back_the_failed_jobs_of_batches_that_were_not_cancelled() {
    let directory = crate::support::TempDir::new("queue-batches-retry");
    let app = sqlite(&directory, "database").await;
    let cancelled = dispatch(&app, queue::batch([item_then("x", "fail")])).await;
    let id = dispatch(
        &app,
        queue::batch([item("a"), item_then("b", "fail"), item_then("c", "fail")])
            .allow_failures()
            .then(Note("then".into())),
    )
    .await;
    work(&app, "").await.assert_successful();
    assert_eq!(counts(&app, id).await, (3, 2, 2));

    clear(&app).await;
    app.resolve::<Repaired>().await.0.store(true, Ordering::SeqCst);
    let result = app
        .command(&format!("queue:retry-batch {id} {cancelled} missing"))
        .await;
    result
        .assert_exit_code(1)
        .assert_error_output_contains(&format!(
            "batch `{cancelled}` was cancelled, so its failed jobs can't be retried"
        ))
        .assert_error_output_contains("no batch has the ID `missing`");
    assert_eq!(result.error_output().matches("` retried.").count(), 2);
    work(&app, "").await.assert_successful();
    let mut retried = records(&app).await;
    retried[..2].sort();
    assert_eq!(retried, ["b", "c", "then"]);
    assert_eq!(counts(&app, id).await, (3, 0, 0));

    app.command(&format!("queue:retry-batch {id}"))
        .await
        .assert_successful()
        .assert_error_output_contains(&format!("Batch `{id}` has no failed jobs."));
    let failed: Option<i64> = app
        .scope(async || {
            db::default_connection()?
                .query("SELECT COUNT(*) FROM failed_jobs")
                .scalar()
                .await
        })
        .await
        .unwrap();
    assert_eq!(failed, Some(1), "the cancelled batch's failed job is kept");
}

#[tokio::test]
async fn prune_batches_deletes_old_batches_with_their_jobs() {
    let directory = crate::support::TempDir::new("queue-batches-prune");
    let app = sqlite(&directory, "database").await;
    let now = jiff::Timestamp::now();
    let literal = |hours: u64| {
        format!(
            "'{}'",
            (now - Duration::from_secs(hours * 3600)).strftime("%Y-%m-%dT%H:%M:%S+00:00")
        )
    };
    let (old, recent) = (literal(48), literal(1));
    let mut ids = Vec::new();
    for name in ["old finished", "recent finished", "old unfinished", "old cancelled"] {
        ids.push(dispatch(&app, queue::batch([item(name), item(name)])).await);
    }
    for (id, set) in ids.iter().zip([
        format!("created_at = {old}, finished_at = {old}"),
        format!("created_at = {old}, finished_at = {recent}"),
        format!("created_at = {old}"),
        format!("created_at = {old}, finished_at = {recent}, cancelled_at = {recent}"),
    ]) {
        statement(&app, &format!("UPDATE job_batches SET {set} WHERE id = '{id}'")).await;
    }

    app.command("queue:prune-batches")
        .await
        .assert_successful()
        .assert_error_output_contains("1 finished batch deleted.");
    assert_eq!(
        stored_batches(&app).await,
        [(ids[1], 2), (ids[2], 2), (ids[3], 2)].map(|(id, jobs)| (id.to_string(), jobs))
    );

    let result = app.command("queue:prune-batches --unfinished=24 --cancelled=24").await;
    result.assert_successful();
    assert_eq!(
        result.error_output().lines().collect::<Vec<_>>(),
        [
            "No finished batches found.",
            "1 unfinished batch deleted.",
            "1 cancelled batch deleted."
        ]
    );
    assert_eq!(stored_batches(&app).await, [(ids[1].to_string(), 2)]);
}

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

async fn stored_batches(app: &Application) -> Vec<(String, i64)> {
    app.scope(async || {
        let rows = db::default_connection()?
            .query(
                "SELECT job_batches.id, (SELECT COUNT(*) FROM job_batch_jobs WHERE batch_id = job_batches.id) \
                 FROM job_batches ORDER BY job_batches.id",
            )
            .select()
            .await?;
        let orphans: Option<i64> = db::default_connection()?
            .query("SELECT COUNT(*) FROM job_batch_jobs WHERE batch_id NOT IN (SELECT id FROM job_batches)")
            .scalar()
            .await?;
        assert_eq!(orphans, Some(0), "no job rows outlive their batch");
        rows.iter()
            .map(|row| Ok((row.try_get(0_usize)?, row.try_get(1_usize)?)))
            .collect::<laravel::Result<Vec<_>>>()
    })
    .await
    .unwrap()
}