Skip to main content

navree_queue/
fake.rs

1//! [`QueueFake`]: records dispatched jobs for assertions in tests.
2
3use std::fmt;
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
5
6use navree_contracts::{BoxError, BoxFuture, Dispatcher, Job, JobEnvelope};
7
8use crate::batch::BatchRow;
9use crate::store::Store;
10use crate::{JobBatch, Queue, QueueOptions};
11
12/// A queue that records jobs instead of running them, for tests.
13///
14/// Swap it in for the app's queue with
15/// `override_value(Arc::new(fake.queue()))` (the module's `dyn Dispatcher`
16/// then records too), or, in an app without `QueueModule`, with
17/// `override_value(fake.dispatcher())`. Then assert on what was dispatched:
18///
19/// ```
20/// use navree_contracts::{BoxError, Job, JobContext};
21/// use navree_queue::QueueFake;
22/// use serde::{Deserialize, Serialize};
23///
24/// #[derive(Debug, Serialize, Deserialize)]
25/// struct SendInvoice {
26///     invoice: u32,
27/// }
28///
29/// impl Job for SendInvoice {
30///     const NAME: &'static str = "billing.send_invoice";
31///
32///     async fn handle(self, _ctx: JobContext) -> Result<(), BoxError> {
33///         Ok(())
34///     }
35/// }
36///
37/// # #[tokio::main(flavor = "current_thread")]
38/// # async fn main() {
39/// let fake = QueueFake::new();
40/// fake.queue().dispatch(SendInvoice { invoice: 7 }).await.unwrap();
41///
42/// fake.assert_dispatched::<SendInvoice>(|job| job.invoice == 7);
43/// assert_eq!(fake.dispatched::<SendInvoice>().len(), 1);
44/// # }
45/// ```
46///
47/// Clones share the record. Jobs dispatched in a unit of work are recorded
48/// when it commits. The fake queue never runs jobs: `work` and
49/// `run_pending` return empty stats and nothing ever fails.
50///
51/// Batches are recorded apart from single jobs ([`batches`](QueueFake::batches),
52/// [`assert_batched`](QueueFake::assert_batched)): a batch's jobs are not
53/// in [`dispatched`](QueueFake::dispatched). `find_batch` and `batches`
54/// return a recorded batch as a driver stores it when it is dispatched
55/// (every job pending), and `cancel_batch` cancels it.
56#[derive(Clone, Default)]
57pub struct QueueFake {
58    recorded: Arc<Mutex<Vec<JobEnvelope>>>,
59    batches: Arc<Mutex<Vec<FakeBatch>>>,
60}
61
62/// A batch [`QueueFake`] recorded: the stored batch, its jobs and its
63/// callbacks.
64#[derive(Clone, Debug)]
65pub struct RecordedBatch {
66    /// The batch as a driver stores it when it is dispatched.
67    pub batch: JobBatch,
68    /// Its jobs, in order.
69    pub jobs: Vec<JobEnvelope>,
70    /// The `then` callback.
71    pub then: Option<JobEnvelope>,
72    /// The `catch` callback.
73    pub catch: Option<JobEnvelope>,
74    /// The `finally` callback.
75    pub finally: Option<JobEnvelope>,
76}
77
78impl RecordedBatch {
79    /// The batch's name.
80    pub fn name(&self) -> &str {
81        &self.batch.name
82    }
83
84    /// The batch's jobs of type `J`, in order.
85    ///
86    /// # Panics
87    ///
88    /// When a recorded payload of type `J` does not deserialize as `J`.
89    pub fn jobs_of<J: Job>(&self) -> Vec<J> {
90        decode_all::<J>(&self.jobs)
91    }
92
93    /// Whether the batch's `then` callback is a `J` (decoded).
94    pub fn then_of<J: Job>(&self) -> Option<J> {
95        self.then.as_ref().and_then(decode::<J>)
96    }
97
98    /// Whether the batch's `catch` callback is a `J` (decoded).
99    pub fn catch_of<J: Job>(&self) -> Option<J> {
100        self.catch.as_ref().and_then(decode::<J>)
101    }
102
103    /// Whether the batch's `finally` callback is a `J` (decoded).
104    pub fn finally_of<J: Job>(&self) -> Option<J> {
105        self.finally.as_ref().and_then(decode::<J>)
106    }
107}
108
109/// What the fake keeps of a batch.
110#[derive(Clone, Debug)]
111struct FakeBatch {
112    row: BatchRow,
113    jobs: Vec<JobEnvelope>,
114}
115
116fn decode<J: Job>(envelope: &JobEnvelope) -> Option<J> {
117    (envelope.job_type == J::NAME)
118        .then(|| serde_json::from_value(envelope.payload.clone()).ok())
119        .flatten()
120}
121
122fn decode_all<J: Job>(envelopes: &[JobEnvelope]) -> Vec<J> {
123    envelopes
124        .iter()
125        .filter(|e| e.job_type == J::NAME)
126        .map(|e| {
127            serde_json::from_value(e.payload.clone()).unwrap_or_else(|error| {
128                panic!("a recorded `{}` job does not deserialize: {error}", J::NAME)
129            })
130        })
131        .collect()
132}
133
134impl QueueFake {
135    /// Every recorded batch, in dispatch order.
136    pub fn batches(&self) -> Vec<RecordedBatch> {
137        self.batch_lock()
138            .iter()
139            .map(|fake| RecordedBatch {
140                batch: fake.row.to_batch(),
141                jobs: fake.jobs.clone(),
142                then: fake.row.callbacks.then.clone(),
143                catch: fake.row.callbacks.catch.clone(),
144                finally: fake.row.callbacks.finally.clone(),
145            })
146            .collect()
147    }
148
149    /// Asserts a batch matching `pred` was dispatched.
150    ///
151    /// # Panics
152    ///
153    /// When none was, naming the batches that were.
154    pub fn assert_batched(&self, pred: impl Fn(&RecordedBatch) -> bool) {
155        let batches = self.batches();
156        assert!(
157            batches.iter().any(pred),
158            "expected a matching batch to be dispatched; these were: {:?}",
159            batches.iter().map(RecordedBatch::name).collect::<Vec<_>>()
160        );
161    }
162
163    /// Asserts no batch was dispatched.
164    ///
165    /// # Panics
166    ///
167    /// When one was.
168    pub fn assert_nothing_batched(&self) {
169        let batches = self.batches();
170        assert!(
171            batches.is_empty(),
172            "expected no batch to be dispatched, these were: {:?}",
173            batches.iter().map(RecordedBatch::name).collect::<Vec<_>>()
174        );
175    }
176
177    /// Records a dispatched batch.
178    pub(crate) fn record_batch(&self, row: BatchRow, jobs: Vec<JobEnvelope>) {
179        self.batch_lock().push(FakeBatch { row, jobs });
180    }
181
182    pub(crate) fn find_batch(&self, id: &str) -> Option<BatchRow> {
183        self.batch_lock()
184            .iter()
185            .find(|fake| fake.row.id == id)
186            .map(|fake| fake.row.clone())
187    }
188
189    pub(crate) fn batch_rows(&self, limit: usize) -> Vec<BatchRow> {
190        let mut rows: Vec<BatchRow> = self.batch_lock().iter().map(|f| f.row.clone()).collect();
191        rows.reverse();
192        rows.truncate(limit);
193        rows
194    }
195
196    pub(crate) fn cancel_batch(&self, id: &str, now: i64) -> Option<BatchRow> {
197        let mut batches = self.batch_lock();
198        let fake = batches.iter_mut().find(|fake| fake.row.id == id)?;
199        fake.row.cancel(now);
200        Some(fake.row.clone())
201    }
202
203    fn batch_lock(&self) -> MutexGuard<'_, Vec<FakeBatch>> {
204        self.batches.lock().unwrap_or_else(PoisonError::into_inner)
205    }
206    /// An empty fake.
207    pub fn new() -> Self {
208        Self::default()
209    }
210
211    /// A [`Queue`] whose dispatches are recorded by this fake. It accepts
212    /// any job type, registered or not.
213    pub fn queue(&self) -> Queue {
214        Queue::new(
215            Store::Fake(self.clone()),
216            QueueOptions::default(),
217            None,
218            Vec::new(),
219            None,
220        )
221    }
222
223    /// This fake as a `dyn Dispatcher`.
224    pub fn dispatcher(&self) -> Arc<dyn Dispatcher> {
225        Arc::new(self.clone())
226    }
227
228    /// Every recorded job, in dispatch order.
229    pub fn envelopes(&self) -> Vec<JobEnvelope> {
230        self.lock().clone()
231    }
232
233    /// The recorded jobs of type `J`, in dispatch order.
234    ///
235    /// # Panics
236    ///
237    /// When a recorded payload of type `J` does not deserialize as `J`.
238    pub fn dispatched<J: Job>(&self) -> Vec<J> {
239        self.lock()
240            .iter()
241            .filter(|e| e.job_type == J::NAME)
242            .map(|e| {
243                serde_json::from_value(e.payload.clone()).unwrap_or_else(|error| {
244                    panic!("a recorded `{}` job does not deserialize: {error}", J::NAME)
245                })
246            })
247            .collect()
248    }
249
250    /// Asserts a job of type `J` matching `pred` was dispatched.
251    ///
252    /// # Panics
253    ///
254    /// When none was, naming the job type and what was dispatched.
255    pub fn assert_dispatched<J: Job>(&self, pred: impl Fn(&J) -> bool) {
256        let jobs = self.dispatched::<J>();
257        assert!(
258            jobs.iter().any(pred),
259            "expected a matching `{}` job to be dispatched; {} `{}` job(s) were, and these job types: {:?}",
260            J::NAME,
261            jobs.len(),
262            J::NAME,
263            self.job_types()
264        );
265    }
266
267    /// Asserts exactly `times` jobs of type `J` were dispatched.
268    ///
269    /// # Panics
270    ///
271    /// When the count differs.
272    pub fn assert_dispatched_times<J: Job>(&self, times: usize) {
273        let count = self.dispatched::<J>().len();
274        assert_eq!(
275            count,
276            times,
277            "expected `{}` to be dispatched {times} time(s), it was {count} time(s)",
278            J::NAME
279        );
280    }
281
282    /// Asserts no job of type `J` was dispatched.
283    ///
284    /// # Panics
285    ///
286    /// When one was.
287    pub fn assert_not_dispatched<J: Job>(&self) {
288        let count = self.dispatched::<J>().len();
289        assert_eq!(
290            count,
291            0,
292            "expected no `{}` job to be dispatched, {count} were",
293            J::NAME
294        );
295    }
296
297    /// Asserts nothing was dispatched.
298    ///
299    /// # Panics
300    ///
301    /// When something was.
302    pub fn assert_nothing_dispatched(&self) {
303        let types = self.job_types();
304        assert!(
305            types.is_empty(),
306            "expected no jobs to be dispatched, these were: {types:?}"
307        );
308    }
309
310    /// Forgets every recorded job and batch.
311    pub fn clear(&self) {
312        self.lock().clear();
313        self.batch_lock().clear();
314    }
315
316    /// Records `envelope`.
317    pub(crate) fn record(&self, envelope: JobEnvelope) {
318        self.lock().push(envelope);
319    }
320
321    /// How many recorded jobs are on `queue`.
322    pub(crate) fn count_on(&self, queue: &str) -> u64 {
323        self.lock()
324            .iter()
325            .filter(|e| e.options.queue == queue)
326            .count() as u64
327    }
328
329    fn job_types(&self) -> Vec<String> {
330        self.lock().iter().map(|e| e.job_type.clone()).collect()
331    }
332
333    fn lock(&self) -> MutexGuard<'_, Vec<JobEnvelope>> {
334        self.recorded.lock().unwrap_or_else(PoisonError::into_inner)
335    }
336}
337
338impl Dispatcher for QueueFake {
339    fn dispatch_envelope(&self, env: JobEnvelope) -> BoxFuture<'_, Result<String, BoxError>> {
340        Box::pin(async move { Ok(self.queue().push(env).await?) })
341    }
342}
343
344impl fmt::Debug for QueueFake {
345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346        f.debug_struct("QueueFake")
347            .field("dispatched", &self.job_types())
348            .finish()
349    }
350}