laravel-rust-queue 0.1.0

Internal crate of Laravel for Rust: jobs, the queue drivers, the worker, batches, and chains. Depend on `laravel-rust` instead
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
use super::QueueManagerInternals as _;
use std::any::type_name;
use std::collections::HashSet;
use std::fmt;
use std::ops::Deref;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;

use serde_json::Value;

use super::batch::{BatchId, BatchSpec};
use super::callback::{Callback, EncodedCallback};
use super::chain::Link;
use super::payload::Payload;
use super::queueable::ModelRows;
use super::{Job, JobId, QueueManager, Queueable};
use crate::context::{Context, Internals};
use crate::testing::fake_stack::{FakeGuard, FakeStack};
use crate::time::ExactDuration;

/// Record this application's dispatched jobs without pushing or running them.
///
/// Keep the returned handle alive while you exercise the application. Dropping the handle
/// removes this fake, and any enclosing fake becomes active again. The newest fake controls
/// dispatch, even when it fakes only certain jobs. HTTP requests, console commands, and
/// application scopes share the same fake, but separate applications never share one.
///
/// The fake still encodes each recorded job. Assertions that read a job, such as
/// [`assert_pushed_where`](QueueFake::assert_pushed_where), decode the job as a worker would, so
/// a job that the queue can't read back fails them. These assertions see the job's models as you
/// dispatched them, without their relationships and without a database query.
///
/// # Panics
///
/// Panics outside an application context.
///
/// ```
/// use laravel::{Application, queue};
///
/// #[derive(laravel::queue::Queueable)]
/// struct ProcessPodcast {
///     podcast_id: i64,
/// }
///
/// #[queue::job]
/// impl ProcessPodcast {
///     async fn handle(self) {}
/// }
///
/// let app = Application::configure()
///     .replace_env(laravel::config::Env::default())
///     .create();
///
/// # laravel::testing::__run(
/// app.scope(async || {
///     let queue = queue::fake();
///
///     ProcessPodcast { podcast_id: 42 }
///         .dispatch()
///         .on_queue("podcasts")
///         .await
///         .unwrap();
///
///     queue.assert_pushed::<ProcessPodcast>();
///     queue.assert_pushed_where::<ProcessPodcast>(|job| {
///         job.podcast_id == 42 && job.queue() == "podcasts"
///     });
/// })
/// # );
/// ```
#[track_caller]
pub fn fake() -> QueueFake {
    let manager = QueueManager::of(Context::expect("laravel::queue::fake()").services());

    QueueFake {
        recording: manager.fakes.push(),
    }
}

/// An active queue fake and its typed assertions.
///
/// The handle isn't cloneable, because its lifetime decides when the fake is active.
#[must_use = "bind the queue fake to a name, as in `let queue = queue::fake();`, because dropping it restores dispatch, and `let _ = ..` drops it straight away"]
pub struct QueueFake {
    recording: FakeGuard<Recording>,
}

impl QueueFake {
    /// Fake only the selected job types.
    ///
    /// Jobs of other types are pushed normally, and the fake doesn't record them. The first call
    /// switches the fake from all jobs to a selection, and each later call adds a type. Configure
    /// the selection before you dispatch jobs.
    #[must_use = "keep the selected queue fake alive while exercising the application"]
    pub fn only<J: Job>(self) -> Self {
        self.recording
            .state()
            .only
            .get_or_insert_with(HashSet::new)
            .insert(J::NAME);
        self
    }

    /// Fake every job type except this one.
    ///
    /// Jobs of the excluded types are pushed normally, and the fake doesn't record them. Each later
    /// call excludes another type. Configure the selection before you dispatch jobs.
    #[must_use = "keep the selected queue fake alive while exercising the application"]
    pub fn except<J: Job>(self) -> Self {
        self.recording.state().except.insert(J::NAME);
        self
    }

    /// Return the recorded jobs of this type in dispatch order, each decoded as a worker would read
    /// it.
    ///
    /// # Panics
    ///
    /// Panics when a recorded job's payload doesn't decode.
    pub fn pushed<J: Job>(&self) -> Vec<Pushed<J>> {
        let records: Vec<Record> = self
            .recording
            .state()
            .records
            .iter()
            .filter(|record| record.payload.job == J::NAME)
            .cloned()
            .collect();

        // Check outside the lock, since deserialization may reenter the application...
        records
            .into_iter()
            .map(|record| Pushed {
                job: dispatched::<J>(&record.payload.dispatched, record.payload.data, "job"),
                id: record.payload.id,
                connection: record.connection,
                queue: record.queue,
                delay: record.delay,
                chain: JobList(record.payload.chain.jobs),
                catch: CallbackList(record.payload.chain.catch),
            })
            .collect()
    }

    /// Assert that at least one job of this type was dispatched.
    ///
    /// # Panics
    ///
    /// Panics when no job of this type was recorded. The message names the expected job and the
    /// recorded jobs.
    #[track_caller]
    pub fn assert_pushed<J: Job>(&self) -> &Self {
        assert!(
            self.count::<J>() > 0,
            "expected job `{}` to be pushed at least once; recorded jobs: {:?}",
            type_name::<J>(),
            self.recorded_names(),
        );
        self
    }

    /// Assert that at least one job of this type satisfies the predicate.
    ///
    /// The predicate receives a [`Pushed`], which dereferences to the job and also reports the job's
    /// queue, connection, and delay.
    ///
    /// # Panics
    ///
    /// Panics when no matching job was recorded, or if the predicate panics.
    #[track_caller]
    pub fn assert_pushed_where<J: Job>(&self, predicate: impl Fn(&Pushed<J>) -> bool) -> &Self {
        let jobs = self.pushed::<J>();
        assert!(
            jobs.iter().any(&predicate),
            "expected job `{}` matching the predicate; recorded {} job(s) of this type",
            type_name::<J>(),
            jobs.len(),
        );
        self
    }

    /// Assert that jobs of this type were dispatched exactly `expected` times, which may be zero.
    ///
    /// # Panics
    ///
    /// Panics when the count differs.
    #[track_caller]
    pub fn assert_pushed_times<J: Job>(&self, expected: usize) -> &Self {
        let actual = self.count::<J>();
        assert_eq!(
            actual,
            expected,
            "expected job `{}` to be pushed {expected} time(s), but recorded {actual}",
            type_name::<J>(),
        );
        self
    }

    /// Assert that no job of this type was dispatched.
    ///
    /// # Panics
    ///
    /// Panics when one or more jobs of this type were recorded.
    #[track_caller]
    pub fn assert_not_pushed<J: Job>(&self) -> &Self {
        self.assert_pushed_times::<J>(0)
    }

    /// Assert that no job of this type satisfies the predicate.
    ///
    /// Other jobs of the same type may still have been dispatched.
    ///
    /// # Panics
    ///
    /// Panics when a matching job was recorded, or if the predicate panics.
    #[track_caller]
    pub fn assert_not_pushed_where<J: Job>(&self, predicate: impl Fn(&Pushed<J>) -> bool) -> &Self {
        let jobs = self.pushed::<J>();
        let matching = jobs.iter().filter(|job| predicate(job)).count();
        assert!(
            matching == 0,
            "unexpected job `{}` matching the predicate: {matching} of {} recorded job(s) of this type match",
            type_name::<J>(),
            jobs.len(),
        );
        self
    }

    /// Assert that a chain of these job types was dispatched.
    ///
    /// The assertion looks for a job of the first type whose chain holds the other types in order,
    /// as in `assert_chained::<(ShipOrder, RecordShipment)>()`. To check the jobs' data, read
    /// [`Pushed::chain`] in [`assert_pushed_where`](Self::assert_pushed_where).
    ///
    /// # Panics
    ///
    /// Panics when no job of the first type was recorded with that chain. The message names the
    /// recorded chains.
    #[track_caller]
    pub fn assert_chained<C: JobTypes>(&self) -> &Self {
        let expected = C::names();
        let (first, rest) = expected.split_first().expect("a tuple of job types has at least one");
        let chains = self.chains(first);
        assert!(
            chains.iter().any(|chain| chain == rest),
            "expected job `{first}` to be pushed with the chain {rest:?}; recorded chains of `{first}`: {chains:?}",
        );
        self
    }

    /// Assert that a job of this type was dispatched without a chain.
    ///
    /// # Panics
    ///
    /// Panics when every recorded job of this type has a chain, or when no job of this type was
    /// recorded.
    #[track_caller]
    pub fn assert_pushed_without_chain<J: Job>(&self) -> &Self {
        let chains = self.chains(J::NAME);
        assert!(
            chains.iter().any(Vec::is_empty),
            "expected job `{}` to be pushed without a chain; recorded chains of `{}`: {chains:?}",
            type_name::<J>(),
            J::NAME,
        );
        self
    }

    fn chains(&self, name: &str) -> Vec<Vec<String>> {
        self.recording
            .state()
            .records
            .iter()
            .filter(|record| record.payload.job == name)
            .map(|record| {
                record
                    .payload
                    .chain
                    .jobs
                    .iter()
                    .map(|link| link.name().to_owned())
                    .collect()
            })
            .collect()
    }

    /// Return the batches dispatched while this fake was active, in dispatch order.
    ///
    /// The fake records every batch, whatever [`only`](Self::only) and [`except`](Self::except)
    /// select, and pushes none of the batches' jobs.
    pub fn batches(&self) -> Vec<PushedBatch> {
        self.recording
            .state()
            .batches
            .iter()
            .map(|batch| PushedBatch(batch.spec.clone()))
            .collect()
    }

    /// Assert that a batch satisfying the predicate was dispatched.
    ///
    /// The predicate receives a [`PushedBatch`], which reports the batch's jobs, name, and options.
    ///
    /// # Panics
    ///
    /// Panics when no matching batch was recorded, or if the predicate panics.
    #[track_caller]
    pub fn assert_batched(&self, predicate: impl Fn(&PushedBatch) -> bool) -> &Self {
        let batches = self.batches();
        assert!(
            batches.iter().any(predicate),
            "expected a batch matching the predicate; recorded {} batch(es)",
            batches.len(),
        );
        self
    }

    /// Assert that exactly `expected` batches were dispatched, which may be zero.
    ///
    /// # Panics
    ///
    /// Panics when the count differs.
    #[track_caller]
    pub fn assert_batch_count(&self, expected: usize) -> &Self {
        let actual = self.recording.state().batches.len();
        assert_eq!(
            actual, expected,
            "expected {expected} batch(es) to be dispatched, but recorded {actual}"
        );
        self
    }

    /// Assert that no batch was dispatched.
    ///
    /// # Panics
    ///
    /// Panics when a batch was recorded. The message names the jobs of each recorded batch.
    #[track_caller]
    pub fn assert_nothing_batched(&self) -> &Self {
        let batches: Vec<Vec<String>> = self
            .batches()
            .iter()
            .map(|batch| batch.jobs().names().into_iter().map(str::to_owned).collect())
            .collect();
        assert!(
            batches.is_empty(),
            "expected no batches to be dispatched; recorded batches of: {batches:?}"
        );
        self
    }

    /// Assert that this fake recorded no jobs.
    ///
    /// A fake created with [`only`](Self::only) or [`except`](Self::except) checks only the job types
    /// it fakes.
    ///
    /// # Panics
    ///
    /// Panics when any job was recorded, naming the recorded jobs.
    #[track_caller]
    pub fn assert_nothing_pushed(&self) -> &Self {
        let names = self.recorded_names();
        assert!(
            names.is_empty(),
            "expected no jobs to be pushed; recorded jobs: {names:?}"
        );
        self
    }

    fn count<J: Job>(&self) -> usize {
        self.recording
            .state()
            .records
            .iter()
            .filter(|record| record.payload.job == J::NAME)
            .count()
    }

    fn recorded_names(&self) -> Vec<String> {
        self.recording
            .state()
            .records
            .iter()
            .map(|record| record.payload.job.clone())
            .collect()
    }
}

impl fmt::Debug for QueueFake {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("QueueFake")
            .field("recorded_jobs", &self.recorded_names())
            .finish_non_exhaustive()
    }
}

/// A job that a [`QueueFake`] recorded, decoded as a worker would read it.
///
/// `Pushed<J>` dereferences to the job. Its own methods, such as `connection`, `queue`, `delay`,
/// and `chain`, take precedence over job methods with the same names, so call those job methods
/// through [`job`](Self::job). Reading the job's fields works directly.
#[derive(Debug)]
pub struct Pushed<J> {
    job: Arc<J>,
    id: JobId,
    connection: String,
    queue: String,
    delay: Duration,
    chain: JobList,
    catch: CallbackList,
}

impl<J> Clone for Pushed<J> {
    fn clone(&self) -> Self {
        Self {
            job: Arc::clone(&self.job),
            id: self.id,
            connection: self.connection.clone(),
            queue: self.queue.clone(),
            delay: self.delay,
            chain: self.chain.clone(),
            catch: self.catch.clone(),
        }
    }
}

impl<J> Pushed<J> {
    /// The job.
    pub fn job(&self) -> &J {
        &self.job
    }

    /// The job's ID.
    pub const fn id(&self) -> JobId {
        self.id
    }

    /// The connection the job was dispatched to, such as `database`.
    pub fn connection(&self) -> &str {
        &self.connection
    }

    /// The queue the job was dispatched to, such as `default`.
    pub fn queue(&self) -> &str {
        &self.queue
    }

    /// How long the job was delayed from when it was pushed.
    ///
    /// The returned duration compares equal to the span or duration you dispatched the job with, as
    /// in `job.delay() == 5.minutes()`.
    pub fn delay(&self) -> ExactDuration {
        self.delay.into()
    }

    /// The jobs chained after this job, in the order they'll run.
    pub const fn chain(&self) -> &JobList {
        &self.chain
    }

    /// The callbacks that this job's chain calls if a job in the chain fails for good.
    pub const fn chain_catch(&self) -> &CallbackList {
        &self.catch
    }
}

/// The jobs waiting in a chain or a batch, as a test sees them.
///
/// The list holds each job's name and the job as you dispatched it. A batch that's a step of a
/// chain is named `batch`, and [`batch`](Self::batch) returns it.
#[derive(Debug, Clone, Default)]
pub struct JobList(Vec<Link>);

impl JobList {
    #[doc(hidden)]
    pub const fn new(jobs: Vec<Link>) -> Self {
        Self(jobs)
    }

    /// The number of jobs in the list.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Whether the list has no jobs.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Each job's name in order, as `Job::NAME` gives it, with `batch` for a batch.
    #[must_use]
    pub fn names(&self) -> Vec<&str> {
        self.0.iter().map(Link::name).collect()
    }

    /// The job at `index`, decoded as a worker would read it.
    ///
    /// Returns `None` when there's no job at `index` or when the job there is of another type.
    ///
    /// # Panics
    ///
    /// Panics when the job at `index` is of this type but its payload doesn't decode.
    #[must_use]
    pub fn get<J: Job>(&self, index: usize) -> Option<Arc<J>> {
        let Some(Link::Job(job)) = self.0.get(index) else {
            return None;
        };
        if job.job != J::NAME {
            return None;
        }

        Some(dispatched(&job.dispatched, job.data.clone(), "chained job"))
    }

    /// The batch at `index`, or `None` when there's no batch there.
    #[must_use]
    pub fn batch(&self, index: usize) -> Option<PushedBatch> {
        match self.0.get(index)? {
            Link::Batch { batch } => Some(PushedBatch((**batch).clone())),
            Link::Job(_) => None,
        }
    }
}

/// A batch's or chain's callbacks, as a test sees them.
///
/// The list holds each callback's name and the callback as you dispatched it.
#[derive(Debug, Clone, Default)]
pub struct CallbackList(Vec<EncodedCallback>);

impl CallbackList {
    /// The number of callbacks in the list.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Whether the list has no callbacks.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Each callback's name, in order, as `Callback::NAME` gives it.
    #[must_use]
    pub fn names(&self) -> Vec<&str> {
        self.0.iter().map(|callback| callback.callback.as_str()).collect()
    }

    /// The callback at `index`, decoded as a worker would read it.
    ///
    /// Returns `None` when there's no callback at `index` or when the callback there is of another
    /// type.
    ///
    /// # Panics
    ///
    /// Panics when the callback at `index` is of this type but its payload doesn't decode.
    #[must_use]
    pub fn get<C: Callback>(&self, index: usize) -> Option<Arc<C>> {
        let callback = self.0.get(index).filter(|callback| callback.callback == C::NAME)?;

        Some(dispatched(&callback.dispatched, callback.data.clone(), "callback"))
    }
}

/// A batch that a [`QueueFake`] recorded, or a batch that's a step of a chain, with its jobs,
/// name, and options.
#[derive(Debug, Clone)]
pub struct PushedBatch(BatchSpec);

impl PushedBatch {
    /// The batch's ID, which awaiting the batch's dispatch returned.
    #[must_use]
    pub const fn id(&self) -> BatchId {
        self.0.id
    }

    /// The batch's name, if it has one.
    #[must_use]
    pub fn name(&self) -> Option<&str> {
        self.0.name.as_deref()
    }

    /// The batch's jobs, in the order they were given. For a chain in the batch, the list holds the
    /// chain's first job.
    #[must_use]
    pub fn jobs(&self) -> JobList {
        JobList(
            self.0
                .jobs
                .iter()
                .filter_map(|chain| chain.jobs.first().cloned())
                .collect(),
        )
    }

    /// The jobs chained after the batch's job at `index`, in the order they'll run.
    ///
    /// The list is empty for a job that isn't a chain.
    #[must_use]
    pub fn chain(&self, index: usize) -> JobList {
        JobList(
            self.0
                .jobs
                .get(index)
                .map(|chain| chain.jobs.iter().skip(1).cloned().collect())
                .unwrap_or_default(),
        )
    }

    /// The callbacks the batch calls once every one of its jobs has succeeded.
    #[must_use]
    pub fn then(&self) -> CallbackList {
        CallbackList(self.0.options.then.clone())
    }

    /// The callbacks the batch calls when the first of its jobs fails for good.
    #[must_use]
    pub fn catch(&self) -> CallbackList {
        CallbackList(self.0.options.catch.clone())
    }

    /// The callbacks the batch calls once every one of its jobs has run.
    #[must_use]
    pub fn finally(&self) -> CallbackList {
        CallbackList(self.0.options.finally.clone())
    }

    /// Whether the batch keeps running when a job fails for good.
    #[must_use]
    pub const fn allows_failures(&self) -> bool {
        self.0.options.allow_failures
    }

    /// The connection the batch sends its jobs to, or `None` if it didn't choose one.
    #[must_use]
    pub fn connection(&self) -> Option<&str> {
        self.0.options.connection.as_deref()
    }

    /// The queue the batch sends its jobs to, or `None` if it didn't choose one.
    #[must_use]
    pub fn queue(&self) -> Option<&str> {
        self.0.options.queue.as_deref()
    }
}

/// A job type or a tuple of job types that names a chain, such as `TranscribePodcast` or
/// `(ShipOrder, RecordShipment)`.
///
/// [`QueueFake::assert_chained`] and the test job chain assertions accept this trait.
pub trait JobTypes {
    /// The jobs' names, in order.
    #[doc(hidden)]
    fn names() -> Vec<&'static str>;
}

impl<J: Job> JobTypes for J {
    fn names() -> Vec<&'static str> {
        vec![J::NAME]
    }
}

macro_rules! job_types {
    ($($name:ident),+) => {
        impl<$($name: Job),+> JobTypes for ($($name,)+) {
            fn names() -> Vec<&'static str> {
                vec![$($name::NAME),+]
            }
        }
    };
}

job_types!(A);
job_types!(A, B);
job_types!(A, B, C);
job_types!(A, B, C, D);
job_types!(A, B, C, D, E);
job_types!(A, B, C, D, E, F);
job_types!(A, B, C, D, E, F, G);
job_types!(A, B, C, D, E, F, G, H);

impl<J> Deref for Pushed<J> {
    type Target = J;

    fn deref(&self) -> &J {
        &self.job
    }
}

/// The models of a job or callback as it was dispatched, without their relationships, kept
/// beside its encoded data so a queue fake's assertions can read them without a database.
/// Payloads read from a queue have none.
#[derive(Clone, Default)]
pub(crate) struct Dispatched(Option<Arc<ModelRows>>);

impl Dispatched {
    pub(crate) fn new(rows: ModelRows) -> Self {
        Self(Some(Arc::new(rows)))
    }
}

/// Payloads compare by their encoded data.
impl PartialEq for Dispatched {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

impl fmt::Debug for Dispatched {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Dispatched")
    }
}

/// The value decoded from its payload, with its models as they were dispatched, without their
/// relationships, as a worker would read them.
fn dispatched<Q: Queueable>(dispatched: &Dispatched, data: Value, kind: &str) -> Arc<Q> {
    let rows = dispatched
        .0
        .as_deref()
        .unwrap_or_else(|| panic!("the {kind} `{}` wasn't recorded by a queue fake", type_name::<Q>()));

    match Q::__assemble(data, rows) {
        Ok(value) => Arc::new(value),
        Err(error) => panic!(
            "the {kind} `{}` couldn't be decoded from its payload: {error}",
            type_name::<Q>()
        ),
    }
}

/// The application's active fakes.
#[derive(Debug, Default)]
pub(crate) struct Fakes(FakeStack<Recording>);

impl std::ops::Deref for Fakes {
    type Target = FakeStack<Recording>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Fakes {
    pub(super) fn record(&self, payload: &Payload, connection: &str, queue: &str, delay: Duration) -> bool {
        let Some(recording) = self.active() else {
            return false;
        };
        let mut state = recording.state();
        if !state.selects(&payload.job) {
            return false;
        }

        state.records.push(Record {
            payload: payload.clone(),
            connection: connection.to_owned(),
            queue: queue.to_owned(),
            delay,
        });
        true
    }

    pub(super) fn record_batch(&self, batch: &BatchSpec) -> bool {
        let Some(recording) = self.active() else {
            return false;
        };

        recording.state().batches.push(RecordedBatch {
            spec: batch.clone(),
            cancelled: false,
        });
        true
    }

    pub(super) fn find_batch(&self, id: BatchId) -> Option<(BatchSpec, bool)> {
        self.recordings().iter().find_map(|recording| {
            let state = recording.state();
            let batch = state.batches.iter().find(|batch| batch.spec.id == id)?;
            Some((batch.spec.clone(), batch.cancelled))
        })
    }

    pub(super) fn cancel_batch(&self, id: BatchId) -> bool {
        self.recordings().iter().any(|recording| {
            let mut state = recording.state();
            let Some(batch) = state.batches.iter_mut().find(|batch| batch.spec.id == id) else {
                return false;
            };
            batch.cancelled = true;
            true
        })
    }
}

#[derive(Default)]
pub(crate) struct Recording(Mutex<State>);

impl Recording {
    fn state(&self) -> MutexGuard<'_, State> {
        self.0.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

#[derive(Default)]
struct State {
    only: Option<HashSet<&'static str>>,
    except: HashSet<&'static str>,
    records: Vec<Record>,
    batches: Vec<RecordedBatch>,
}

struct RecordedBatch {
    spec: BatchSpec,
    cancelled: bool,
}

impl State {
    fn selects(&self, job: &str) -> bool {
        !self.except.contains(job) && self.only.as_ref().is_none_or(|jobs| jobs.contains(job))
    }
}

#[derive(Clone)]
struct Record {
    payload: Payload,
    connection: String,
    queue: String,
    delay: Duration,
}