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
use std::error::Error as StdError;
use std::future::{Future, IntoFuture};
use std::pin::Pin;

use jiff::ZonedDateTimeArithmetic;
use tracing::Instrument;

use crate::context::{Context, Internals};
use crate::queue::{
    Batch, BatchId, Callback, Catch, EncodedCallback, EncodedJob, Finally, Job, JobList, JobTypes, Link, Outcome,
    Payload, Place, Point, Ran, Then,
};
use crate::{Application, Error};

/// Runs one attempt of a queued job, or one method of a batch callback, in the test's process,
/// without a queue or a worker.
///
/// [`job`](Self::job) returns a [`TestJob`] and [`callback`](Self::callback) returns a
/// [`TestCallback`]. Await either one to run it.
///
/// The job is encoded to its payload and decoded again, as it would be for a worker, so it reads
/// its models again from the database. It runs in a fresh context of the application. When the
/// job fails, its `failed` hook doesn't run. When the job succeeds, the jobs it added to its
/// chain aren't dispatched, and [`TestJobResult::chain`] lists them instead. A job run
/// [`in_batch`](TestJob::in_batch) doesn't change a stored batch either, and
/// [`TestJobResult::added_to_batch`] lists the jobs it added.
///
/// ```
/// use laravel::queue::{Attempt, job};
/// use laravel::testing::RunsJobs;
/// use laravel::time::ToSpan;
///
/// #[derive(laravel::queue::Queueable)]
/// struct ProcessPodcast { podcast_id: i64 }
///
/// #[job(tries = 3)]
/// impl ProcessPodcast {
///     async fn handle(self, attempt: &Attempt) {
///         if attempt.number() < 3 {
///             attempt.release(30.seconds());
///         }
///     }
/// }
///
/// let app = laravel::Application::configure()
///     .replace_env(laravel::config::Env::default())
///     .create();
/// laravel::testing::__run(async {
///     app.job(ProcessPodcast { podcast_id: 42 }).await.assert_released_after(30.seconds());
///     app.job(ProcessPodcast { podcast_id: 42 }).attempt(3).await.assert_succeeded();
/// });
/// ```
pub trait RunsJobs {
    /// Run one attempt of `job`. The attempt is the job's first unless [`TestJob::attempt`]
    /// sets another number.
    fn job<J: Job>(&self, job: J) -> TestJob<J>;

    /// Prepare a call to one of `callback`'s methods, as a worker makes when a batch or chain
    /// reaches that point.
    ///
    /// The method receives a batch that exists only for the test. [`TestCallback`] sets the
    /// batch's counts and chooses the method to call.
    fn callback<C: Callback>(&self, callback: C) -> TestCallback<C>;
}

impl RunsJobs for Application {
    fn job<J: Job>(&self, job: J) -> TestJob<J> {
        TestJob {
            application: self.clone(),
            job,
            attempt: 1,
            batch: None,
        }
    }

    fn callback<C: Callback>(&self, callback: C) -> TestCallback<C> {
        TestCallback {
            application: self.clone(),
            callback,
            batch: FakeBatch::default(),
        }
    }
}

/// One attempt of a job, from [`RunsJobs::job`].
///
/// Await the attempt to run the job and get a [`TestJobResult`]. A job that fails or panics
/// doesn't fail the test, so assert how the job ended on the result.
#[derive(Debug)]
#[must_use = "a test job does nothing unless awaited"]
pub struct TestJob<J> {
    application: Application,
    job: J,
    attempt: u32,
    batch: Option<BatchId>,
}

impl<J: Job> TestJob<J> {
    /// Run as this attempt, as [`Attempt::number`](crate::queue::Attempt::number) reports it.
    ///
    /// Attempts count from 1, which is the default. Passing `0` runs attempt 1.
    pub fn attempt(mut self, number: u32) -> Self {
        self.attempt = number.max(1);
        self
    }

    /// Run as one of a batch's jobs.
    ///
    /// [`Attempt::batch_id`](crate::queue::Attempt::batch_id) returns an ID, and the job can add
    /// jobs to its batch or cancel it. The test stores no batch, so assert those changes on the
    /// [`TestJobResult`].
    pub fn in_batch(mut self) -> Self {
        self.batch = Some(BatchId::generate());
        self
    }

    async fn run(self) -> TestJobResult {
        let Self {
            application,
            job,
            attempt,
            batch,
        } = self;

        application
            .scope(async move || {
                let context = Context::expect("laravel::testing::RunsJobs::job()");
                let connection = crate::queue::manager().default_connection().to_owned();
                let queue = J::options().queue.unwrap_or("default");
                let ran = match EncodedJob::new(job).map(|job| Payload::new(job, &context.values())) {
                    Ok(mut payload) => {
                        payload.debounce_id = None;
                        payload.batch = batch;
                        let place = Place {
                            connection: &connection,
                            queue,
                            number: attempt,
                        };
                        payload.run(place).instrument(payload.span(place)).await
                    }
                    Err(error) => Ran::failed(error),
                };

                TestJobResult {
                    job: J::NAME,
                    outcome: ran.outcome,
                    chain: JobList::new(ran.chain.jobs),
                    added_to_batch: JobList::new(
                        ran.batch
                            .added
                            .into_iter()
                            .filter_map(|chain| chain.jobs.into_iter().next())
                            .collect::<Vec<Link>>(),
                    ),
                    cancelled_batch: ran.batch.cancel,
                }
            })
            .await
    }
}

impl<J: Job> IntoFuture for TestJob<J> {
    type Output = TestJobResult;
    type IntoFuture = Pin<Box<dyn Future<Output = TestJobResult> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.run())
    }
}

/// How one attempt of a job ended, with assertions.
///
/// When an assertion fails, its message names the job and says how the job actually ended. If
/// the job failed, the message includes its error.
#[derive(Debug)]
pub struct TestJobResult {
    job: &'static str,
    outcome: Outcome,
    chain: JobList,
    added_to_batch: JobList,
    cancelled_batch: bool,
}

impl TestJobResult {
    /// The jobs the attempt added to its chain with
    /// [`Attempt::prepend_to_chain`](crate::queue::Attempt::prepend_to_chain) and
    /// [`append_to_chain`](crate::queue::Attempt::append_to_chain), in the order they would run.
    #[must_use]
    pub const fn chain(&self) -> &JobList {
        &self.chain
    }

    /// Assert that the attempt added these jobs to its chain, in order.
    ///
    /// Pass a single job type or a tuple of job types, such as `TranscribePodcast` or
    /// `(TranscribePodcast, PublishPodcast)`.
    ///
    /// # Panics
    ///
    /// Panics when the jobs added to the chain don't match.
    #[track_caller]
    pub fn assert_chained<C: JobTypes>(&self) -> &Self {
        let expected = C::names();
        let actual = self.chain.names();
        assert_eq!(
            actual, expected,
            "expected job `{}` to chain {expected:?}, but it chained {actual:?}",
            self.job,
        );
        self
    }

    /// The jobs the attempt added to its batch with
    /// [`Attempt::add_to_batch`](crate::queue::Attempt::add_to_batch), in order. For a chain
    /// added to the batch, the list holds the chain's first job.
    #[must_use]
    pub const fn added_to_batch(&self) -> &JobList {
        &self.added_to_batch
    }

    /// Assert that the attempt cancelled its batch with
    /// [`Attempt::cancel_batch`](crate::queue::Attempt::cancel_batch).
    ///
    /// # Panics
    ///
    /// Panics when the attempt didn't cancel its batch.
    #[track_caller]
    pub fn assert_batch_cancelled(&self) -> &Self {
        assert!(
            self.cancelled_batch,
            "expected job `{}` to cancel its batch, but it {} without cancelling it",
            self.job,
            self.ended(),
        );
        self
    }

    /// The error the job failed with, or `None` when it didn't fail.
    ///
    /// A job that panics also fails with an error.
    #[must_use]
    pub const fn error(&self) -> Option<&Error> {
        match &self.outcome {
            Outcome::Failed { error, .. } | Outcome::Settled(error) => Some(error),
            Outcome::Succeeded
            | Outcome::Released(_)
            | Outcome::Deleted
            | Outcome::Debounced
            | Outcome::Skipped
            | Outcome::MissingModels => None,
        }
    }

    /// Assert that the job finished, without failing, releasing itself, or deleting itself.
    ///
    /// # Panics
    ///
    /// Panics when the job ended any other way.
    #[track_caller]
    pub fn assert_succeeded(&self) -> &Self {
        assert!(
            matches!(self.outcome, Outcome::Succeeded),
            "expected job `{}` to succeed, but it {}",
            self.job,
            self.ended(),
        );
        self
    }

    /// Assert that the job released itself back to its queue, with or without a delay.
    ///
    /// # Panics
    ///
    /// Panics when the job ended any other way.
    #[track_caller]
    pub fn assert_released(&self) -> &Self {
        assert!(
            matches!(self.outcome, Outcome::Released(_)),
            "expected job `{}` to be released, but it {}",
            self.job,
            self.ended(),
        );
        self
    }

    /// Assert that the job released itself back to its queue with this delay.
    ///
    /// # Panics
    ///
    /// Panics when the job ended any other way, or released itself with another delay.
    #[track_caller]
    pub fn assert_released_after(&self, delay: impl Into<ZonedDateTimeArithmetic>) -> &Self {
        let expected = crate::clock::exact_duration(delay);
        assert!(
            matches!(self.outcome, Outcome::Released(delay) if delay == expected),
            "expected job `{}` to be released for {expected:?}, but it {}",
            self.job,
            self.ended(),
        );
        self
    }

    /// Assert that the job deleted itself.
    ///
    /// # Panics
    ///
    /// Panics when the job ended any other way.
    #[track_caller]
    pub fn assert_deleted(&self) -> &Self {
        assert!(
            matches!(self.outcome, Outcome::Deleted | Outcome::MissingModels),
            "expected job `{}` to be deleted, but it {}",
            self.job,
            self.ended(),
        );
        self
    }

    /// Assert that the job failed, whether it returned an error, panicked, or failed itself.
    ///
    /// # Panics
    ///
    /// Panics when the job ended any other way.
    #[track_caller]
    pub fn assert_failed(&self) -> &Self {
        assert!(
            self.error().is_some(),
            "expected job `{}` to fail, but it {}",
            self.job,
            self.ended(),
        );
        self
    }

    /// Assert that the job failed with an error of this type, including one kept as
    /// another error's `#[source]`.
    ///
    /// # Panics
    ///
    /// Panics when the job didn't fail, or failed with an error of another type.
    #[track_caller]
    pub fn assert_failed_with<E: StdError + Send + Sync + 'static>(&self) -> &Self {
        assert!(
            self.error().and_then(super::find_error::<E>).is_some(),
            "expected job `{}` to fail with `{}`, but it {}",
            self.job,
            std::any::type_name::<E>(),
            self.ended(),
        );
        self
    }

    fn ended(&self) -> String {
        match &self.outcome {
            Outcome::Succeeded => "succeeded".to_owned(),
            Outcome::Released(delay) => format!("was released for {delay:?}"),
            Outcome::Deleted | Outcome::MissingModels => "was deleted".to_owned(),
            Outcome::Debounced => "was debounced".to_owned(),
            Outcome::Skipped => "was skipped".to_owned(),
            Outcome::Failed { error, .. } | Outcome::Settled(error) => format!("failed: {error}"),
        }
    }
}

/// A [callback](macro@crate::queue::callback) to call in a test, from [`RunsJobs::callback`].
///
/// Await [`then`](Self::then), [`catch`](Self::catch), or [`finally`](Self::finally) to call that
/// method in a fresh context of the application, as a worker would, and get the callback's
/// result. The callback is encoded to its payload and decoded again, as it would be when stored
/// with a batch, so it reads its models again from the database.
///
/// The method receives a `&Batch` that isn't stored. By default, the batch has one job. For
/// `then` and `finally`, that job succeeded and the batch is finished. For `catch`, the job
/// failed. The other methods of this type change the batch's name, counts, and cancellation.
///
/// ```
/// use laravel::queue::{Batch, callback};
/// use laravel::testing::RunsJobs;
///
/// #[derive(laravel::queue::Queueable)]
/// struct ImportFinished { import_id: i64 }
///
/// #[callback]
/// impl ImportFinished {
///     async fn finally(self, batch: &Batch) -> laravel::Result<()> {
///         if batch.has_failures() {
///             return Err(laravel::abort_with(500, "the import has failures"));
///         }
///         Ok(())
///     }
/// }
///
/// let app = laravel::Application::configure()
///     .replace_env(laravel::config::Env::default())
///     .create();
/// laravel::testing::__run(async {
///     app.callback(ImportFinished { import_id: 7 }).finally().await.unwrap();
///     app.callback(ImportFinished { import_id: 7 })
///         .total_jobs(3)
///         .failed_jobs(1)
///         .finally()
///         .await
///         .unwrap_err();
/// });
/// ```
#[derive(Debug)]
#[must_use = "a test callback does nothing until one of its methods is awaited"]
pub struct TestCallback<C> {
    application: Application,
    callback: C,
    batch: FakeBatch,
}

#[derive(Debug, Default)]
struct FakeBatch {
    name: Option<String>,
    total: Option<u64>,
    pending: Option<u64>,
    failed: Option<u64>,
    cancelled: bool,
}

impl<C: Callback> TestCallback<C> {
    /// Name the batch, as [`Batch::name`] reports it.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.batch.name = Some(name.into());
        self
    }

    /// Give the batch this many jobs. The default is 1.
    pub const fn total_jobs(mut self, jobs: u64) -> Self {
        self.batch.total = Some(jobs);
        self
    }

    /// Leave this many of the batch's jobs pending.
    ///
    /// As in a stored batch, the pending count includes the failed jobs. The default is the
    /// number of failed jobs, which makes the batch finished.
    pub const fn pending_jobs(mut self, jobs: u64) -> Self {
        self.batch.pending = Some(jobs);
        self
    }

    /// Count this many of the batch's jobs as failed. The default is 1 for `catch`, and 0 for
    /// `then` and `finally`.
    pub const fn failed_jobs(mut self, jobs: u64) -> Self {
        self.batch.failed = Some(jobs);
        self
    }

    /// Mark the batch as cancelled.
    pub const fn cancelled(mut self) -> Self {
        self.batch.cancelled = true;
        self
    }

    async fn call(self, method: Method) -> crate::Result<()> {
        let Self {
            application,
            callback,
            batch,
        } = self;
        let failed = batch.failed.unwrap_or(u64::from(matches!(method, Method::Catch(_))));
        let pending = batch.pending.unwrap_or(failed);
        let total = batch.total.unwrap_or(1).max(pending).max(failed);
        let callback = EncodedCallback::new(callback)?;

        application
            .scope(async move || {
                let now = jiff::Timestamp::try_from(crate::clock::system_now()).unwrap_or(jiff::Timestamp::UNIX_EPOCH);
                let batch = Batch::new(
                    BatchId::generate(),
                    batch.name,
                    (total, pending, failed),
                    now,
                    batch.cancelled.then_some(now),
                    // Failed jobs stay pending, so a batch is finished once only they are...
                    (pending == failed).then_some(now),
                );
                let point = match &method {
                    Method::Then => Point::Then(&batch),
                    Method::Catch(error) => Point::Catch(Some(&batch), error),
                    Method::Finally => Point::Finally(&batch),
                };
                callback.run(point).await
            })
            .await
    }
}

/// The callback method a [`TestCallback`] calls.
enum Method {
    Then,
    Catch(Error),
    Finally,
}

impl<C: Then> TestCallback<C> {
    /// Call the callback's `then`, as a worker does when every job of a batch succeeded.
    ///
    /// # Errors
    ///
    /// Returns the callback's error, an error for a panic in the callback, or an error encoding
    /// the callback.
    pub fn then(self) -> impl Future<Output = crate::Result<()>> + Send {
        self.call(Method::Then)
    }
}

impl<C: Catch> TestCallback<C> {
    /// Call the callback's `catch` with `error`, as a worker does when a job fails and has no
    /// tries left.
    ///
    /// # Errors
    ///
    /// Returns the callback's error, an error for a panic in the callback, or an error encoding
    /// the callback.
    pub fn catch(self, error: impl Into<Error>) -> impl Future<Output = crate::Result<()>> + Send {
        self.call(Method::Catch(error.into()))
    }
}

impl<C: Finally> TestCallback<C> {
    /// Call the callback's `finally`, as a worker does when every job of a batch has run.
    ///
    /// # Errors
    ///
    /// Returns the callback's error, an error for a panic in the callback, or an error encoding
    /// the callback.
    pub fn finally(self) -> impl Future<Output = crate::Result<()>> + Send {
        self.call(Method::Finally)
    }
}