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
use std::sync::Mutex;

use laravel::Application;
use laravel::config::Env;
use laravel::container::Inject;
use laravel::foundation::StartupError;
use laravel::queue::Queueable;
use laravel::queue::{self, Attempt, job};
use laravel::testing::{MakesHttpRequests, RunsJobs};
use laravel::time::ToSpan;

#[derive(Default)]
pub(crate) struct Records(Mutex<Vec<String>>);

impl Records {
    pub(crate) fn push(&self, value: impl Into<String>) {
        self.0.lock().unwrap().push(value.into());
    }

    pub(crate) fn all(&self) -> Vec<String> {
        self.0.lock().unwrap().clone()
    }

    pub(crate) fn clear(&self) {
        self.0.lock().unwrap().clear();
    }
}

#[derive(Debug, thiserror::Error)]
#[error("the podcast is corrupt")]
struct Corrupt;

#[derive(Queueable)]
struct ProcessPodcast {
    podcast_id: i64,
    outcome: Option<String>,
}

impl ProcessPodcast {
    fn new(podcast_id: i64) -> Self {
        Self {
            podcast_id,
            outcome: None,
        }
    }

    fn then(mut self, outcome: &str) -> Self {
        self.outcome = Some(outcome.to_owned());
        self
    }
}

#[job(queue = "podcasts", tries = 3, backoff = [10.seconds(), 1.minutes()], timeout = 2.minutes(), retry_for = 1.hours())]
impl ProcessPodcast {
    async fn handle(self, records: Inject<Records>, attempt: &Attempt) -> laravel::Result<()> {
        let tenant = laravel::context::get::<String>("tenant").unwrap_or_default();
        records.push(format!(
            "processed {} for {tenant:?} on {}/{} as attempt {}",
            self.podcast_id,
            attempt.connection(),
            attempt.queue(),
            attempt.number(),
        ));

        match self.outcome.as_deref() {
            Some("error") => Err(Corrupt.into()),
            Some("fail") => {
                attempt.fail(Corrupt);
                Ok(())
            }
            Some("release") => {
                attempt.release(30.seconds());
                Ok(())
            }
            Some("delete") => {
                attempt.delete();
                Ok(())
            }
            Some("panic") => panic!("the encoder crashed"),
            _ => Ok(()),
        }
    }

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

#[derive(Queueable)]
struct Ping;

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

#[derive(Queueable)]
struct Renamed;

#[job(name = "podcasts.renamed")]
impl Renamed {
    async fn handle(self) {}
}

fn configure(connection: &'static str) -> laravel::foundation::ApplicationBuilder {
    Application::configure()
        .replace_env(Env::default())
        .with_config(move |config, _| {
            config.queue.default = connection.into();
        })
        .with_services(|services| {
            services.instance(Records::default());
        })
}

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

#[tokio::test]
async fn the_sync_connection_runs_jobs_in_a_fresh_context_with_the_dispatching_contexts_values() {
    let app = configure("sync").create();
    app.scope(async || {
        laravel::context::add("tenant", "acme");

        ProcessPodcast::new(42).dispatch().await.unwrap();
        ProcessPodcast::new(43).dispatch().on_queue("urgent").await.unwrap();
    })
    .await;

    assert_eq!(
        records(&app).await,
        [
            "processed 42 for \"acme\" on sync/podcasts as attempt 1",
            "processed 43 for \"acme\" on sync/urgent as attempt 1",
        ]
    );
}

#[tokio::test]
async fn sync_failures_run_the_failed_hook_once_and_return_the_error() {
    let app = configure("sync").create();
    let errors = app
        .scope(async || {
            let returned = ProcessPodcast::new(1).then("error").dispatch().await.unwrap_err();
            let failed = ProcessPodcast::new(2).then("fail").dispatch().await.unwrap_err();
            let panicked = ProcessPodcast::new(3).then("panic").dispatch().await.unwrap_err();
            ProcessPodcast::new(4).then("release").dispatch().await.unwrap();
            ProcessPodcast::new(5).then("delete").dispatch().await.unwrap();
            [returned, failed, panicked]
        })
        .await;

    assert!(errors[0].is::<Corrupt>() && errors[1].is::<Corrupt>(), "{errors:?}");
    assert!(errors[2].to_string().contains("the encoder crashed"), "{}", errors[2]);
    let records = records(&app).await;
    let failures: Vec<_> = records.iter().filter(|record| record.starts_with("failed")).collect();
    assert_eq!(
        failures[..2],
        ["failed 1: the podcast is corrupt", "failed 2: the podcast is corrupt"]
    );
    assert!(
        failures[2].starts_with("failed 3: ") && failures[2].ends_with("the encoder crashed"),
        "{failures:?}"
    );
    assert_eq!(records.len(), 8, "each job ran once: {records:?}");
}

#[tokio::test]
async fn dispatch_sync_runs_jobs_now_whatever_the_default_connection() {
    let app = configure("discard").create();
    app.scope(async || {
        Ping.dispatch().await.unwrap();
        assert!(records(&app).await.is_empty(), "the discard connection discards jobs");

        Ping.dispatch_sync().await.unwrap();
        queue::dispatch_sync(Ping).await.unwrap();
        let error = ProcessPodcast::new(7).then("error").dispatch_sync().await.unwrap_err();
        assert!(error.is::<Corrupt>());
    })
    .await;

    assert_eq!(
        records(&app).await,
        [
            "ping",
            "ping",
            "processed 7 for \"\" on sync/podcasts as attempt 1",
            "failed 7: the podcast is corrupt",
        ]
    );
}

#[tokio::test]
async fn dispatching_to_an_undefined_connection_fails() {
    let app = configure("sync").create();
    let error = app
        .scope(async || Ping.dispatch().on_connection("beanstalkd").await)
        .await
        .unwrap_err();

    assert_eq!(error.to_string(), "queue connection `beanstalkd` isn't defined");
    assert_eq!(
        app.scope(async || { queue::manager().connection_names() }).await,
        ["database", "discard", "redis", "sqs", "sync"],
    );
}

#[tokio::test]
async fn the_application_refuses_to_start_with_an_undefined_default_connection() {
    let undefined = Application::configure()
        .replace_env(Env::from_iter([("QUEUE_CONNECTION", "beanstalkd")]))
        .try_create()
        .unwrap_err();
    assert_eq!(
        undefined,
        StartupError::Queue("the default queue connection `beanstalkd` isn't defined".into())
    );
}

#[tokio::test]
async fn fakes_record_jobs_with_where_they_were_sent() {
    let app = configure("sync").create();
    app.scope(async || {
        let queue = queue::fake();
        let id = ProcessPodcast::new(42)
            .dispatch()
            .on_connection("database")
            .delay(5.minutes())
            .await
            .unwrap();
        ProcessPodcast::new(43).dispatch().on_queue("urgent").await.unwrap();
        Ping.dispatch().await.unwrap();

        queue
            .assert_pushed::<ProcessPodcast>()
            .assert_pushed_times::<ProcessPodcast>(2)
            .assert_pushed_where::<ProcessPodcast>(|job| job.podcast_id == 42 && job.queue() == "podcasts")
            .assert_pushed_where::<ProcessPodcast>(|job| job.queue() == "urgent" && job.connection() == "sync")
            .assert_not_pushed_where::<ProcessPodcast>(|job| job.podcast_id == 44)
            .assert_pushed_times::<Ping>(1)
            .assert_not_pushed::<Renamed>();

        let pushed = queue.pushed::<ProcessPodcast>();
        assert_eq!(pushed[0].id(), id);
        assert_eq!(pushed[0].connection(), "database");
        assert_eq!(pushed[0].delay(), 5.minutes());
        assert_eq!(pushed[0].delay(), std::time::Duration::from_secs(300));
        assert_ne!(pushed[0].delay(), 4.minutes());
        assert_ne!(pushed[0].delay(), 300.milliseconds());
        assert_eq!(pushed[1].delay(), std::time::Duration::ZERO);
        assert_eq!(queue.pushed::<Ping>()[0].queue(), "default");
    })
    .await;

    assert!(records(&app).await.is_empty(), "faked jobs don't run");
}

#[tokio::test]
async fn tests_run_jobs_on_the_default_connection_even_when_they_name_their_own() {
    let app = Application::configure()
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_services(|services| {
            services.instance(Records::default());
        })
        .create();
    app.scope(async || {
        ProcessPodcast::new(7).dispatch().on_connection("redis").await.unwrap();
        queue::bulk([ProcessPodcast::new(8)])
            .on_connection("database")
            .await
            .unwrap();
        queue::chain(ProcessPodcast::new(9)).on_connection("sqs").await.unwrap();
        let undefined = Ping.dispatch().on_connection("beanstalkd").await.unwrap_err();
        assert_eq!(undefined.to_string(), "queue connection `beanstalkd` isn't defined");

        let queue = queue::fake();
        ProcessPodcast::new(10).dispatch().on_connection("redis").await.unwrap();
        assert_eq!(
            queue.pushed::<ProcessPodcast>()[0].connection(),
            "redis",
            "fakes record the connection the job names"
        );
    })
    .await;

    assert_eq!(
        records(&app).await,
        [
            "processed 7 for \"\" on sync/podcasts as attempt 1",
            "processed 8 for \"\" on sync/podcasts as attempt 1",
            "processed 9 for \"\" on sync/podcasts as attempt 1",
        ]
    );
}

#[tokio::test]
async fn bulk_dispatches_push_each_job_where_it_goes_in_order() {
    let app = configure("sync").create();
    app.scope(async || {
        let queue = queue::fake();
        let ids = queue::bulk((ProcessPodcast::new(1), Ping, ProcessPodcast::new(2)))
            .on_connection("database")
            .await
            .unwrap();
        queue::bulk([Ping]).on_queue("urgent").await.unwrap();
        assert!(queue::bulk(Vec::<Ping>::new()).await.unwrap().is_empty());
        let iterator_ids = queue::bulk((3..=6).filter(|id| id % 2 == 1).map(ProcessPodcast::new))
            .on_queue("imports")
            .await
            .unwrap();

        let podcasts = queue.pushed::<ProcessPodcast>();
        assert_eq!([podcasts[0].id(), podcasts[1].id()], [ids[0], ids[2]]);
        assert_eq!(
            podcasts.iter().map(|job| job.podcast_id).collect::<Vec<_>>(),
            [1, 2, 3, 5]
        );
        assert_eq!([podcasts[2].id(), podcasts[3].id()], iterator_ids.as_slice());
        assert!(podcasts[2..].iter().all(|job| job.queue() == "imports"));
        assert!(
            podcasts[..2]
                .iter()
                .all(|job| job.connection() == "database" && job.queue() == "podcasts")
        );
        let pings: Vec<_> = queue
            .pushed::<Ping>()
            .iter()
            .map(|job| job.queue().to_owned())
            .collect();
        assert_eq!(pings, ["default", "urgent"]);
        assert_eq!(queue.pushed::<Ping>()[0].id(), ids[1]);

        let batch = queue::bulk(queue::batch([Ping])).await.unwrap_err();
        assert!(batch.to_string().contains("not batches"), "{batch}");
    })
    .await;

    assert!(records(&app).await.is_empty(), "faked jobs don't run");
}

#[tokio::test]
async fn bulk_dispatches_on_sync_run_in_order_and_stop_at_the_first_error() {
    let app = configure("sync").create();
    let error = app
        .scope(async || {
            queue::bulk([
                ProcessPodcast::new(1),
                ProcessPodcast::new(2).then("error"),
                ProcessPodcast::new(3),
            ])
            .await
        })
        .await
        .unwrap_err();

    assert!(error.is::<Corrupt>(), "{error}");
    assert_eq!(
        records(&app).await,
        [
            "processed 1 for \"\" on sync/podcasts as attempt 1",
            "processed 2 for \"\" on sync/podcasts as attempt 1",
            "failed 2: the podcast is corrupt",
        ]
    );
}

#[tokio::test]
async fn selective_fakes_let_other_jobs_run_and_dropping_a_fake_restores_dispatch() {
    let app = configure("sync").create();
    app.scope(async || {
        {
            let queue = queue::fake().only::<Ping>();
            Ping.dispatch().await.unwrap();
            ProcessPodcast::new(1).dispatch().await.unwrap();
            queue.assert_pushed::<Ping>().assert_not_pushed::<ProcessPodcast>();
        }
        {
            let queue = queue::fake().except::<Ping>();
            Ping.dispatch().await.unwrap();
            ProcessPodcast::new(2).dispatch_sync().await.unwrap();
            queue.assert_not_pushed::<Ping>().assert_pushed::<ProcessPodcast>();
            assert_eq!(queue.pushed::<ProcessPodcast>()[0].connection(), "sync");
        }
        Ping.dispatch().await.unwrap();
    })
    .await;

    assert_eq!(
        records(&app).await,
        ["processed 1 for \"\" on sync/podcasts as attempt 1", "ping", "ping"]
    );
}

#[tokio::test]
#[should_panic(
    expected = "expected job `integration::queue::Ping` to be pushed at least once; recorded jobs: [\"podcasts.renamed\"]"
)]
async fn failed_fake_assertions_name_the_recorded_jobs() {
    let app = configure("sync").create();
    app.scope(async || {
        let queue = queue::fake();
        Renamed.dispatch().await.unwrap();
        queue.assert_pushed::<Ping>();
    })
    .await;
}

#[tokio::test]
async fn handlers_dispatch_jobs() {
    async fn upload() -> laravel::Result<&'static str> {
        ProcessPodcast::new(42).dispatch().await?;
        Ok("queued")
    }

    let app = configure("sync")
        .with_routing(|routing, _| {
            routing.routes(|routes| {
                routes.post("/podcasts", upload);
            });
        })
        .create();
    let queue = app.scope(async || queue::fake()).await;

    app.post("/podcasts").await.assert_ok().assert_see("queued");
    queue.assert_pushed_where::<ProcessPodcast>(|job| job.podcast_id == 42);
}

#[tokio::test]
async fn test_jobs_report_how_an_attempt_ended() {
    let app = configure("discard").create();

    app.job(ProcessPodcast::new(1)).await.assert_succeeded();
    app.job(ProcessPodcast::new(2).then("release"))
        .await
        .assert_released()
        .assert_released_after(30.seconds());
    app.job(ProcessPodcast::new(3).then("delete")).await.assert_deleted();
    app.job(ProcessPodcast::new(4).then("fail"))
        .attempt(2)
        .await
        .assert_failed()
        .assert_failed_with::<Corrupt>();
    let panicked = app.job(ProcessPodcast::new(5).then("panic")).await;
    assert!(
        panicked
            .assert_failed()
            .error()
            .unwrap()
            .to_string()
            .contains("encoder crashed")
    );

    assert_eq!(
        records(&app).await,
        [
            "processed 1 for \"\" on discard/podcasts as attempt 1",
            "processed 2 for \"\" on discard/podcasts as attempt 1",
            "processed 3 for \"\" on discard/podcasts as attempt 1",
            "processed 4 for \"\" on discard/podcasts as attempt 2",
            "processed 5 for \"\" on discard/podcasts as attempt 1",
        ],
        "test jobs don't run failed hooks"
    );
}

#[tokio::test]
#[should_panic(
    expected = "expected job `integration::queue::ProcessPodcast` to be released for 60s, but it was released for 30s"
)]
async fn failed_test_job_assertions_say_how_the_job_ended() {
    let app = configure("discard").create();
    app.job(ProcessPodcast::new(1).then("release"))
        .await
        .assert_released_after(1.minutes());
}

#[tokio::test]
async fn missing_services_fail_the_job_naming_it() {
    #[derive(Queueable)]
    struct NeedsMailer;
    struct Mailer;
    #[job]
    impl NeedsMailer {
        async fn handle(self, _mailer: Inject<Mailer>) {}
    }

    let app = configure("sync").create();
    let result = app.job(NeedsMailer).await;
    let error = result.assert_failed().error().unwrap().to_string();
    assert!(
        error.contains("injecting `integration::queue::NeedsMailer` failed"),
        "{error}"
    );
}

#[cfg(feature = "database")]
pub(crate) mod database {
    use laravel::config::database::ConnectionConfig;
    use laravel::db::{self, AnyConnection, Driver};
    use serde_json::Value;

    use super::*;

    pub(crate) fn create_table(driver: Driver) -> &'static str {
        match driver {
            Driver::Postgres => {
                "CREATE TABLE jobs (
                    id BIGSERIAL PRIMARY KEY,
                    queue VARCHAR(255) NOT NULL,
                    payload TEXT NOT NULL,
                    attempts INTEGER NOT NULL DEFAULT 0,
                    reserved_at TIMESTAMP(6),
                    available_at TIMESTAMP(6) NOT NULL,
                    created_at TIMESTAMP(6) NOT NULL
                )"
            }
            Driver::MySql | Driver::MariaDb => {
                "CREATE TABLE jobs (
                    id BIGINT AUTO_INCREMENT PRIMARY KEY,
                    queue VARCHAR(255) NOT NULL,
                    payload LONGTEXT NOT NULL,
                    attempts INT NOT NULL DEFAULT 0,
                    reserved_at DATETIME(6) NULL,
                    available_at DATETIME(6) NOT NULL,
                    created_at DATETIME(6) NOT NULL,
                    INDEX jobs_queue_index (queue)
                )"
            }
            _ => {
                "CREATE TABLE jobs (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    queue VARCHAR(255) NOT NULL,
                    payload TEXT NOT NULL,
                    attempts INTEGER NOT NULL DEFAULT 0,
                    reserved_at TIMESTAMP(6),
                    available_at TIMESTAMP(6) NOT NULL,
                    created_at TIMESTAMP(6) NOT NULL
                )"
            }
        }
    }

    pub(crate) async fn application(url: impl Into<String>) -> Application {
        let url = url.into();
        let app = configure("database")
            .with_config(move |config, _| {
                let mut connection = ConnectionConfig::new(url);
                connection.max_connections = 1;
                connection.idle_timeout = None;
                connection.max_lifetime = None;
                config.database.default = "primary".into();
                config.database.connections.insert("primary".into(), connection);
            })
            .create();
        app.scope(async || {
            let connection = db::default_connection()?;
            connection.query("DROP TABLE IF EXISTS jobs").statement().await?;
            connection.query(create_table(connection.driver())).statement().await
        })
        .await
        .unwrap();
        app
    }

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

    async fn rows(connection: &AnyConnection) -> Vec<Row> {
        connection
            .query("SELECT queue, payload, attempts, reserved_at, available_at, created_at FROM jobs ORDER BY id")
            .select_as()
            .await
            .unwrap()
    }

    pub(crate) fn create_failed_table(driver: Driver) -> &'static str {
        match driver {
            Driver::Postgres => {
                "CREATE TABLE failed_jobs (
                    id BIGSERIAL PRIMARY KEY,
                    job_id VARCHAR(36) NOT NULL UNIQUE,
                    connection VARCHAR(255) NOT NULL,
                    queue VARCHAR(255) NOT NULL,
                    payload TEXT NOT NULL,
                    error TEXT NOT NULL,
                    failed_at TIMESTAMP(6) NOT NULL
                )"
            }
            Driver::MySql | Driver::MariaDb => {
                "CREATE TABLE failed_jobs (
                    id BIGINT AUTO_INCREMENT PRIMARY KEY,
                    job_id VARCHAR(36) NOT NULL UNIQUE,
                    connection VARCHAR(255) NOT NULL,
                    queue VARCHAR(255) NOT NULL,
                    payload LONGTEXT NOT NULL,
                    error LONGTEXT NOT NULL,
                    failed_at DATETIME(6) NOT NULL
                )"
            }
            _ => {
                "CREATE TABLE failed_jobs (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    job_id VARCHAR(36) NOT NULL UNIQUE,
                    connection VARCHAR(255) NOT NULL,
                    queue VARCHAR(255) NOT NULL,
                    payload TEXT NOT NULL,
                    error TEXT NOT NULL,
                    failed_at TIMESTAMP(6) NOT NULL
                )"
            }
        }
    }

    #[tokio::test]
    async fn the_application_refuses_to_start_with_an_invalid_table() {
        let invalid = Application::configure()
            .replace_env(Env::default())
            .with_config(|config, _| {
                config.queue.add_connection(
                    "jobs",
                    laravel::config::queue::DatabaseQueue::new().table("jobs; DROP TABLE users"),
                );
            })
            .try_create()
            .unwrap_err();
        assert!(
            matches!(&invalid, StartupError::Queue(message) if message.contains("queue connection `jobs` uses the table")),
            "{invalid:?}"
        );
    }

    pub(crate) async fn push_contract(app: &Application) {
        let now = laravel::time::Timestamp::from_second(1_800_000_000).unwrap();
        app.travel_to(now);
        let now = now.as_second();

        let (first, rows) = app
            .scope(async || {
                laravel::context::add("tenant", "acme");
                laravel::context::add_hidden("token", "secret");
                let first = ProcessPodcast::new(42).dispatch().await.unwrap();
                Ping.dispatch().delay(90.seconds()).await.unwrap();
                Ping.dispatch()
                    .on_queue("later")
                    .delay(laravel::time::Timestamp::from_second(now + 3600).unwrap())
                    .await
                    .unwrap();
                (first, rows(&db::default_connection().unwrap()).await)
            })
            .await;

        assert!(records(app).await.is_empty(), "nothing runs until a worker takes it");
        let queues: Vec<_> = rows
            .iter()
            .map(|row| (row.queue.as_str(), row.available_at.as_second() - now))
            .collect();
        assert_eq!(queues, [("podcasts", 0), ("default", 90), ("later", 3600)]);
        assert!(
            rows.iter()
                .all(|row| row.attempts == 0 && row.reserved_at.is_none() && row.created_at.as_second() == now)
        );

        let payload: Value = serde_json::from_str(&rows[0].payload).unwrap();
        assert_eq!(
            payload,
            serde_json::json!({
                "version": 1,
                "id": first.to_string(),
                "job": "integration::queue::ProcessPodcast",
                "data": { "podcast_id": 42, "outcome": null },
                "context": { "tenant": "acme" },
                "hidden_context": { "token": "secret" },
                "dispatched_at": now,
            })
        );
    }

    pub(crate) async fn transaction_contract(app: &Application) {
        let (during, after) = app
            .scope(async || {
                db::default_connection()?.query("DELETE FROM jobs").statement().await?;
                let connection = db::default_connection().unwrap();
                let during = connection
                    .transaction(async |tx| {
                        ProcessPodcast::new(1).dispatch().await?;
                        tx.query("SELECT COUNT(*) FROM jobs").scalar::<i64>().await
                    })
                    .await
                    .unwrap();
                let rolled_back = connection
                    .transaction(async |_| {
                        ProcessPodcast::new(2).dispatch().await?;
                        Err::<(), _>(laravel::abort_with(500, "rolled back"))
                    })
                    .await;
                assert!(rolled_back.is_err());
                Ok::<_, laravel::Error>((during, rows(&connection).await))
            })
            .await
            .unwrap();

        assert_eq!(during, Some(0), "the job waits for the commit");
        let payloads: Vec<Value> = after
            .iter()
            .map(|row| serde_json::from_str(&row.payload).unwrap())
            .collect();
        assert_eq!(payloads.len(), 1);
        assert_eq!(payloads[0]["data"]["podcast_id"], 1);
    }

    pub(crate) async fn bulk_contract(app: &Application) {
        let (ids, during, after) = app
            .scope(async || {
                db::default_connection()?.query("DELETE FROM jobs").statement().await?;
                let connection = db::default_connection().unwrap();
                let (ids, during) = connection
                    .transaction(async |tx| {
                        let ids = queue::bulk((ProcessPodcast::new(1), Ping, ProcessPodcast::new(2), Ping)).await?;
                        let during = tx.query("SELECT COUNT(*) FROM jobs").scalar::<i64>().await?;
                        Ok::<_, laravel::Error>((ids, during))
                    })
                    .await
                    .unwrap();
                let rolled_back = connection
                    .transaction(async |_| {
                        queue::bulk([Ping, Ping]).await?;
                        Err::<(), _>(laravel::abort_with(500, "rolled back"))
                    })
                    .await;
                assert!(rolled_back.is_err());
                queue::bulk([ProcessPodcast::new(3), ProcessPodcast::new(4)])
                    .on_queue("urgent")
                    .await
                    .unwrap();
                Ok::<_, laravel::Error>((ids, during, rows(&connection).await))
            })
            .await
            .unwrap();

        assert_eq!(during, Some(0), "the jobs wait for the commit");
        let stored: Vec<_> = after
            .iter()
            .map(|row| {
                let payload: Value = serde_json::from_str(&row.payload).unwrap();
                (row.queue.as_str(), payload["id"].as_str().unwrap().to_owned())
            })
            .collect();
        let queues: Vec<_> = stored.iter().map(|(queue, _)| *queue).collect();
        assert_eq!(
            queues,
            ["podcasts", "default", "podcasts", "default", "urgent", "urgent"]
        );
        let first_ids: Vec<_> = stored[..4].iter().map(|(_, id)| id.clone()).collect();
        assert_eq!(first_ids, ids.iter().map(ToString::to_string).collect::<Vec<_>>());
    }

    #[cfg(feature = "database-sqlite")]
    #[tokio::test]
    async fn sqlite_stores_jobs_with_their_queue_delay_and_context() {
        let app = application("sqlite::memory:").await;
        push_contract(&app).await;
        transaction_contract(&app).await;
        bulk_contract(&app).await;
    }

    #[cfg(feature = "database-sqlite")]
    #[tokio::test]
    async fn sync_jobs_in_a_transaction_run_once_it_commits_and_dispatch_sync_runs_at_once() {
        let app = configure("sync")
            .with_config(|config, _| {
                let mut connection = ConnectionConfig::new("sqlite::memory:");
                connection.max_connections = 1;
                config.database.default = "primary".into();
                config.database.connections.insert("primary".into(), connection);
            })
            .create();
        let during = app
            .scope(async || {
                db::default_connection()
                    .unwrap()
                    .transaction(async |_| {
                        Ping.dispatch().await?;
                        ProcessPodcast::new(1).dispatch_sync().await?;
                        Ok(app.resolve::<Records>().await.all())
                    })
                    .await
                    .unwrap()
            })
            .await;

        assert_eq!(during, ["processed 1 for \"\" on sync/podcasts as attempt 1"]);
        assert_eq!(
            records(&app).await,
            ["processed 1 for \"\" on sync/podcasts as attempt 1", "ping"]
        );
    }

    #[derive(Queueable)]
    struct CountPodcasts;

    #[job]
    impl CountPodcasts {
        async fn handle(self, records: Inject<Records>) -> laravel::Result<()> {
            let count = db::default_connection()?
                .query("SELECT COUNT(*) FROM podcasts")
                .scalar::<i64>()
                .await?
                .unwrap_or_default();
            records.push(format!("{count} podcasts"));
            Ok(())
        }
    }

    #[cfg(feature = "database-sqlite")]
    #[tokio::test]
    async fn dispatch_sync_in_a_transaction_sees_its_rows() {
        // A file and a second pooled connection, so a job outside the transaction reads the
        // committed table instead of waiting for the transaction's connection...
        let directory = crate::support::TempDir::new("dispatch-sync-transaction");
        let url = format!("sqlite://{}?mode=rwc", directory.join("podcasts.sqlite").display());
        let app = configure("sync")
            .with_config(move |config, _| {
                let mut connection = ConnectionConfig::new(url);
                connection.max_connections = 2;
                config.database.default = "primary".into();
                config.database.connections.insert("primary".into(), connection);
            })
            .create();
        app.scope(async || {
            let connection = db::default_connection()?;
            connection
                .query("CREATE TABLE podcasts (id INTEGER PRIMARY KEY)")
                .statement()
                .await?;
            connection
                .transaction(async |transaction| {
                    transaction
                        .query("INSERT INTO podcasts (id) VALUES (1)")
                        .statement()
                        .await?;
                    CountPodcasts.dispatch_sync().await
                })
                .await
        })
        .await
        .unwrap();

        assert_eq!(records(&app).await, ["1 podcasts"]);
    }
}