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
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::str::FromStr;
use std::sync::{Arc, LazyLock};
use std::time::Duration;

use futures_util::future::BoxFuture;
use jiff::ZonedDateTimeArithmetic;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::{Attempt, MiddlewareGroup, Queueable};
use crate::time::ExactDuration;
use crate::{Error, Result};

/// A [`Queueable`] struct with a handler, which the queue keeps and runs later.
///
/// Implement this trait with [`#[job]`](macro@super::job) on the struct's `impl` block. The
/// attribute names the job, reads its options, and resolves the handler's services. The struct's
/// fields are the job's data, which the queue stores until the job runs.
pub trait Job: Queueable {
    /// The name that the queue stores the job under and finds it by.
    ///
    /// The name defaults to the type's path, so moving or renaming the type leaves jobs that are
    /// already queued without a handler. Set `#[job(name = "..")]` to keep the name stable. Names
    /// must be unique, and an application with two jobs of the same name, including jobs from
    /// packages, doesn't start.
    const NAME: &'static str;

    /// The job's queue, retries, and timeout. Defaults to [`JobOptions::new`].
    #[must_use]
    fn options() -> JobOptions {
        JobOptions::new()
    }

    /// The middleware that wraps `handle` on each attempt, with the first middleware outermost.
    ///
    /// The worker calls this method before each attempt, so the middleware can depend on the job's
    /// data. Defaults to no middleware.
    #[must_use]
    fn middleware(&self) -> MiddlewareGroup {
        MiddlewareGroup::new()
    }

    /// The ID that tells this job's debounced dispatches apart.
    ///
    /// Of the dispatches with the same ID, only the latest runs. The queue uses the ID only when
    /// the job sets `debounce_for`. Defaults to an empty ID, so every dispatch of the job shares
    /// one ID.
    ///
    /// The queue records each ID's latest dispatch in the default cache store. Dispatching fails
    /// when the cache can't be written, and the job runs when the worker can't read the cache. A
    /// job may therefore run more often than it should, but it's never lost. Before each run,
    /// including retries and runs after a release, and before the job's middleware, the queue
    /// removes a job that a later dispatch replaced, with the outcome
    /// [`JobOutcome::Debounced`](super::events::JobOutcome). A replaced job's chain doesn't run.
    ///
    /// A dispatch's own `delay` replaces `debounce_for`. A dispatch inside a transaction replaces
    /// earlier dispatches when the transaction commits. When the connection refuses a dispatch,
    /// every earlier waiting dispatch runs. A dispatch made `max_wait` after a wait started runs,
    /// and the next dispatch starts a new wait. A job that starts its `handle` also ends the wait. A
    /// debounced job later in a chain claims its ID when the job before it finishes. `queue:retry`
    /// doesn't make a job the latest dispatch. The `sync` connection, `dispatch_sync`, and test
    /// attempts don't debounce.
    #[must_use]
    fn debounce_id(&self) -> String {
        String::new()
    }

    /// Run the job.
    ///
    /// An error fails the attempt. The worker retries the job after its backoff, or fails it for
    /// good once it has no tries left. A [`TooManyAttempts`](crate::rate_limit::TooManyAttempts)
    /// error instead releases the job until the rate limit allows it, or fails the job for good when
    /// that time falls after its `retry_for`.
    fn handle(self, attempt: &Attempt) -> impl Future<Output = Result<()>> + Send;

    /// Clean up after the job has failed for good.
    ///
    /// This method receives a copy of the job restored from its payload, with its models read
    /// again, so changes that `handle` made to its own copy are gone. A job that the worker can't
    /// restore fails without calling this method. The worker reports any error this method returns.
    fn failed(self, error: &Error, attempt: &Attempt) -> impl Future<Output = Result<()>> + Send {
        let _ = (error, attempt);
        async { Ok(()) }
    }
}

/// A job's queue, retries, and timeout, from the options of [`#[job(..)]`](macro@super::job).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct JobOptions {
    /// The queue the job joins when its dispatch doesn't name another.
    pub queue: Option<&'static str>,
    /// How many times the job may run, counting releases, or `None` for the worker's default.
    /// The worker ignores this limit when `retry_for` is set.
    pub tries: Option<u32>,
    /// How many of the job's runs may fail before it fails for good, or `None` for no limit
    /// other than `tries`.
    ///
    /// A run that stops its worker counts as a failed run. The worker counts errors in the default
    /// cache store for a day. When the worker can't reach the cache, it doesn't count the error.
    pub max_errors: Option<u32>,
    /// How long to wait before each retry, in order. The last delay repeats once the list runs out.
    pub backoff: Vec<ExactDuration>,
    /// How long one attempt may run, or `None` for the worker's default.
    pub timeout: Option<ExactDuration>,
    /// How long after dispatch the job may still be retried, or `None` for no limit.
    pub retry_for: Option<ExactDuration>,
    /// How long each dispatch waits before it may run, or `None` to not debounce the job.
    ///
    /// Of the waiting dispatches with the same [debounce ID](Job::debounce_id), only the latest
    /// runs.
    pub debounce_for: Option<ExactDuration>,
    /// How long the first of a debounced job's waiting dispatches may wait before a dispatch runs
    /// without waiting, or `None` for no limit. The queue ignores this limit without
    /// `debounce_for`.
    pub max_wait: Option<ExactDuration>,
    /// Whether to fail the job for good, rather than delete it, when the row of one of its models
    /// is gone.
    pub fail_when_missing_models: bool,
}

impl JobOptions {
    /// Create options with nothing set, so the worker's defaults apply.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Join this queue when the dispatch doesn't name another.
    #[must_use]
    pub const fn queue(mut self, queue: &'static str) -> Self {
        self.queue = Some(queue);
        self
    }

    /// Run the job at most this many times, counting releases. The value must be at least one.
    #[must_use]
    pub fn tries(mut self, tries: u32) -> Self {
        self.tries = Some(tries.max(1));
        self
    }

    /// Fail the job for good once this many runs have failed. The value must be at least one.
    #[must_use]
    pub fn max_errors(mut self, errors: u32) -> Self {
        self.max_errors = Some(errors.max(1));
        self
    }

    /// Wait this long before each retry, in order.
    #[must_use]
    pub fn backoff(mut self, delays: impl IntoIterator<Item = impl Into<ZonedDateTimeArithmetic>>) -> Self {
        self.backoff = delays
            .into_iter()
            .map(|delay| crate::clock::exact_duration(delay).into())
            .collect();
        self
    }

    /// Stop an attempt that runs longer than this.
    #[must_use]
    pub fn timeout(mut self, timeout: impl Into<ZonedDateTimeArithmetic>) -> Self {
        self.timeout = Some(crate::clock::exact_duration(timeout).into());
        self
    }

    /// Keep retrying the job for at most this long after dispatch, however many runs that takes.
    #[must_use]
    pub fn retry_for(mut self, lifetime: impl Into<ZonedDateTimeArithmetic>) -> Self {
        self.retry_for = Some(crate::clock::exact_duration(lifetime).into());
        self
    }

    /// Hold each dispatch this long, and run only the latest dispatch with the same debounce ID.
    #[must_use]
    pub fn debounce_for(mut self, delay: impl Into<ZonedDateTimeArithmetic>) -> Self {
        self.debounce_for = Some(crate::clock::exact_duration(delay).into());
        self
    }

    /// Run a dispatch immediately once the first waiting dispatch has waited this long.
    #[must_use]
    pub fn max_wait(mut self, wait: impl Into<ZonedDateTimeArithmetic>) -> Self {
        self.max_wait = Some(crate::clock::exact_duration(wait).into());
        self
    }

    /// Fail the job for good with a [`MissingModels`](super::MissingModels) error, rather than
    /// delete it, when the row of one of its models is gone.
    ///
    /// Without this option, the worker deletes the job without running it, the jobs after it in a
    /// chain don't run, and a batch counts them as skipped.
    #[must_use]
    pub const fn fail_when_missing_models(mut self) -> Self {
        self.fail_when_missing_models = true;
        self
    }
}

/// A dispatched job's unique ID, which is a time-ordered UUID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct JobId(uuid::Uuid);

impl JobId {
    pub(crate) fn generate() -> Self {
        Self(crate::str::uuid7())
    }

    pub(crate) const fn into_uuid(self) -> uuid::Uuid {
        self.0
    }
}

impl fmt::Display for JobId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.hyphenated().fmt(f)
    }
}

impl FromStr for JobId {
    type Err = ParseIdError;

    fn from_str(id: &str) -> Result<Self, Self::Err> {
        id.parse().map(Self).map_err(ParseIdError)
    }
}

/// The error from parsing text that isn't a UUID as a [`JobId`] or [`BatchId`](super::BatchId).
///
/// ```
/// use laravel::queue::{BatchId, JobId, ParseIdError};
///
/// let error: ParseIdError = "not-an-id".parse::<JobId>().unwrap_err();
/// assert_eq!(error.to_string(), "the ID isn't a UUID");
/// assert!("not-an-id".parse::<BatchId>().is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("the ID isn't a UUID")]
pub struct ParseIdError(
    #[source]
    #[doc(hidden)]
    pub uuid::Error,
);

/// The error for a job that ran longer than its `timeout` and was stopped.
///
/// The attempt counts as a failure, so the worker retries the job while it has tries left.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub struct JobTimedOut {
    after: Duration,
}

impl JobTimedOut {
    pub(crate) const fn new(after: Duration) -> Self {
        Self { after }
    }

    /// How long the attempt was allowed to run.
    #[must_use]
    pub fn after(&self) -> ExactDuration {
        self.after.into()
    }
}

impl fmt::Display for JobTimedOut {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "the job ran longer than its timeout of {}", self.after())
    }
}

/// A return type that a job's `handle` and `failed` methods and a callback's methods support.
///
/// The supported types are `()` and `laravel::Result<()>`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` isn't a job or callback method's return type",
    label = "return `()` or `laravel::Result<()>`",
    note = "`?` converts other errors into a `laravel::Error`, and the method ends with `Ok(())`"
)]
pub trait JobResult: sealed::Result {
    /// Convert the method's return value into a `Result`.
    #[doc(hidden)]
    fn into_result(self) -> Result<()>;
}

impl JobResult for () {
    fn into_result(self) -> Result<()> {
        Ok(())
    }
}

impl JobResult for Result<()> {
    fn into_result(self) -> Result<()> {
        self
    }
}

mod sealed {
    pub trait Result {}
    impl Result for () {}
    impl Result for crate::Result<()> {}
}

/// Restore a job from its data, then return the future that runs it.
type Run = fn(Value, Arc<Attempt>) -> BoxFuture<'static, Result<BoxFuture<'static, Result<()>>>>;
type Failed = for<'a> fn(Value, &'a Error, &'a Attempt) -> BoxFuture<'a, Result<BoxFuture<'a, Result<()>>>>;

/// A job type the queue can run from a payload, registered by [`#[job]`](macro@super::job).
#[doc(hidden)]
#[derive(Debug)]
pub struct __Registration {
    name: &'static str,
    pub(crate) type_name: fn() -> &'static str,
    options: fn() -> JobOptions,
    run: Run,
    failed: Failed,
}

impl __Registration {
    #[must_use]
    pub const fn new<J: Job>() -> Self {
        Self {
            name: J::NAME,
            type_name: std::any::type_name::<J>,
            options: J::options,
            run: run::<J>,
            failed: failed::<J>,
        }
    }
}

impl __Registration {
    pub(crate) fn find(name: &str) -> Result<&'static Self> {
        registry().get(name).copied().ok_or_else(|| {
            crate::error::fail(format!(
                "no job named `{name}` is registered: was it renamed, or removed, after it was dispatched?"
            ))
        })
    }

    pub(crate) const fn name(&self) -> &'static str {
        self.name
    }

    pub(crate) fn options(&self) -> JobOptions {
        (self.options)()
    }

    /// Restore the job from `data`, then return the future that runs it.
    pub(crate) fn run(
        &self,
        data: Value,
        attempt: Arc<Attempt>,
    ) -> BoxFuture<'static, Result<BoxFuture<'static, Result<()>>>> {
        (self.run)(data, attempt)
    }

    /// Restore the job from `data`, then return the future that runs its `failed` hook.
    pub(crate) fn failed<'a>(
        &self,
        data: Value,
        error: &'a Error,
        attempt: &'a Attempt,
    ) -> BoxFuture<'a, Result<BoxFuture<'a, Result<()>>>> {
        (self.failed)(data, error, attempt)
    }
}

inventory::collect!(__Registration);

fn run<J: Job>(data: Value, attempt: Arc<Attempt>) -> BoxFuture<'static, Result<BoxFuture<'static, Result<()>>>> {
    Box::pin(async move {
        let job = restore::<J>(data).await?;

        Ok(Box::pin(async move {
            let middleware = job.middleware();
            let handle = {
                let attempt = Arc::clone(&attempt);
                Box::pin(async move {
                    if let Some(id) = attempt.debounce_id() {
                        super::debounce::running(J::NAME, id).await;
                    }
                    job.handle(&attempt).await
                })
            };

            middleware.run(attempt, handle).await
        }) as BoxFuture<'static, Result<()>>)
    })
}

fn failed<'a, J: Job>(
    data: Value,
    error: &'a Error,
    attempt: &'a Attempt,
) -> BoxFuture<'a, Result<BoxFuture<'a, Result<()>>>> {
    Box::pin(async move {
        let job = restore::<J>(data).await?;

        Ok(Box::pin(job.failed(error, attempt)) as BoxFuture<'a, Result<()>>)
    })
}

pub(crate) async fn restore<J: Job>(data: Value) -> Result<J> {
    J::__restore(data)
        .await
        .map_err(|error| super::queueable::restore_error("job", J::NAME, error))
}

fn registry() -> &'static HashMap<&'static str, &'static __Registration> {
    static REGISTRY: LazyLock<HashMap<&'static str, &'static __Registration>> = LazyLock::new(|| {
        inventory::iter::<__Registration>
            .into_iter()
            .map(|registration| (registration.name, registration))
            .collect()
    });

    &REGISTRY
}

pub(crate) fn check_names() -> Result<(), String> {
    duplicate_names(
        "jobs",
        "#[job(name = \"..\")]",
        inventory::iter::<__Registration>
            .into_iter()
            .map(|registration| (registration.name, (registration.type_name)())),
    )
}

/// Check that no two registered items share a name.
///
/// # Errors
///
/// Returns an error listing every duplicate name and the types that share it.
pub fn duplicate_names<'a>(
    kind: &str,
    rename: &str,
    types: impl Iterator<Item = (&'a str, &'a str)>,
) -> Result<(), String> {
    let mut named: HashMap<&str, Vec<&str>> = HashMap::new();
    for (name, ty) in types {
        named.entry(name).or_default().push(ty);
    }

    let mut duplicates: Vec<_> = named.into_iter().filter(|(_, types)| types.len() > 1).collect();
    duplicates.sort_unstable();
    match duplicates.first() {
        None => Ok(()),
        Some((name, types)) => Err(format!(
            "the {kind} {} are all named `{name}`: give each its own `{rename}`",
            types
                .iter()
                .map(|ty| format!("`{ty}`"))
                .collect::<Vec<_>>()
                .join(" and "),
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn names_shared_by_several_jobs_are_rejected() {
        let rename = "#[job(name = \"..\")]";
        assert_eq!(
            duplicate_names("jobs", rename, [("a", "app::A"), ("b", "app::B")].into_iter()),
            Ok(())
        );

        let error = duplicate_names(
            "jobs",
            rename,
            [("send", "app::Send"), ("ship", "app::Ship"), ("send", "billing::Send")].into_iter(),
        )
        .unwrap_err();
        assert_eq!(
            error,
            "the jobs `app::Send` and `billing::Send` are all named `send`: give each its own `#[job(name = \"..\")]`"
        );
    }
}