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
use std::sync::{Arc, Mutex};
use std::time::Duration;

use laravel::Application;
use laravel::config::Env;
use laravel::config::database::ConnectionConfig;
use laravel::container::Inject;
use laravel::db;
use laravel::event::{Event, listener};
use laravel::model::{Created, HasMany, Updated, create, model, update};
use laravel::queue::events::JobProcessed;
use laravel::queue::{self, Batch, Queueable, callback, job};
use laravel::testing::{MakesConsoleRequests, RunsJobs, TestCommandResult};
use serde_json::{Value, json};

use crate::queue::Records;
use crate::queue::database::{create_failed_table, create_table};
use crate::queue_batches::create_batch_tables;
use crate::support::TempDir;

#[model]
pub struct User {
    pub id: i64,
    pub name: String,
    pub email: String,
    #[has_many]
    pub posts: HasMany<Post>,
}

#[model]
pub struct Post {
    pub id: i64,
    pub user_id: i64,
    pub title: String,
}

#[derive(Queueable)]
struct SendDigest {
    user: User,
    editor: Option<User>,
    reviewer: Option<User>,
    posts: Vec<Post>,
    note: String,
}

#[job(name = "models.digest", tries = 3, fail_when_missing_models)]
impl SendDigest {
    async fn handle(self, records: Inject<Records>) {
        let titles: Vec<&str> = self.posts.iter().map(|post| post.title.as_str()).collect();
        records.push(format!(
            "digest for {} edited by {:?} reviewed by {:?}: {titles:?} ({})",
            self.user.name,
            self.editor.map(|editor| editor.name),
            self.reviewer.map(|reviewer| reviewer.name),
            self.note,
        ));
    }

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

#[derive(Queueable)]
struct Forget {
    post: Option<Post>,
    posts: Vec<Post>,
}

#[job(name = "models.forget")]
impl Forget {
    async fn handle(self, records: Inject<Records>) {
        records.push(format!("forgot {} posts", self.posts.len()));
    }
}

#[derive(Queueable)]
struct Announce {
    author: User,
    readers: Vec<User>,
}

#[job(name = "models.announce")]
impl Announce {
    async fn handle(self, records: Inject<Records>) {
        let readers: Vec<&str> = self.readers.iter().map(|reader| reader.name.as_str()).collect();
        records.push(format!("{} announced to {readers:?}", self.author.name));
    }
}

#[derive(Queueable)]
struct Remind {
    #[serde(alias = "user")]
    recipient: User,
    #[serde(default)]
    followers: Vec<User>,
    #[serde(default = "default_times::<3>")]
    times: u32,
    #[serde(rename = "msg")]
    message: String,
}

const fn default_times<const N: u32>() -> u32 {
    N
}

#[job(name = "models.remind")]
impl Remind {
    async fn handle(self, records: Inject<Records>) {
        records.push(format!(
            "remind {} {} times with {} followers: {}",
            self.recipient.name,
            self.times,
            self.followers.len(),
            self.message
        ));
    }
}

#[derive(Queueable)]
struct Rename {
    user: User,
    delete: bool,
}

#[job(name = "models.rename", tries = 1)]
impl Rename {
    async fn handle(mut self) -> laravel::Result<()> {
        update!(self.user { name: "Renamed" }).quietly().await?;
        if self.delete {
            self.user.delete().await?;
        }
        Err(laravel::abort_with(500, "the rename broke"))
    }

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

#[derive(Queueable)]
struct Celebrate {
    user: User,
}

#[callback(name = "models.celebrate")]
impl Celebrate {
    async fn then(self, _batch: &Batch, records: Inject<Records>) {
        records.push(format!("celebrate {}", self.user.name));
    }

    async fn catch(self, _error: &laravel::Error, records: Inject<Records>) {
        records.push(format!("console {}", self.user.name));
    }
}

#[listener(queued, name = "models.welcome")]
async fn welcome(event: Event<Created<User>>, records: Inject<Records>) {
    records.push(format!("welcome {} <{}>", event.model.name, event.model.email));
}

#[listener(queued, name = "models.reverify")]
async fn reverify(event: Event<Updated<User>>, records: Inject<Records>) {
    let columns: Vec<&str> = event.changes.columns().collect();
    records.push(format!(
        "reverify {} <{}>: {} {columns:?}",
        event.model.name,
        event.model.email,
        event.changes.has(User::email),
    ));
}

#[listener(queued, name = "models.audit", fail_when_missing_models)]
async fn audit(event: Event<Updated<User>>, records: Inject<Records>) {
    records.push(format!("audit {}", event.changes.old(User::email)));
}

#[derive(Queueable)]
struct Mourn {
    user: User,
}

#[callback(name = "models.mourn", fail_when_missing_models)]
impl Mourn {
    async fn then(self, _batch: &Batch, records: Inject<Records>) {
        records.push(format!("mourn {}", self.user.name));
    }
}

#[derive(Default)]
struct Queries(Arc<Mutex<Vec<String>>>);

/// The errors the application reported.
#[derive(Clone, Default)]
struct Reported(Arc<Mutex<Vec<String>>>);

/// Each processed job's name and outcome.
#[derive(Default)]
struct Processed(Mutex<Vec<String>>);

async fn application(name: &str) -> (TempDir, Application) {
    let directory = TempDir::new(name);
    let url = format!("sqlite://{}?mode=rwc", directory.join("models.sqlite").display());
    let reported = Reported::default();
    let app = Application::configure()
        .replace_env(Env::default())
        .with_config(move |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(Queries::default());
                services.instance(reported);
                services.instance(Processed::default());
            }
        })
        .with_errors(move |errors, _| {
            errors.report_all(move |error| reported.0.lock().unwrap().push(error.to_string()));
        })
        .with_events(|events, _| {
            events.listen(welcome);
            events.listen(reverify);
            events.listen(audit);
            events.listen(|event: Event<JobProcessed>, processed: Inject<Processed>| async move {
                let line = format!("{} {}", event.job.name, event.outcome);
                processed.0.lock().unwrap().push(line);
            });
        })
        .create();
    app.scope(async || {
        let connection = db::default_connection()?;
        connection.query(create_table(connection.driver())).statement().await?;
        connection
            .query(create_failed_table(connection.driver()))
            .statement()
            .await?;
        for table in [
            "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL)",
            "CREATE TABLE posts (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, title TEXT NOT NULL)",
        ] {
            connection.query(db::sqlx::AssertSqlSafe(table)).statement().await?;
        }
        let queries = Arc::clone(&laravel::resolve::<Queries>().await?.0);
        connection.listen(move |query| queries.lock().unwrap().push(query.sql.to_string()));
        Ok::<_, laravel::Error>(())
    })
    .await
    .unwrap();

    (directory, app)
}

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

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

/// The data of each queued job, in order.
async fn queued(app: &Application) -> Vec<Value> {
    app.scope(async || {
        let payloads: Vec<String> = db::default_connection()?
            .query("SELECT payload FROM jobs ORDER BY id")
            .select_as()
            .await?;
        Ok::<_, laravel::Error>(
            payloads
                .iter()
                .map(|payload| serde_json::from_str::<Value>(payload).unwrap()["data"].clone())
                .collect(),
        )
    })
    .await
    .unwrap()
}

async fn processed(app: &Application) -> Vec<String> {
    app.resolve::<Processed>().await.0.lock().unwrap().clone()
}

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

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

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

async fn seed(app: &Application) -> (User, User, Vec<Post>) {
    app.scope(async || {
        let taylor = create!(User {
            name: "Taylor",
            email: "taylor@laravel.com"
        })
        .quietly()
        .await?;
        let abigail = create!(User {
            name: "Abigail",
            email: "abigail@laravel.com"
        })
        .quietly()
        .await?;
        let first = create!(Post {
            user_id: taylor.id,
            title: "First"
        })
        .quietly()
        .await?;
        let second = create!(Post {
            user_id: taylor.id,
            title: "Second"
        })
        .quietly()
        .await?;
        Ok::<_, laravel::Error>((taylor, abigail, vec![second, first]))
    })
    .await
    .unwrap()
}

#[tokio::test]
async fn model_fields_are_stored_as_keys_and_read_again_before_the_job_runs() {
    let (_directory, app) = application("queue-models-keys").await;
    let (taylor, abigail, posts) = seed(&app).await;
    app.scope(async || {
        let note = "weekly".to_owned();
        SendDigest {
            user: taylor,
            editor: Some(abigail),
            reviewer: None,
            posts,
            note,
        }
        .dispatch()
        .await
    })
    .await
    .unwrap();

    assert_eq!(
        queued(&app).await,
        [json!({ "user": 1, "editor": 2, "reviewer": null, "posts": [2, 1], "note": "weekly" })]
    );

    statement(&app, "UPDATE users SET name = 'Taylor Otwell' WHERE id = 1").await;
    let queries = Arc::clone(&app.resolve::<Queries>().await.0);
    queries.lock().unwrap().clear();
    work(&app).await.assert_successful();

    assert_eq!(
        records(&app).await,
        [r#"digest for Taylor Otwell edited by Some("Abigail") reviewed by None: ["Second", "First"] (weekly)"#]
    );
    let reads: Vec<String> = queries
        .lock()
        .unwrap()
        .iter()
        .filter(|sql| !sql.contains("`jobs`"))
        .cloned()
        .collect();
    assert_eq!(
        reads,
        [
            "select `users`.* from `users` where `users`.`id` in (?, ?)",
            "select `posts`.* from `posts` where `posts`.`id` in (?, ?)",
        ]
    );
}

#[tokio::test]
async fn fail_when_missing_models_fails_the_job_for_good_naming_the_model_and_keys() {
    let (_directory, app) = application("queue-models-missing").await;
    let (taylor, _, posts) = seed(&app).await;
    app.scope(async || {
        let note = String::new();
        SendDigest {
            user: taylor,
            editor: None,
            reviewer: None,
            posts,
            note,
        }
        .dispatch()
        .await
    })
    .await
    .unwrap();
    statement(&app, "DELETE FROM users WHERE id = 1").await;

    work(&app).await.assert_successful();

    assert_eq!(
        records(&app).await,
        Vec::<String>::new(),
        "neither `handle` nor `failed` runs"
    );
    assert_eq!(queued(&app).await, Vec::<Value>::new(), "the job isn't retried");
    let errors = failed_errors(&app).await;
    assert_eq!(errors.len(), 1, "{errors:?}");
    assert!(errors[0].contains("no `User` has the key `1` any more"), "{errors:?}");
}

#[tokio::test]
async fn a_missing_row_deletes_the_job_by_default() {
    let (_directory, app) = application("queue-models-delete").await;
    let (_, _, posts) = seed(&app).await;
    let forget = || Forget {
        post: Some(posts[1].clone()),
        posts: posts.clone(),
    };
    app.scope(async || forget().dispatch().await).await.unwrap();
    statement(&app, "DELETE FROM posts WHERE id = 1").await;

    work(&app).await.assert_successful();

    assert_eq!(records(&app).await, Vec::<String>::new());
    assert_eq!(queued(&app).await, Vec::<Value>::new());
    assert_eq!(failed_errors(&app).await, Vec::<String>::new());
    assert_eq!(processed(&app).await, ["models.forget missing models"]);
    app.job(forget()).await.assert_deleted();
}

#[tokio::test]
async fn a_chain_whose_job_is_deleted_for_missing_models_lets_its_batch_finish() {
    let (_directory, app) = application("queue-models-batched-chain").await;
    let (taylor, abigail, posts) = seed(&app).await;
    let id = app
        .scope(async || {
            let connection = db::default_connection()?;
            for table in create_batch_tables(connection.driver()) {
                connection.query(table).statement().await?;
            }
            let forget = Forget {
                post: Some(posts[0].clone()),
                posts: Vec::new(),
            };
            let announce = Announce {
                author: abigail,
                readers: Vec::new(),
            };

            queue::batch([queue::chain((forget, announce))])
                .then(Celebrate { user: taylor })
                .await
        })
        .await
        .unwrap();
    statement(&app, "DELETE FROM posts").await;

    work(&app).await.assert_successful();

    let batch = app.scope(async || queue::find_batch(id).await).await.unwrap().unwrap();
    assert_eq!((batch.pending_jobs(), batch.failed_jobs()), (0, 0), "{batch:?}");
    assert!(batch.is_finished(), "{batch:?}");
    assert_eq!(
        records(&app).await,
        ["celebrate Taylor"],
        "the rest of the chain doesn't run"
    );
}

#[tokio::test]
async fn the_failed_hook_reads_the_models_again_and_is_skipped_when_a_row_is_gone() {
    let (_directory, app) = application("queue-models-failed").await;
    let (taylor, abigail, _) = seed(&app).await;
    app.scope(async || {
        Rename {
            user: taylor,
            delete: false,
        }
        .dispatch()
        .await?;
        Rename {
            user: abigail,
            delete: true,
        }
        .dispatch()
        .await
    })
    .await
    .unwrap();

    work(&app).await.assert_successful();

    assert_eq!(records(&app).await, ["rename of Renamed failed"]);
    let errors = failed_errors(&app).await;
    assert_eq!(errors.len(), 2, "{errors:?}");
    assert!(
        errors.iter().all(|error| error.contains("the rename broke")),
        "{errors:?}"
    );
}

#[tokio::test]
async fn model_events_queue_their_keys_and_updated_keeps_only_the_changed_column_names() {
    let (_directory, app) = application("queue-models-events").await;
    app.scope(async || {
        let mut user = create!(User {
            name: "Taylor",
            email: "old@laravel.com"
        })
        .await?;
        update!(user {
            email: "new@laravel.com"
        })
        .await?;
        Ok::<_, laravel::Error>(())
    })
    .await
    .unwrap();

    let queued = queued(&app).await;
    assert_eq!(queued.len(), 3, "{queued:?}");
    assert_eq!(queued[0], json!({ "model": 1 }));
    for updated in &queued[1..] {
        assert_eq!(*updated, json!({ "model": 1, "changes": ["email"] }));
        let payload = updated.to_string();
        assert!(
            !payload.contains("old@laravel.com") && !payload.contains("new@laravel.com"),
            "{payload}"
        );
    }
    statement(&app, "UPDATE users SET name = 'Taylor Otwell' WHERE id = 1").await;
    work(&app).await.assert_successful();

    assert_eq!(
        records(&app).await,
        [
            "welcome Taylor Otwell <new@laravel.com>",
            r#"reverify Taylor Otwell <new@laravel.com>: true ["email"]"#,
        ]
    );
    let errors = failed_errors(&app).await;
    assert_eq!(errors.len(), 1, "{errors:?}");
    assert!(
        errors[0].contains(
            "a queued listener's `Updated` holds only the names of the changed columns; read old and new values in a \
             listener that isn't queued"
        ),
        "{errors:?}"
    );
}

#[tokio::test]
async fn queued_listeners_whose_row_is_gone_are_deleted_unless_they_ask_to_fail() {
    let (_directory, app) = application("queue-models-listeners").await;
    app.scope(async || {
        let mut user = create!(User {
            name: "Taylor",
            email: "old@laravel.com"
        })
        .await?;
        update!(user {
            email: "new@laravel.com"
        })
        .await?;
        Ok::<_, laravel::Error>(())
    })
    .await
    .unwrap();
    statement(&app, "DELETE FROM users WHERE id = 1").await;

    work(&app).await.assert_successful();

    assert_eq!(records(&app).await, Vec::<String>::new());
    let errors = failed_errors(&app).await;
    assert_eq!(errors.len(), 1, "only `audit` fails: {errors:?}");
    assert!(errors[0].contains("no `User` has the key `1` any more"), "{errors:?}");
}

/// Field names that the derive's own generated code also uses.
#[derive(Queueable)]
struct Export {
    fields: Vec<String>,
    stored: String,
    rows: User,
}

#[job(name = "models.export")]
impl Export {
    async fn handle(self) {}
}

#[tokio::test]
async fn fields_may_share_names_with_the_derives_own_variables() {
    let (_directory, app) = application("queue-models-names").await;
    let (taylor, _, _) = seed(&app).await;
    app.scope(async || {
        let fake = queue::fake();
        Export {
            fields: vec!["email".into()],
            stored: "csv".into(),
            rows: taylor,
        }
        .dispatch()
        .await?;

        fake.assert_pushed_where::<Export>(|job| {
            job.fields == ["email"] && job.stored == "csv" && job.rows.name == "Taylor"
        });
        Ok::<_, laravel::Error>(())
    })
    .await
    .unwrap();
}

#[tokio::test]
async fn queue_fakes_assert_against_the_models_as_dispatched() {
    let (_directory, app) = application("queue-models-fake").await;
    let (taylor, abigail, posts) = seed(&app).await;
    app.scope(async || {
        let fake = queue::fake();
        let mut user = taylor.clone();
        user.load(User::posts).await?;
        SendDigest {
            user,
            editor: None,
            reviewer: None,
            posts: posts.clone(),
            note: String::new(),
        }
        .dispatch()
        .await?;
        let rename = Rename {
            user: abigail.clone(),
            delete: false,
        };
        let user = taylor.clone();
        queue::chain((Forget { post: None, posts }, rename))
            .catch(Celebrate { user })
            .await?;
        queue::batch([Forget {
            post: None,
            posts: Vec::new(),
        }])
        .then(Celebrate { user: abigail.clone() })
        .await?;
        statement_in_scope("DELETE FROM users").await?;

        fake.assert_pushed_where::<SendDigest>(|job| {
            job.user.email == "taylor@laravel.com" && job.user.posts.try_loaded().is_none() && job.posts.len() == 2
        });
        let chained = fake.pushed::<Forget>().remove(0);
        assert_eq!(chained.posts[0].title, "Second");
        assert_eq!(chained.chain().get::<Rename>(0).unwrap().user.name, "Abigail");
        assert_eq!(chained.chain_catch().get::<Celebrate>(0).unwrap().user.name, "Taylor");
        let batch = fake.batches().remove(0);
        assert_eq!(batch.then().get::<Celebrate>(0).unwrap().user.name, "Abigail");
        Ok::<_, laravel::Error>(())
    })
    .await
    .unwrap();
}

async fn statement_in_scope(sql: &'static str) -> laravel::Result<()> {
    db::default_connection()?
        .query(db::sqlx::AssertSqlSafe(sql))
        .statement()
        .await
        .map(drop)
}

#[tokio::test]
async fn jobs_queued_before_a_field_was_added_or_renamed_still_run() {
    let (_directory, app) = application("queue-models-serde").await;
    let (taylor, abigail, _) = seed(&app).await;
    app.scope(async || {
        let message = "Ship it".to_owned();
        Remind {
            recipient: taylor,
            followers: vec![abigail],
            times: 5,
            message,
        }
        .dispatch()
        .await
    })
    .await
    .unwrap();
    assert_eq!(
        queued(&app).await,
        [json!({ "recipient": 1, "followers": [2], "times": 5, "msg": "Ship it" })]
    );

    // The job as it was stored before `recipient` was renamed and `followers` and `times` added...
    app.scope(async || {
        let connection = db::default_connection()?;
        let payload: String = connection
            .query("SELECT payload FROM jobs")
            .select_as()
            .await?
            .remove(0);
        let mut payload: Value = serde_json::from_str(&payload)?;
        payload["data"] = json!({ "user": 1, "msg": "Ship it" });

        connection
            .query("UPDATE jobs SET payload = ?")
            .bind(payload.to_string())
            .statement()
            .await
    })
    .await
    .unwrap();
    work(&app).await.assert_successful();

    assert_eq!(records(&app).await, ["remind Taylor 3 times with 0 followers: Ship it"]);
}

async fn announce(app: &Application, author: &str, readers: &[&str]) -> (Vec<String>, Vec<String>) {
    let (taylor, abigail, _) = seed(app).await;
    let (author, readers) = app
        .scope(async || {
            let jess = create!(User {
                name: "Jess",
                email: "jess@laravel.com"
            })
            .quietly()
            .await?;
            let user = |name: &str| {
                [&taylor, &abigail, &jess]
                    .into_iter()
                    .find(|user| user.name == name)
                    .unwrap()
                    .clone()
            };
            let readers: Vec<User> = readers.iter().map(|name| user(name)).collect();
            Ok::<_, laravel::Error>((user(author), readers))
        })
        .await
        .unwrap();
    app.scope(async || Announce { author, readers }.dispatch().await)
        .await
        .unwrap();
    statement(app, "DELETE FROM users WHERE name = 'Abigail'").await;

    work(app).await.assert_successful();

    (records(app).await, failed_errors(app).await)
}

#[tokio::test]
async fn a_list_leaves_out_models_whose_rows_are_gone() {
    let (_directory, app) = application("queue-models-list").await;

    let (records, errors) = announce(&app, "Taylor", &["Jess", "Abigail", "Taylor", "Jess"]).await;

    assert_eq!(records, [r#"Taylor announced to ["Jess", "Taylor", "Jess"]"#]);
    assert_eq!(errors, Vec::<String>::new());
}

#[tokio::test]
async fn a_missing_row_a_list_shares_with_a_single_model_deletes_the_job() {
    let (_directory, app) = application("queue-models-shared").await;

    let (records, errors) = announce(&app, "Abigail", &["Abigail", "Jess"]).await;

    assert_eq!(records, Vec::<String>::new());
    assert_eq!(errors, Vec::<String>::new());
}

#[tokio::test]
async fn a_callback_whose_row_is_gone_is_skipped_unless_it_asks_to_fail() {
    let (_directory, app) = application("queue-models-callbacks").await;
    let (taylor, abigail, _) = seed(&app).await;
    app.scope(async || {
        let connection = db::default_connection()?;
        for table in create_batch_tables(connection.driver()) {
            connection.query(table).statement().await?;
        }
        let announce = Announce {
            author: taylor.clone(),
            readers: Vec::new(),
        };

        queue::batch([announce])
            .then(Celebrate { user: abigail.clone() })
            .then(Mourn { user: abigail })
            .then(Celebrate { user: taylor })
            .await
    })
    .await
    .unwrap();
    statement(&app, "DELETE FROM users WHERE name = 'Abigail'").await;

    work(&app).await.assert_successful();

    assert_eq!(records(&app).await, ["Taylor announced to []", "celebrate Taylor"]);
    let reported = reported(&app).await;
    assert_eq!(reported.len(), 1, "only `Mourn` reports: {reported:?}");
    assert!(
        reported[0].contains("no `User` has the key `2` any more"),
        "{reported:?}"
    );
}