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
use std::collections::BTreeMap;
use std::time::{Duration, Instant};

use laravel::Application;
use laravel::config::Env;
use laravel::config::queue::{FailedJobs, RedisQueue};
use laravel::config::redis::ConnectionConfig;
use laravel::container::Inject;
use laravel::foundation::ApplicationBuilder;
use laravel::queue::Queueable;
use laravel::queue::{Attempt, QueueSizes, job};
use laravel::redis::{RedisManager, client};
use laravel::testing::{MakesConsoleRequests, TestCommandResult};
use laravel::time::{Timestamp, ToSpan};

use crate::queue::Records;
use crate::redis::{key, server};

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

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

        Ok(())
    }

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

#[derive(Queueable)]
struct ReleaseOnce;

#[job(name = "redis.release_once", tries = 2)]
impl ReleaseOnce {
    async fn handle(self, records: Inject<Records>, attempt: &Attempt) {
        records.push(format!("release ran as attempt {}", attempt.number()));
        if attempt.number() == 1 {
            attempt.release(30.seconds());
        }
    }
}

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

#[job(name = "redis.note")]
impl Note {
    async fn handle(self, records: Inject<Records>, attempt: &Attempt) {
        records.push(format!("{} as attempt {}", self.0, attempt.number()));
    }
}

#[derive(Queueable)]
struct Hold;

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

#[job(name = "redis.hold", tries = 2, timeout = 60.seconds())]
impl Hold {
    async fn handle(self, gate: Inject<Gate>, records: Inject<Records>, attempt: &Attempt) {
        records.push(format!("hold ran as attempt {}", attempt.number()));
        let _ = gate.0.subscribe().wait_for(|open| *open >= attempt.number()).await;
    }
}

const NOW: i64 = 1_800_000_000;
const NOW_MS: i64 = NOW * 1000;

fn configure(block_for: Option<Duration>) -> (ApplicationBuilder, String) {
    let (url, queue) = (server(), key("jobs"));
    let mut connection = RedisQueue::new().queue(&queue);
    connection.block_for = block_for.map(Into::into);
    let builder = Application::configure()
        .replace_env(Env::default())
        .with_config(move |config, _| {
            config
                .redis
                .add_connection("default", ConnectionConfig::new(url).database(14));
            config.queue.default = "redis".into();
            config.queue.failed = FailedJobs::Discard;
            config.queue.add_connection("redis", connection);
        })
        .with_services(|services| {
            services.instance(Records::default());
            services.instance(Gate::default());
        });

    (builder, queue)
}

fn application(block_for: Option<Duration>) -> (Application, String) {
    let (builder, queue) = configure(block_for);
    let app = builder.create();
    app.travel_to(Timestamp::from_second(NOW).unwrap());

    (app, queue)
}

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

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

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

#[derive(Debug, PartialEq, Eq)]
struct State {
    available: Vec<String>,
    delayed: Vec<(String, i64)>,
    reserved: Vec<(String, i64)>,
    attempts: BTreeMap<String, u32>,
    payloads: usize,
    notify: usize,
}

async fn state(app: &Application, queue: &str) -> State {
    let mut redis = app.resolve::<RedisManager>().await.default_connection().unwrap();
    let key = |suffix: &str| format!("queues:{{{queue}}}{suffix}");
    let stored: BTreeMap<String, String> = client::cmd("HGETALL")
        .arg(key(":payloads"))
        .query_async(&mut redis)
        .await
        .unwrap();
    let names: BTreeMap<String, String> = stored
        .iter()
        .map(|(id, payload)| {
            assert!(id.len() == 36 && id.as_bytes()[14] == b'7', "{id} is a UUID v7");
            (id.clone(), name(payload))
        })
        .collect();
    let name_of = |id: String| names.get(&id).cloned().unwrap_or_else(|| format!("missing {id}"));
    let available: Vec<String> = client::cmd("LRANGE")
        .arg(key(""))
        .arg(0)
        .arg(-1)
        .query_async(&mut redis)
        .await
        .unwrap();
    let mut scored = async |suffix: &str| -> Vec<(String, i64)> {
        client::cmd("ZRANGE")
            .arg(key(suffix))
            .arg(0)
            .arg(-1)
            .arg("WITHSCORES")
            .query_async(&mut redis)
            .await
            .unwrap()
    };
    let delayed = scored(":delayed").await;
    let reserved = scored(":reserved").await;
    let attempts: BTreeMap<String, u32> = client::cmd("HGETALL")
        .arg(key(":attempts"))
        .query_async(&mut redis)
        .await
        .unwrap();
    let notify = client::cmd("LLEN")
        .arg(key(":notify"))
        .query_async(&mut redis)
        .await
        .unwrap();

    let scored_by_name = |jobs: Vec<(String, i64)>| jobs.into_iter().map(|(id, at)| (name_of(id), at)).collect();
    State {
        available: available.into_iter().map(name_of).collect(),
        delayed: scored_by_name(delayed),
        reserved: scored_by_name(reserved),
        attempts: attempts.into_iter().map(|(id, count)| (name_of(id), count)).collect(),
        payloads: stored.len(),
        notify,
    }
}

fn name(payload: &str) -> String {
    let payload: serde_json::Value = serde_json::from_str(payload).unwrap();
    match payload["job"].as_str().unwrap() {
        "redis.flaky" => format!("flaky {}", payload["data"]["id"]),
        "redis.note" => payload["data"][0].as_str().unwrap().to_owned(),
        "redis.release_once" => "release".to_owned(),
        "redis.hold" => "hold".to_owned(),
        other => other.to_owned(),
    }
}

fn named<const N: usize>(names: [&str; N]) -> Vec<String> {
    names.map(str::to_owned).to_vec()
}

fn scored<const N: usize>(jobs: [(&str, i64); N]) -> Vec<(String, i64)> {
    jobs.map(|(name, at)| (name.to_owned(), at)).to_vec()
}

fn attempts<const N: usize>(jobs: [(&str, u32); N]) -> BTreeMap<String, u32> {
    jobs.into_iter().map(|(name, count)| (name.to_owned(), count)).collect()
}

fn empty() -> State {
    State {
        available: Vec::new(),
        delayed: Vec::new(),
        reserved: Vec::new(),
        attempts: BTreeMap::new(),
        payloads: 0,
        notify: 0,
    }
}

async fn wait_for(app: &Application, queue: &str, expected: impl Fn(&State) -> bool) -> State {
    let waited = async {
        loop {
            let state = state(app, queue).await;
            if expected(&state) {
                return state;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    };

    tokio::time::timeout(Duration::from_secs(20), waited)
        .await
        .expect("the queue should reach the expected state")
}

#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn failed_attempts_wait_out_their_backoff_then_fail_for_good() {
    let (app, queue) = application(None);
    dispatch(&app, Flaky { id: 1, failures: 2 }).await;
    dispatch(&app, Flaky { id: 2, failures: 5 }).await;
    assert_eq!(
        state(&app, &queue).await,
        State {
            available: named(["flaky 1", "flaky 2"]),
            payloads: 2,
            notify: 2,
            ..empty()
        }
    );

    let result = work(&app, "").await;
    result.assert_successful();
    assert_eq!(
        result.error_output().matches(" retrying  ").count(),
        2,
        "{}",
        result.error_output()
    );
    assert_eq!(
        state(&app, &queue).await,
        State {
            delayed: scored([("flaky 1", NOW_MS + 10_000), ("flaky 2", NOW_MS + 10_000)]),
            attempts: attempts([("flaky 1", 1), ("flaky 2", 1)]),
            payloads: 2,
            ..empty()
        },
        "a failure waits out the first backoff"
    );

    app.travel(10.seconds());
    work(&app, "").await.assert_successful();
    assert_eq!(
        state(&app, &queue).await.delayed,
        scored([("flaky 1", NOW_MS + 70_000), ("flaky 2", NOW_MS + 70_000)]),
        "the second failure waits out the second backoff"
    );

    app.travel(1.minutes());
    let result = work(&app, "").await;
    assert!(
        crate::support::outcomes(result.error_output()).contains(&"done"),
        "{}",
        result.error_output()
    );
    assert!(result.error_output().contains(" failed  "), "{}", result.error_output());
    assert_eq!(
        records(&app).await,
        [
            "flaky 1 ran as attempt 1",
            "flaky 2 ran as attempt 1",
            "flaky 1 ran as attempt 2",
            "flaky 2 ran as attempt 2",
            "flaky 1 ran as attempt 3",
            "flaky 2 ran as attempt 3",
            "failed hook for flaky 2: flaky 2 broke",
        ]
    );
    assert_eq!(state(&app, &queue).await, empty());
}

#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn released_jobs_go_to_the_back_of_the_queue_and_delayed_jobs_wait() {
    let (app, queue) = application(None);
    dispatch(&app, ReleaseOnce).await;
    dispatch(&app, Note("first".into())).await;
    app.scope(async || Note("delayed".into()).dispatch().delay(5.minutes()).await)
        .await
        .unwrap();

    work(&app, "").await.assert_error_output_contains(" released  ");
    assert_eq!(records(&app).await, ["release ran as attempt 1", "first as attempt 1"]);
    assert_eq!(
        state(&app, &queue).await,
        State {
            delayed: scored([("release", NOW_MS + 30_000), ("delayed", NOW_MS + 300_000)]),
            attempts: attempts([("release", 1)]),
            payloads: 2,
            ..empty()
        },
        "the release waits its delay, keeping its attempt"
    );

    dispatch(&app, Note("second".into())).await;
    app.travel(30.seconds());
    assert_eq!(
        crate::support::outcomes(work(&app, "--max-jobs=1").await.error_output()),
        ["done"]
    );
    assert_eq!(
        state(&app, &queue).await.available,
        ["release"],
        "the due job joined behind the second note"
    );
    work(&app, "").await.assert_successful();
    assert_eq!(
        records(&app).await[2..],
        ["second as attempt 1", "release ran as attempt 2"]
    );

    app.travel(5.minutes());
    work(&app, "").await.assert_successful();
    assert_eq!(records(&app).await[4..], ["delayed as attempt 1"]);
    assert_eq!(state(&app, &queue).await, empty());

    dispatch(&app, Note("cleared".into())).await;
    app.scope(async || Note("cleared later".into()).dispatch().delay(1.minutes()).await)
        .await
        .unwrap();
    app.command("queue:clear")
        .await
        .assert_successful()
        .assert_error_output_contains("2 jobs cleared from `redis:");
    assert_eq!(state(&app, &queue).await, empty());
    dispatch(&app, Note("after clearing".into())).await;
    assert_eq!(state(&app, &queue).await.available, ["after clearing"]);
}

#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn a_lapsed_reservation_goes_to_another_worker_and_the_first_leaves_the_job_alone() {
    let (app, queue) = application(None);
    dispatch(&app, Hold).await;
    let gate = app.resolve::<Gate>().await;
    let (first_done, first_finished) = tokio::sync::oneshot::channel();

    let first = async {
        let result = work(&app, "").await;
        first_done.send(()).unwrap();
        result
    };
    let others = async {
        let reserved = wait_for(&app, &queue, |state| !state.reserved.is_empty()).await;
        assert_eq!(reserved.reserved, scored([("hold", NOW_MS + 60_000)]));
        app.travel(45.seconds());
        wait_for(&app, &queue, |state| {
            state.reserved == scored([("hold", NOW_MS + 105_000)])
        })
        .await;
        app.travel(30.seconds());
        work(&app, "").await.assert_successful();
        assert_eq!(
            records(&app).await,
            ["hold ran as attempt 1"],
            "no other worker took it"
        );

        app.travel(1.minutes());
        let second = work(&app, "");
        let settle = async {
            let taken = wait_for(&app, &queue, |state| state.attempts.get("hold") == Some(&2)).await;
            assert_eq!(taken.reserved, scored([("hold", NOW_MS + 195_000)]));

            gate.0.send_replace(1);
            first_finished.await.unwrap();
            assert_eq!(
                state(&app, &queue).await,
                State {
                    reserved: scored([("hold", NOW_MS + 195_000)]),
                    attempts: attempts([("hold", 2)]),
                    payloads: 1,
                    ..empty()
                }
            );
            gate.0.send_replace(2);
        };
        let (second, ()) = tokio::join!(second, settle);
        second.assert_successful();
        assert!(
            crate::support::outcomes(second.error_output()).contains(&"done"),
            "{}",
            second.error_output()
        );
    };

    let (first, ()) = tokio::join!(first, others);
    first.assert_successful();
    assert_eq!(records(&app).await, ["hold ran as attempt 1", "hold ran as attempt 2"]);
    assert_eq!(state(&app, &queue).await, empty());
}

#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn workers_racing_for_jobs_each_take_different_ones() {
    let (app, queue) = application(Some(Duration::from_millis(200)));
    for note in 0..40 {
        dispatch(&app, Note(format!("note {note:02}"))).await;
    }

    let (first, second, third) = tokio::join!(
        work(&app, "--concurrency=4"),
        work(&app, "--concurrency=4"),
        work(&app, "--concurrency=4"),
    );
    first.assert_successful();
    second.assert_successful();
    third.assert_successful();
    let mut notes = records(&app).await;
    notes.sort();
    assert_eq!(
        notes,
        (0..40)
            .map(|note| format!("note {note:02} as attempt 1"))
            .collect::<Vec<_>>()
    );
    assert_eq!(state(&app, &queue).await, empty());
}

#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn a_waiting_worker_takes_a_job_once_it_is_pushed_and_stopping_it_loses_nothing() {
    let (app, queue) = application(Some(Duration::from_secs(10)));

    let waiting = tokio::time::timeout(Duration::from_millis(500), app.command("queue:work")).await;
    assert!(waiting.is_err(), "the worker was still waiting");

    tokio::time::sleep(Duration::from_millis(200)).await;
    dispatch(&app, Note("kept".into())).await;
    assert_eq!(
        state(&app, &queue).await,
        State {
            available: named(["kept"]),
            payloads: 1,
            notify: 1,
            ..empty()
        }
    );
    work(&app, "--max-jobs=1").await.assert_successful();
    assert_eq!(records(&app).await, ["kept as attempt 1"]);

    let started = Instant::now();
    let worker = app.command("queue:work --sleep=30 --max-jobs=1");
    let push = async {
        tokio::time::sleep(Duration::from_millis(500)).await;
        dispatch(&app, Note("woken".into())).await;
    };
    let (result, ()) = tokio::join!(worker, push);
    result.assert_successful();
    assert!(started.elapsed() < Duration::from_secs(3), "{:?}", started.elapsed());
    assert_eq!(records(&app).await[1..], ["woken as attempt 1"]);
    assert_eq!(state(&app, &queue).await, empty());

    let worker = app.command("queue:work --sleep=30 --max-jobs=1");
    let push = async {
        tokio::time::sleep(Duration::from_millis(500)).await;
        tokio::join!(
            dispatch(&app, Note("first".into())),
            dispatch(&app, Note("second".into()))
        );
    };
    let (result, _) = tokio::join!(worker, push);
    result.assert_successful();
    let after = state(&app, &queue).await;
    assert_eq!((after.available.len(), after.notify), (1, 1), "{after:?}");
}

#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn a_waiting_worker_whose_job_was_taken_leaves_no_stale_notify_token() {
    let (app, queue) = application(Some(Duration::from_secs(10)));
    let mut redis = app.resolve::<RedisManager>().await.default_connection().unwrap();

    // Wake a blocked worker on an empty queue, as when another worker stole the job...
    let worker = app.command("queue:work --stop-when-empty");
    let wake = async {
        tokio::time::sleep(Duration::from_millis(300)).await;
        let () = client::cmd("RPUSH")
            .arg(format!("queues:{{{queue}}}:notify"))
            .arg(1)
            .query_async(&mut redis)
            .await
            .unwrap();
    };
    let (result, ()) = tokio::join!(worker, wake);
    result.assert_successful();
    assert_eq!(state(&app, &queue).await, empty());

    // A stale token already on `notify` is cleared on the next reserve, so waiting still blocks...
    let () = client::cmd("RPUSH")
        .arg(format!("queues:{{{queue}}}:notify"))
        .arg(1)
        .query_async(&mut redis)
        .await
        .unwrap();
    let waiting = tokio::time::timeout(Duration::from_millis(500), app.command("queue:work --stop-when-empty")).await;
    assert!(waiting.is_err(), "the worker should keep blocking in BLPOP");
    assert_eq!(state(&app, &queue).await, empty());
}

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

#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn sizes_count_due_jobs_and_lapsed_reservations_as_pending() {
    let (app, queue) = application(None);
    dispatch(&app, Note("first".into())).await;
    app.scope(async || Note("later".into()).dispatch().delay(30.seconds()).await)
        .await
        .unwrap();
    let mut redis = app.resolve::<RedisManager>().await.default_connection().unwrap();
    let () = client::cmd("ZADD")
        .arg(format!("queues:{{{queue}}}:reserved"))
        .arg(NOW_MS + 60_000)
        .arg("running")
        .arg(NOW_MS - 1)
        .arg("abandoned")
        .query_async(&mut redis)
        .await
        .unwrap();

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

#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn reserving_moves_at_most_a_hundred_due_jobs_per_script() {
    let (app, queue) = application(None);
    let notes: Vec<_> = (0..150).map(|note| format!("note {note:03}")).collect();
    app.scope(async || {
        for note in &notes {
            Note(note.clone()).dispatch().delay(30.seconds()).await?;
        }
        Ok::<_, laravel::Error>(())
    })
    .await
    .unwrap();
    app.travel(30.seconds());

    work(&app, "--max-jobs=1").await.assert_successful();
    assert_eq!(records(&app).await.len(), 1);
    let after = state(&app, &queue).await;
    assert_eq!((after.available.len(), after.delayed.len(), after.notify), (99, 50, 99));

    work(&app, "").await.assert_successful();
    assert_eq!(records(&app).await.len(), 150);
    assert_eq!(state(&app, &queue).await, empty());
}

#[cfg(feature = "database-sqlite")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_URL pointing to a disposable Redis server"]
async fn batches_push_their_jobs_in_order_a_thousand_per_script() {
    use laravel::config::database::ConnectionConfig as DatabaseConnection;
    use laravel::db;

    let directory = crate::support::TempDir::new("queue-redis-bulk");
    let url = format!("sqlite://{}?mode=rwc", directory.join("batches.sqlite").display());
    let (builder, queue) = configure(None);
    let app = builder
        .with_config(move |config, _| {
            config.database.default = "primary".into();
            config
                .database
                .connections
                .insert("primary".into(), DatabaseConnection::new(url));
        })
        .create();
    app.scope(async || {
        let connection = db::default_connection()?;
        for sql in crate::queue_batches::create_batch_tables(connection.driver()) {
            connection.query(sql).statement().await?;
        }
        Ok::<_, laravel::Error>(())
    })
    .await
    .unwrap();

    let notes: Vec<_> = (0..1100).map(|note| format!("note {note:04}")).collect();
    let id = app
        .scope(async || laravel::queue::batch(notes.iter().cloned().map(Note).collect::<Vec<_>>()).await)
        .await
        .unwrap();
    let state = state(&app, &queue).await;
    assert_eq!(state.available, notes);
    assert_eq!((state.payloads, state.notify), (1100, 1100));

    work(&app, "").await.assert_successful();
    let ran: Vec<_> = notes.iter().map(|note| format!("{note} as attempt 1")).collect();
    assert_eq!(records(&app).await, ran);
    let batch = app
        .scope(async || laravel::queue::find_batch(id).await)
        .await
        .unwrap()
        .unwrap();
    assert!(batch.is_finished());
}

#[tokio::test]
#[ignore = "requires LARAVEL_TEST_REDIS_CLUSTER_URL pointing to a node of a disposable Redis Cluster"]
async fn each_queue_keeps_its_jobs_on_one_node_of_a_cluster() {
    let node = std::env::var("LARAVEL_TEST_REDIS_CLUSTER_URL")
        .expect("LARAVEL_TEST_REDIS_CLUSTER_URL points to a cluster node");
    let queues: Vec<String> = (0..4).map(|_| key("cluster")).collect();
    let app = Application::configure()
        .replace_env(Env::default())
        .with_config(move |config, _| {
            config
                .redis
                .add_connection("default", ConnectionConfig::cluster([node]));
            config.queue.default = "redis".into();
            config.queue.failed = FailedJobs::Discard;
            config.queue.add_connection("redis", RedisQueue::new());
        })
        .with_services(|services| {
            services.instance(Records::default());
        })
        .create();
    for queue in &queues {
        app.scope(async || Note(queue.clone()).dispatch().on_queue(queue).await)
            .await
            .unwrap();
    }
    app.scope(async || ReleaseOnce.dispatch().on_queue(&queues[0]).await)
        .await
        .unwrap();

    let result = work(&app, &format!("--queue={}", queues.join(","))).await;
    result.assert_successful().assert_error_output_contains(" released  ");
    let notes: Vec<_> = records(&app)
        .await
        .into_iter()
        .filter(|record| record.starts_with("laravel-test"))
        .collect();
    let expected: Vec<_> = queues.iter().map(|queue| format!("{queue} as attempt 1")).collect();
    assert_eq!(notes, expected, "each queue's job ran, in the queues' order");
    app.command(&format!("queue:clear --queue={}", queues[0]))
        .await
        .assert_successful()
        .assert_error_output_contains("1 job cleared from `redis:");
}