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
use super::QueueManagerInternals as _;
use std::future::IntoFuture;
use std::panic::Location;
use std::sync::Arc;
use std::time::Duration;

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

use super::batch::{BatchId, BatchSpec};
use super::callback::{ChainCatch, EncodedCallback, Point};
use super::dispatch::{own_queue, send};
use super::fake::Dispatched;
use super::payload::Payload;
use super::queueable::ModelRows;
use super::{Job, JobId, QueueManager};
use crate::context::{Context, Internals, Values};
use crate::time::Moment;
use crate::{Error, Result};

/// A job encoded for its payload, with its ID, name, and data.
///
/// The ID is chosen when the job is encoded, so a job that waits in a chain or a batch already
/// has its ID before it's dispatched.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EncodedJob {
    pub(crate) id: JobId,
    pub(crate) job: String,
    pub(crate) data: Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) debounce_id: Option<String>,
    #[serde(skip)]
    pub(crate) dispatched: Dispatched,
}

impl EncodedJob {
    /// Encode `job` into a storable payload.
    ///
    /// # Errors
    ///
    /// Fails when encoding the job fails.
    #[expect(
        clippy::needless_pass_by_value,
        reason = "dispatch takes the job, and only its payload outlives it"
    )]
    pub fn new<J: Job>(job: J) -> Result<Self> {
        Self::from_ref(&job)
    }

    /// Encode a borrowed `job` into a storable payload.
    ///
    /// # Errors
    ///
    /// Fails when encoding the job fails.
    pub fn from_ref<J: Job>(job: &J) -> Result<Self> {
        let debounce_id = J::options().debounce_for.map(|_| job.debounce_id());
        let mut rows = ModelRows::new();
        let data = super::queueable::store("job", J::NAME, job, &mut rows)?;

        Ok(Self {
            id: JobId::generate(),
            job: J::NAME.to_owned(),
            data,
            debounce_id,
            dispatched: Dispatched::new(rows),
        })
    }
}

/// A step that waits in a chain for its turn.
///
/// A step is either a job or a batch. The chain continues after a batch once all of the batch's
/// jobs have run.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Link {
    Job(EncodedJob),
    Batch { batch: Box<BatchSpec> },
}

impl Link {
    pub(crate) fn new<J: Job>(job: J) -> Result<Self> {
        EncodedJob::new(job).map(Self::Job)
    }

    pub(crate) fn name(&self) -> &str {
        match self {
            Self::Job(job) => &job.job,
            Self::Batch { .. } => "batch",
        }
    }
}

/// One or more jobs to add to a chain, in order.
///
/// The jobs are a job, a tuple of jobs of any types, an iterable of jobs of one type, or a
/// batch. An iterable is consumed and encoded immediately. [`queue::chain`](super::chain),
/// [`PendingChain::then`], [`Attempt::prepend_to_chain`](super::Attempt::prepend_to_chain), and
/// [`Attempt::append_to_chain`](super::Attempt::append_to_chain) all accept this trait. A
/// generic helper forwards the inferred `Kind` with a bound such as `impl IntoJobs<Kind>`.
///
/// ```no_run
/// # #[derive(laravel::queue::Queueable)] pub struct ShipOrder { pub id: i64 }
/// # #[laravel::queue::job] impl ShipOrder { async fn handle(self) {} }
/// # #[derive(laravel::queue::Queueable)] pub struct RecordShipment { pub id: i64 }
/// # #[laravel::queue::job] impl RecordShipment { async fn handle(self) {} }
/// # #[derive(laravel::queue::Queueable)] pub struct NotifyBuyer { pub id: i64 }
/// # #[laravel::queue::job] impl NotifyBuyer { async fn handle(self) {} }
/// use laravel::queue;
///
/// # async fn example(id: i64, buyers: Vec<i64>) -> laravel::Result<()> {
/// queue::chain((ShipOrder { id }, RecordShipment { id }))
///     .then(buyers.into_iter().map(|id| NotifyBuyer { id }))
///     .await?;
/// # Ok(()) }
/// ```
pub trait IntoJobs<Kind = ()>: sealed::Sealed<Kind> {
    /// Encode the jobs, in order.
    #[doc(hidden)]
    fn into_links(self) -> Result<Vec<Link>>;
}

impl<J: Job> sealed::Sealed for J {}

impl<J: Job> IntoJobs for J {
    fn into_links(self) -> Result<Vec<Link>> {
        Ok(vec![Link::new(self)?])
    }
}

/// Distinguishes iterable inputs from single jobs during type inference.
#[doc(hidden)]
#[derive(Debug)]
pub enum Iterable {}

impl<I: IntoIterator<Item: Job>> sealed::Sealed<Iterable> for I {}

impl<I: IntoIterator<Item: Job>> IntoJobs<Iterable> for I {
    fn into_links(self) -> Result<Vec<Link>> {
        self.into_iter().map(Link::new).collect()
    }
}

macro_rules! tuple_jobs {
    ($($name:ident),+) => {
        impl<$($name: Job),+> sealed::Sealed for ($($name,)+) {}

        impl<$($name: Job),+> IntoJobs for ($($name,)+) {
            #[expect(non_snake_case, reason = "the bindings reuse the type parameters' names")]
            fn into_links(self) -> Result<Vec<Link>> {
                let ($($name,)+) = self;
                Ok(vec![$(Link::new($name)?),+])
            }
        }
    };
}

tuple_jobs!(A);
tuple_jobs!(A, B);
tuple_jobs!(A, B, C);
tuple_jobs!(A, B, C, D);
tuple_jobs!(A, B, C, D, E);
tuple_jobs!(A, B, C, D, E, F);
tuple_jobs!(A, B, C, D, E, F, G);
tuple_jobs!(A, B, C, D, E, F, G, H);
tuple_jobs!(A, B, C, D, E, F, G, H, I);
tuple_jobs!(A, B, C, D, E, F, G, H, I, K);
tuple_jobs!(A, B, C, D, E, F, G, H, I, K, L);
tuple_jobs!(A, B, C, D, E, F, G, H, I, K, L, M);

pub(super) mod sealed {
    pub trait Sealed<Kind = ()> {}
}

/// The rest of a job's chain, kept in the job's payload.
///
/// The chain holds the jobs still to run, the connection and queue they go to, and the
/// callbacks to call if one of the jobs fails for good.
#[doc(hidden)]
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Chain {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub jobs: Vec<Link>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) connection: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) queue: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) catch: Vec<EncodedCallback>,
}

impl Chain {
    pub(crate) fn is_empty(&self) -> bool {
        *self == Self::default()
    }

    pub(crate) async fn dispatch(
        self,
        job: EncodedJob,
        context: &Context,
        values: &Values,
        delay: Option<Duration>,
        member_of: Option<BatchId>,
    ) -> Result<JobId> {
        let manager = QueueManager::of(context.services());
        let (payload, connection, queue) = self.into_payload(&manager, job, values, member_of)?;
        let id = payload.id;

        send(manager, payload, connection, queue, delay).await?;
        Ok(id)
    }

    fn into_payload(
        self,
        manager: &QueueManager,
        job: EncodedJob,
        values: &Values,
        member_of: Option<BatchId>,
    ) -> Result<(Payload, String, String)> {
        let (connection, queue) = self.route(manager, &job.job)?;
        let mut payload = Payload::new(job, values);
        payload.batch = member_of;
        payload.chain = self;

        Ok((payload, connection, queue))
    }

    pub(crate) fn into_bulk_payload(
        mut self,
        manager: &QueueManager,
        values: &Values,
        member_of: Option<BatchId>,
    ) -> Result<Result<(Payload, String, String), Self>> {
        if self.jobs.is_empty() {
            return Ok(Err(self));
        }
        let job = match self.jobs.remove(0) {
            Link::Job(job) if job.debounce_id.is_none() => job,
            link => {
                self.jobs.insert(0, link);
                return Ok(Err(self));
            }
        };
        let (connection, _) = self.route(manager, &job.job)?;
        if manager.runs_inline(&connection)? {
            self.jobs.insert(0, Link::Job(job));
            return Ok(Err(self));
        }

        self.into_payload(manager, job, values, member_of).map(Ok)
    }

    pub(crate) fn dispatch_next(
        mut self,
        context: &Context,
        values: Arc<Values>,
        member_of: Option<BatchId>,
    ) -> BoxFuture<'static, Result<()>> {
        let context = context.clone();

        Box::pin(async move {
            if self.jobs.is_empty() {
                return Ok(());
            }

            match self.jobs.remove(0) {
                Link::Job(job) => self.dispatch(job, &context, &values, None, member_of).await.map(drop),
                Link::Batch { batch } => batch.dispatch(context, values, Some((self, member_of))).await.map(drop),
            }
        })
    }

    pub(crate) async fn call_catch(&self, error: &Error, context: &Context) {
        for callback in &self.catch {
            callback.call(Point::Catch(None, error), context).await;
        }
    }

    pub(crate) fn member_ids(&self) -> impl Iterator<Item = uuid::Uuid> + '_ {
        self.jobs.iter().map(|link| match link {
            Link::Job(job) => job.id.into_uuid(),
            Link::Batch { batch } => batch.id.into_uuid(),
        })
    }

    pub(crate) fn route(&self, manager: &QueueManager, job: &str) -> Result<(String, String)> {
        let queue = self.queue.as_deref().or_else(|| own_queue(job));

        manager.route(self.connection.as_deref(), queue)
    }
}

/// The first step dispatched by a chain.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChainDispatched {
    /// The chain started with this job.
    Job(JobId),
    /// The chain started with this batch.
    Batch(BatchId),
}

/// A chain of jobs on its way to the queue.
///
/// Await the chain to dispatch its first step. Awaiting returns a [`ChainDispatched`] for that
/// step. The errors and panics of awaiting are listed on [`queue::chain`](super::chain).
///
/// The queue dispatches each job once the job before it succeeds or deletes itself. A job that
/// releases itself runs again before the chain continues. A job that fails for good stops the
/// chain, and the worker that ran the job calls the chain's [`catch`](Self::catch) callbacks
/// with the error. Inside a database transaction, the chain waits for the transaction to commit,
/// as a [`dispatch`](super::dispatch) does.
///
/// ```no_run
/// # #[derive(laravel::queue::Queueable)] pub struct ProcessPodcast { pub podcast_id: i64 }
/// # #[laravel::queue::job] impl ProcessPodcast { async fn handle(self) {} }
/// # #[derive(laravel::queue::Queueable)] pub struct OptimizePodcast { pub podcast_id: i64 }
/// # #[laravel::queue::job] impl OptimizePodcast { async fn handle(self) {} }
/// # #[derive(laravel::queue::Queueable)] pub struct ReleasePodcast { pub podcast_id: i64 }
/// # #[laravel::queue::job] impl ReleasePodcast { async fn handle(self) {} }
/// # #[derive(laravel::queue::Queueable)] pub struct PodcastFailed { pub podcast_id: i64 }
/// # #[laravel::queue::callback] impl PodcastFailed { async fn catch(self, error: &laravel::Error) {} }
/// use laravel::queue;
///
/// # async fn example(podcast_id: i64) -> laravel::Result<()> {
/// queue::chain((
///     ProcessPodcast { podcast_id },
///     OptimizePodcast { podcast_id },
/// ))
///     .then(ReleasePodcast { podcast_id })
///     .on_queue("podcasts")
///     .catch(PodcastFailed { podcast_id })
///     .await?;
/// # Ok(()) }
/// ```
#[derive(Debug)]
#[must_use = "a chain is dispatched only when it's awaited"]
pub struct PendingChain {
    chain: Result<Chain>,
    delay: Option<Moment>,
    caller: &'static Location<'static>,
}

impl PendingChain {
    #[track_caller]
    pub(super) fn new<Kind>(jobs: impl IntoJobs<Kind>) -> Self {
        let chain = Self {
            chain: Ok(Chain::default()),
            delay: None,
            caller: Location::caller(),
        };

        chain.then(jobs)
    }

    /// Run `jobs` in order once the steps before them have succeeded.
    ///
    /// `jobs` is a job, a tuple of jobs, an iterable of jobs of one type, or a batch.
    pub fn then<Kind>(mut self, jobs: impl IntoJobs<Kind>) -> Self {
        self.chain = self.chain.and_then(|mut chain| {
            chain.jobs.extend(jobs.into_links()?);
            Ok(chain)
        });
        self
    }

    /// Push every job in the chain to this connection rather than the default one.
    pub fn on_connection(mut self, connection: impl Into<String>) -> Self {
        if let Ok(chain) = &mut self.chain {
            chain.connection = Some(connection.into());
        }
        self
    }

    /// Push every job in the chain to this queue, rather than the queue that each job's options or
    /// connection choose.
    pub fn on_queue(mut self, queue: impl Into<String>) -> Self {
        if let Ok(chain) = &mut self.chain {
            chain.queue = Some(queue.into());
        }
        self
    }

    /// Delay the chain's first job by a span such as `10.minutes()`, or until a point in time.
    ///
    /// The later jobs run as soon as the job before them finishes. Awaiting a delayed chain fails
    /// when the chain starts with a batch, and awaiting a batch fails when one of its jobs is a
    /// delayed chain.
    pub fn delay(mut self, delay: impl Into<Moment>) -> Self {
        self.delay = Some(delay.into());
        self
    }

    /// Call `callback`'s `catch` method with the error if a job in the chain fails for good.
    ///
    /// The chain stops after the failure, and the worker that ran the failed job calls the
    /// callback. Each call adds another callback.
    pub fn catch(mut self, callback: impl ChainCatch) -> Self {
        self.chain = self.chain.and_then(|mut chain| {
            chain.catch.push(EncodedCallback::new(callback)?);
            Ok(chain)
        });
        self
    }

    pub(super) fn into_chain(self) -> Result<Chain> {
        let chain = self.chain?;
        if chain.jobs.is_empty() {
            return Err(crate::error::fail("the chain has no jobs to dispatch"));
        }
        if self.delay.is_some() {
            return Err(crate::error::fail("a chain in a batch can't have a delay"));
        }

        Ok(chain)
    }

    async fn send(self) -> Result<ChainDispatched> {
        let mut rest = self.chain?;
        let context = Context::expect_for("laravel::queue::chain()", self.caller);
        let delay = self.delay.map(|delay| delay.remaining());
        if rest.jobs.is_empty() {
            return Err(crate::error::fail("the chain has no jobs to dispatch"));
        }
        let first = rest.jobs.remove(0);

        match first {
            Link::Job(first) => rest
                .dispatch(first, &context, &context.values(), delay, None)
                .await
                .map(ChainDispatched::Job),
            Link::Batch { batch } => {
                if delay.is_some() {
                    return Err(crate::error::fail("a chain starting with a batch can't have a delay"));
                }

                batch
                    .dispatch_after_commit(context, Some((rest, None)))
                    .await
                    .map(ChainDispatched::Batch)
            }
        }
    }
}

impl IntoFuture for PendingChain {
    type Output = Result<ChainDispatched>;
    type IntoFuture = BoxFuture<'static, Result<ChainDispatched>>;

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