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

use laravel::Application;
use laravel::config::Env;
use laravel::config::queue::ConnectionConfig;
use laravel::container::Inject;
use laravel::queue::Queueable;
use laravel::queue::{self, Attempt, Callback, Job, callback, job};
use laravel::testing::RunsJobs;
use laravel::time::ToSpan;
use serde::{Deserialize, Serialize};

use crate::queue::Records;

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

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

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

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

#[derive(Debug, thiserror::Error)]
#[error("{0} broke")]
struct Broke(String);

#[job]
impl Step {
    async fn handle(
        self,
        records: Inject<Records>,
        repaired: Inject<Repaired>,
        attempt: &Attempt,
    ) -> laravel::Result<()> {
        records.push(format!("{} on {}/{}", self.name, attempt.connection(), attempt.queue()));
        match self.then.as_deref().unwrap_or_default().split_once(':') {
            Some(("prepend", names)) => attempt.prepend_to_chain(names.split(',').map(step)),
            Some(("append", name)) => attempt.append_to_chain(step(name)),
            _ => {}
        }
        match self.then.as_deref() {
            Some("fail") if !repaired.0.load(Ordering::SeqCst) => {
                return Err(Broke(self.name).into());
            }
            Some("release") => attempt.release(30.seconds()),
            Some("delete") => attempt.delete(),
            _ => {}
        }

        Ok(())
    }

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

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

#[job(queue = "podcasts")]
impl Publish {
    async fn handle(self, records: Inject<Records>, attempt: &Attempt) {
        records.push(format!(
            "publish {} on {}/{}",
            self.0,
            attempt.connection(),
            attempt.queue()
        ));
    }
}

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

#[callback]
impl Alert {
    async fn catch(self, error: &laravel::Error, records: Inject<Records>) {
        let kind = if error.is::<Broke>() { "Broke" } else { "another error" };
        records.push(format!("alert {}: {kind}: {error}", self.0));
    }
}

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

fn trail() -> String {
    laravel::context::get::<Vec<String>>("trail")
        .unwrap_or_default()
        .join(">")
}

#[job]
impl Trail {
    async fn handle(self, records: Inject<Records>) -> laravel::Result<()> {
        let mut trail = laravel::context::get::<Vec<String>>("trail").unwrap_or_default();
        trail.push(self.0.clone());
        laravel::context::add("trail", &trail);
        records.push(trail.join(">"));
        if self.0.ends_with('!') {
            return Err(Broke(self.0).into());
        }

        Ok(())
    }

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

#[derive(Queueable)]
struct SeeTrail;

#[callback]
impl SeeTrail {
    async fn catch(self, records: Inject<Records>) {
        records.push(format!("catch sees {}", trail()));
    }
}

fn trail_chain(last: &str) -> queue::PendingChain {
    queue::chain((Trail("a".into()), Trail("b".into()), Trail(last.into()))).catch(SeeTrail)
}

const TRAIL_RECORDS: [&str; 5] = ["a", "a>b", "a>b>c!", "catch sees a>b>c!", "failed hook sees a>b>c!"];

/// Can't be encoded, since JSON object keys must be strings.
#[derive(Queueable)]
struct Unencodable(BTreeMap<(u8, u8), u8>);

#[job]
impl Unencodable {
    async fn handle(self) {}
}

fn unencodable() -> Unencodable {
    Unencodable(BTreeMap::from([((1, 2), 3)]))
}

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

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

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

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

    let start = app
        .scope(async || {
            queue::chain(["a"].into_iter().map(step))
                .then(["skip", "b"].into_iter().filter(|name| *name != "skip").map(step))
                .then(Publish("c".into()))
                .await
        })
        .await
        .unwrap();
    assert!(matches!(start, queue::ChainDispatched::Job(_)));
    assert_eq!(
        records(&app).await,
        ["a on sync/default", "b on sync/default", "publish c on sync/podcasts"]
    );

    clear(&app).await;
    app.scope(async || queue::chain(step_then("a", "delete")).then(step("b")).await)
        .await
        .unwrap();
    assert_eq!(records(&app).await, ["a on sync/default", "b on sync/default"]);

    clear(&app).await;
    app.scope(async || queue::chain(step_then("a", "release")).then(step("b")).await)
        .await
        .unwrap();
    assert_eq!(
        records(&app).await,
        ["a on sync/default"],
        "a release ends the job and the chain"
    );

    clear(&app).await;
    let error = app
        .scope(async || {
            queue::chain(step("a"))
                .then(step_then("b", "fail"))
                .then(step("c"))
                .catch(Alert("x".into()))
                .catch(Alert("y".into()))
                .await
        })
        .await
        .unwrap_err();
    assert_eq!(
        error.to_string(),
        "b broke",
        "the failed job's error returns, not a wrapped one"
    );
    assert_eq!(
        records(&app).await,
        [
            "a on sync/default",
            "b on sync/default",
            "alert x: Broke: b broke",
            "alert y: Broke: b broke",
            "failed hook for b: b broke",
        ],
        "the failed job runs its hook once and the rest of the chain doesn't run"
    );
}

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

    let error = app.scope(async || trail_chain("c!").await).await.unwrap_err();
    assert!(error.is::<Broke>(), "{error}");
    assert_eq!(records(&app).await, TRAIL_RECORDS);
}

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

    app.scope(async || {
        queue::chain((step("a"), Publish("b".into())))
            .then([step("c"), step("d")])
            .then(vec![Publish("e".into())])
            .await
    })
    .await
    .unwrap();
    assert_eq!(
        records(&app).await,
        [
            "a on sync/default",
            "publish b on sync/podcasts",
            "c on sync/default",
            "d on sync/default",
            "publish e on sync/podcasts",
        ]
    );

    let error = app
        .scope(async || queue::chain(Vec::<Step>::new()).then(Vec::<Publish>::new()).await)
        .await
        .unwrap_err();
    assert_eq!(error.to_string(), "the chain has no jobs to dispatch");

    app.scope(async || {
        let fake = queue::fake();
        queue::chain((step("a"), Publish("b".into()), step("c")))
            .catch(Alert("x".into()))
            .catch(Alert("y".into()))
            .await
            .unwrap();
        fake.assert_chained::<(Step, Publish, Step)>()
            .assert_pushed_where::<Step>(|job| job.chain_catch().names() == [Alert::NAME, Alert::NAME]);
    })
    .await;
}

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

    let error = app
        .scope(async || {
            queue::chain(step("a"))
                .then(Publish("b".into()))
                .on_connection("other")
                .on_queue("shows")
                .catch(Alert("x".into()))
                .then(step_then("c", "fail"))
                .await
        })
        .await
        .unwrap_err();
    assert_eq!(error.to_string(), "c broke");
    assert_eq!(
        records(&app).await,
        [
            "a on other/shows",
            "publish b on other/shows",
            "c on other/shows",
            "alert x: Broke: c broke",
            "failed hook for c: c broke",
        ]
    );

    clear(&app).await;
    app.scope(async || {
        queue::chain(step("a"))
            .then(Publish("b".into()))
            .on_connection("other")
            .await
    })
    .await
    .unwrap();
    assert_eq!(
        records(&app).await,
        ["a on other/default", "publish b on other/podcasts"]
    );
}

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

    app.scope(async || queue::chain(step_then("a", "prepend:x,w")).then(step("b")).await)
        .await
        .unwrap();
    app.scope(async || queue::chain(step_then("c", "append:y")).then(step("d")).await)
        .await
        .unwrap();
    assert_eq!(
        records(&app).await,
        [
            "a on sync/default",
            "x on sync/default",
            "w on sync/default",
            "b on sync/default",
            "c on sync/default",
            "d on sync/default",
            "y on sync/default",
        ]
    );

    clear(&app).await;
    app.scope(async || step_then("a", "append:b").dispatch_sync().await)
        .await
        .unwrap();
    assert_eq!(records(&app).await, ["a on sync/default", "b on sync/default"]);

    clear(&app).await;
    app.scope(async || ReleaseAfter(step_then("a", "append:b")).dispatch_sync().await)
        .await
        .unwrap();
    assert_eq!(
        records(&app).await,
        ["a on sync/default"],
        "jobs added by a released attempt don't run"
    );
}

#[derive(Queueable)]
struct ReleaseAfter(Step);

#[job]
impl ReleaseAfter {
    async fn handle(self, records: Inject<Records>, attempt: &Attempt) -> laravel::Result<()> {
        records.push(format!(
            "{} on {}/{}",
            self.0.name,
            attempt.connection(),
            attempt.queue()
        ));
        if let Some(("append", name)) = self.0.then.as_deref().and_then(|then| then.split_once(':')) {
            attempt.append_to_chain(step(name));
        }
        attempt.release(1.seconds());
        Ok(())
    }
}

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

    app.scope(async || {
        let fake = queue::fake();
        let start = queue::chain(step("a"))
            .then(step("b"))
            .then(Publish("c".into()))
            .on_queue("shows")
            .delay(10.seconds())
            .catch(Alert("x".into()))
            .await
            .unwrap();
        assert_eq!(start, queue::ChainDispatched::Job(fake.pushed::<Step>()[0].id()));
        step("lonely").dispatch().await.unwrap();

        fake.assert_pushed_times::<Step>(2)
            .assert_not_pushed::<Publish>()
            .assert_chained::<(Step, Step, Publish)>()
            .assert_pushed_without_chain::<Step>()
            .assert_pushed_where::<Step>(|job| {
                job.name == "a"
                    && job.queue() == "shows"
                    && job.delay() == Duration::from_secs(10)
                    && job.chain().len() == 2
                    && job.chain().get::<Step>(0).is_some_and(|b| b.name == "b")
                    && job.chain().get::<Publish>(0).is_none()
                    && job.chain().get::<Publish>(1).is_some_and(|c| c.0 == "c")
                    && job.chain_catch().names() == [Alert::NAME]
            });

        for (wrong, message) in [
            (
                catch_unwind(AssertUnwindSafe(|| {
                    fake.assert_chained::<(Step, Publish)>();
                })),
                "expected job `integration::queue_chains::Step` to be pushed with the chain \
                 [\"integration::queue_chains::Publish\"]",
            ),
            (
                catch_unwind(AssertUnwindSafe(|| {
                    fake.assert_pushed_without_chain::<Publish>();
                })),
                "expected job `integration::queue_chains::Publish` to be pushed without a chain",
            ),
        ] {
            let panic = wrong.unwrap_err();
            let panic = panic.downcast_ref::<String>().unwrap();
            assert!(panic.starts_with(message), "{panic}");
        }
    })
    .await;
    assert!(records(&app).await.is_empty());

    let error = app
        .scope(async || {
            let fake = queue::fake();
            let error = queue::chain(step("a"))
                .then(std::iter::once(unencodable()))
                .await
                .unwrap_err();
            fake.assert_nothing_pushed();
            error
        })
        .await;
    assert!(
        error
            .to_string()
            .starts_with("the job `integration::queue_chains::Unencodable` couldn't be encoded"),
        "{error}"
    );
}

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

    let result = app.job(step_then("a", "prepend:x")).await;
    result.assert_succeeded().assert_chained::<Step>();
    assert_eq!(result.chain().names(), [Step::NAME]);
    assert_eq!(result.chain().get::<Step>(0).unwrap().name, "x");
    assert_eq!(records(&app).await, ["a on sync/default"]);

    app.job(step_then("a", "prepend:x,y"))
        .await
        .assert_succeeded()
        .assert_chained::<(Step, Step)>();

    let wrong = catch_unwind(AssertUnwindSafe(|| {
        result.assert_chained::<Publish>();
    }));
    let message = wrong
        .unwrap_err()
        .downcast::<String>()
        .map_or_else(|_| String::new(), |message| *message);
    assert!(
        message.contains("expected job `integration::queue_chains::Step` to chain")
            && message.contains("integration::queue_chains::Publish"),
        "{message}"
    );

    app.job(step("b")).await.assert_succeeded();
    assert!(app.job(step("b")).await.chain().is_empty());

    let result = app.job(AddsUnencodable).await;
    result.assert_failed();
    assert!(result.error().unwrap().to_string().contains("couldn't be encoded"));
}

#[derive(Queueable)]
struct AddsUnencodable;

#[job]
impl AddsUnencodable {
    async fn handle(self, attempt: &Attempt) {
        attempt.append_to_chain(unencodable());
    }
}

#[cfg(feature = "database-sqlite")]
mod database {
    use laravel::config::database::ConnectionConfig as DatabaseConnection;
    use laravel::config::queue::DatabaseQueue;
    use laravel::db;
    use laravel::testing::{MakesConsoleRequests, TestCommandResult};

    use super::*;
    use crate::queue::database::{create_failed_table, create_table};

    async fn application(directory: &crate::support::TempDir, default: &'static str) -> Application {
        let url = format!("sqlite://{}?mode=rwc", directory.join("queue.sqlite").display());
        let app = configure(default)
            .with_config(move |config, _| {
                config.database.default = "primary".into();
                config
                    .database
                    .connections
                    .insert("primary".into(), DatabaseConnection::new(url));
                config
                    .queue
                    .add_connection("broken", DatabaseQueue::new().table("missing_jobs"));
            })
            .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
        })
        .await
        .unwrap();

        app
    }

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

    async fn count(app: &Application, table: &str) -> i64 {
        app.scope(async || {
            db::default_connection()?
                .query(db::sqlx::AssertSqlSafe(format!("SELECT COUNT(*) FROM {table}")))
                .scalar::<i64>()
                .await
        })
        .await
        .unwrap()
        .unwrap()
    }

    #[tokio::test]
    async fn the_worker_runs_a_chain_in_order_and_retrying_a_failed_job_resumes_it() {
        let directory = crate::support::TempDir::new("queue-chains-worker");
        let app = application(&directory, "database").await;

        app.scope(async || {
            queue::chain(step_then("a", "append:z"))
                .then(Publish("b".into()))
                .then(step("c"))
                .await
        })
        .await
        .unwrap();
        assert_eq!(count(&app, "jobs").await, 1, "only the first job is queued");
        let output = work(&app, "database").await;
        output.assert_successful();
        assert!(
            !output.error_output().contains(" failed  "),
            "{}",
            output.error_output()
        );
        assert_eq!(
            records(&app).await,
            [
                "a on database/default",
                "publish b on database/podcasts",
                "c on database/default",
                "z on database/default",
            ]
        );

        clear(&app).await;
        app.scope(async || {
            queue::chain(step("a"))
                .then(step_then("b", "fail"))
                .then(step("c"))
                .catch(Alert("x".into()))
                .await
        })
        .await
        .unwrap();
        work(&app, "database")
            .await
            .assert_successful()
            .assert_error_output_contains(" failed  ");
        assert_eq!(
            records(&app).await,
            [
                "a on database/default",
                "b on database/default",
                "alert x: Broke: b broke",
                "failed hook for b: b broke",
            ]
        );
        assert_eq!(count(&app, "failed_jobs").await, 1);

        clear(&app).await;
        app.resolve::<Repaired>().await.0.store(true, Ordering::SeqCst);
        app.command("queue:retry all").await.assert_successful();
        work(&app, "database").await.assert_successful();
        assert_eq!(
            records(&app).await,
            ["b on database/default", "c on database/default"],
            "the retried job carries the rest of its chain"
        );
        assert_eq!(count(&app, "jobs").await, 0);
        assert_eq!(count(&app, "failed_jobs").await, 0);
    }

    #[tokio::test]
    async fn the_worker_passes_context_values_down_the_chain() {
        let directory = crate::support::TempDir::new("queue-chains-context");
        let app = application(&directory, "database").await;

        app.scope(async || trail_chain("c!").await).await.unwrap();
        work(&app, "database").await.assert_successful();
        assert_eq!(records(&app).await, TRAIL_RECORDS);
    }

    #[tokio::test]
    async fn a_job_whose_next_job_cant_be_dispatched_fails_for_good() {
        let directory = crate::support::TempDir::new("queue-chains-broken");
        let app = application(&directory, "broken").await;

        let error = app
            .scope(async || queue::chain(step("a")).then(step("b")).await)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("missing_jobs"), "{error}");
        assert!(records(&app).await.is_empty());

        app.scope(async || step_then("a", "append:b").dispatch().on_connection("database").await)
            .await
            .unwrap();
        work(&app, "database")
            .await
            .assert_successful()
            .assert_error_output_contains(" failed  ");
        let records = records(&app).await;
        assert_eq!(records.len(), 2, "{records:?}");
        assert_eq!(records[0], "a on database/default");
        assert!(records[1].starts_with("failed hook for a: "), "{records:?}");
        assert_eq!(count(&app, "failed_jobs").await, 1);
        assert_eq!(count(&app, "jobs").await, 0);
    }

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

        let during = app
            .scope(async || {
                let connection = db::default_connection().unwrap();
                let rolled_back = connection
                    .transaction(async |_| {
                        queue::chain(step("never")).then(step("ever")).await?;
                        Err::<(), _>(laravel::abort_with(500, "rolled back"))
                    })
                    .await;
                assert!(rolled_back.is_err());
                connection
                    .transaction(async |tx| {
                        queue::chain(step("a")).then(step("b")).await?;
                        tx.query("SELECT COUNT(*) FROM jobs").scalar::<i64>().await
                    })
                    .await
                    .unwrap()
            })
            .await;

        assert_eq!(during, Some(0));
        assert_eq!(count(&app, "jobs").await, 1);
        work(&app, "database").await.assert_successful();
        assert_eq!(records(&app).await, ["a on database/default", "b on database/default"]);
    }
}