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
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;

use futures_util::future::BoxFuture;
use jiff::Timestamp;

use crate::config::DriverSettings;
use crate::config::queue::{ConnectionConfig, CustomConnection};
use crate::container::{Bindings, Container};
use crate::{Error, Result};

/// How often a worker renews the reservation of a job it's running.
pub const HEARTBEAT: Duration = Duration::from_secs(15);

/// How long a reservation lasts without being renewed. A job whose worker stopped renewing it is
/// available to other workers once its reservation lapses.
pub const LEASE: Duration = Duration::from_secs(60);

/// A queue backend, which stores a connection's jobs and hands each one to a worker.
///
/// Laravel includes the `database`, `redis`, `sqs`, and `cloud` drivers. A package adds another
/// driver by implementing this trait and [`ReservedJob`], then registering a named factory with
/// [`Drivers::extend`]:
///
/// ```
/// use std::time::Duration;
///
/// use laravel::queue::{Driver, Reservation, ReservedJob};
///
/// struct BeanstalkdDriver { /* a client */ }
/// struct BeanstalkdJob { /* a reserved job's ID, tube and body */ }
///
/// impl Driver for BeanstalkdDriver {
///     type Job = BeanstalkdJob;
///
///     async fn push(&self, queue: &str, payload: String, delay: Duration) -> laravel::Result<()> {
///         // use queue, put 0 delay ttr payload...
///         # Ok(())
///     }
///
///     async fn reserve(&self, queues: &[String]) -> laravel::Result<Option<BeanstalkdJob>> {
///         // reserve-with-timeout 0 from each tube in turn...
///         # Ok(None)
///     }
///
///     async fn clear(&self, queue: &str) -> laravel::Result<u64> {
///         // delete every job in the tube...
///         # Ok(0)
///     }
/// }
///
/// impl ReservedJob for BeanstalkdJob {
///     fn queue(&self) -> &str { "default" }
///     fn payload(&self) -> &str { "{}" }
///     fn attempts(&self) -> u32 { 1 }
///
///     async fn renew(&self) -> laravel::Result<Reservation> {
///         // touch id...
///         # Ok(Reservation::Held)
///     }
///
///     async fn delete(&self) -> laravel::Result<Reservation> {
///         // delete id...
///         # Ok(Reservation::Held)
///     }
///
///     async fn release(&self, delay: Duration) -> laravel::Result<Reservation> {
///         // release id with the delay...
///         # Ok(Reservation::Held)
///     }
/// }
/// ```
///
/// A driver stores payloads unchanged, and hands each payload to one worker at a time. The
/// worker decides what happens to a job, and asks the reserved job to carry out that decision. A
/// reservation lasts [`LEASE`], and the worker [renews](ReservedJob::renew) it every
/// [`HEARTBEAT`] while the job runs. When a reservation lapses, the job becomes available again,
/// and the next reservation counts as another attempt.
pub trait Driver: Send + Sync + 'static {
    /// A job this driver reserved for a worker.
    type Job: ReservedJob;

    /// Add a job to `queue`, available once `delay` has passed.
    ///
    /// # Errors
    ///
    /// Fails when the job can't be stored.
    fn push(&self, queue: &str, payload: String, delay: Duration) -> impl Future<Output = Result<()>> + Send;

    /// Reserve the next available job for [`LEASE`], from the first of `queues` that has one.
    ///
    /// Returns `None` when none of the queues has a job. This method may wait for a job to arrive,
    /// as a long poll does. When the worker is told to stop, it drops a pending `reserve`. A job
    /// reserved at that moment never runs, and becomes available again once its reservation lapses,
    /// as a stopped worker's job does.
    ///
    /// # Errors
    ///
    /// Fails when the queues can't be read.
    fn reserve(&self, queues: &[String]) -> impl Future<Output = Result<Option<Self::Job>>> + Send;

    /// Delete every job on `queue`, and return the number of jobs deleted, as closely as the backend
    /// can count them.
    ///
    /// # Errors
    ///
    /// Fails when the queue can't be cleared.
    fn clear(&self, queue: &str) -> impl Future<Output = Result<u64>> + Send;

    /// Add several jobs to `queue`, available now, in as few round trips as the backend allows.
    ///
    /// By default, this method [pushes](Self::push) each payload in turn. A driver whose backend
    /// can store many jobs at once overrides this method. The jobs are stored in order, and storing
    /// stops at the first job that fails, so the jobs after it aren't stored.
    ///
    /// # Errors
    ///
    /// Fails when a job can't be stored. The jobs before it may have been stored.
    fn bulk(&self, queue: &str, payloads: Vec<String>) -> impl Future<Output = Result<()>> + Send {
        async move {
            for payload in payloads {
                self.push(queue, payload, Duration::ZERO).await?;
            }

            Ok(())
        }
    }

    /// Count the jobs on `queue` by state, or return `None` when the backend can't count them.
    ///
    /// By default, this method returns `None`.
    ///
    /// # Errors
    ///
    /// Fails when the queue can't be read.
    fn sizes(&self, queue: &str) -> impl Future<Output = Result<Option<QueueSizes>>> + Send {
        let _ = queue;
        async { Ok(None) }
    }
}

/// How many jobs a queue holds in each state, as
/// [`QueueManager::sizes`](super::QueueManager::sizes) reports them.
///
/// A driver builds `QueueSizes` from its defaults, so that fields added later don't break the
/// driver:
///
/// ```
/// use laravel::queue::QueueSizes;
///
/// let sizes = QueueSizes {
///     pending: 12,
///     reserved: 2,
///     ..QueueSizes::default()
/// };
///
/// assert_eq!(sizes.total(), 14);
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct QueueSizes {
    /// The jobs a worker can take now, including jobs whose reservation lapsed.
    pub pending: u64,
    /// The jobs waiting out a delay from their dispatch or a release.
    pub delayed: u64,
    /// The jobs a worker has reserved and is running.
    pub reserved: u64,
    /// When the next pending job was dispatched, or `None` if the backend doesn't know.
    pub oldest_pending: Option<Timestamp>,
    /// Whether the backend only estimates the counts, as SQS does.
    pub approximate: bool,
}

impl QueueSizes {
    /// The number of jobs on the queue, counting pending, delayed, and reserved jobs.
    #[must_use]
    pub const fn total(&self) -> u64 {
        self.pending.saturating_add(self.delayed).saturating_add(self.reserved)
    }
}

/// One reservation of a job, which a worker runs and then settles.
///
/// When the reservation has lapsed and another worker has taken the job, `renew`, `delete`, and
/// `release` return [`Reservation::Lost`], and `fail` returns [`Failed::Lost`]. The worker then
/// leaves the job alone.
pub trait ReservedJob: Send + Sync + 'static {
    /// The queue the job was reserved from.
    fn queue(&self) -> &str;

    /// The payload, unchanged from when it was pushed.
    fn payload(&self) -> &str;

    /// How many times the job has been reserved, including this time.
    ///
    /// The count is the run's number, starting at 1. Releases, retries, and reservations that lapsed
    /// all count.
    fn attempts(&self) -> u32;

    /// Extend the reservation to [`LEASE`] from now, and return whether the job is still this
    /// worker's.
    ///
    /// # Errors
    ///
    /// Fails when the backend can't be reached.
    fn renew(&self) -> impl Future<Output = Result<Reservation>> + Send;

    /// Remove the job, and return whether it was still this worker's.
    ///
    /// # Errors
    ///
    /// Fails when the backend can't be reached.
    fn delete(&self) -> impl Future<Output = Result<Reservation>> + Send;

    /// Put the job back on its queue to become available after `delay`, and return whether it was
    /// still this worker's.
    ///
    /// The released job keeps its identity and its count of attempts.
    ///
    /// # Errors
    ///
    /// Fails when the backend can't be reached.
    fn release(&self, delay: Duration) -> impl Future<Output = Result<Reservation>> + Send;

    /// Remove a job that failed for good with `error`, and return what became of it.
    ///
    /// By default, this method [deletes](Self::delete) the job, and the worker stores it with the
    /// application's failed jobs. A driver whose backend keeps failed jobs itself, such as the Laravel
    /// Cloud driver, records the failure there and returns [`Failed::Kept`].
    ///
    /// # Errors
    ///
    /// Fails when the backend can't be reached.
    fn fail(&self, error: &Error) -> impl Future<Output = Result<Failed>> + Send {
        let _ = error;
        async move {
            Ok(match self.delete().await? {
                Reservation::Held => Failed::Removed,
                Reservation::Lost => Failed::Lost,
            })
        }
    }
}

/// Whether a job was still a worker's when the worker renewed, deleted, or released it, as
/// [`ReservedJob`] reports it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reservation {
    /// The job was still this worker's, so the change took effect.
    Held,
    /// The reservation lapsed and another worker took the job, so this worker leaves it alone.
    Lost,
}

#[cfg(any(feature = "database", feature = "redis", feature = "sqs"))]
impl Reservation {
    pub(crate) const fn held_if(held: bool) -> Self {
        if held { Self::Held } else { Self::Lost }
    }
}

/// What became of a job that failed for good, as [`ReservedJob::fail`] reports it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Failed {
    /// The job was removed, and the worker stores it with the application's failed jobs.
    Removed,
    /// The job was removed, and the driver kept the failure itself.
    Kept,
    /// The reservation lapsed and another worker took the job, so this worker leaves it alone.
    Lost,
}

pub trait ErasedDriver: Send + Sync {
    fn push<'a>(&'a self, queue: &'a str, payload: String, delay: Duration) -> BoxFuture<'a, Result<()>>;
    fn reserve<'a>(&'a self, queues: &'a [String]) -> BoxFuture<'a, Result<Option<Arc<dyn ErasedJob>>>>;
    fn clear<'a>(&'a self, queue: &'a str) -> BoxFuture<'a, Result<u64>>;
    fn bulk<'a>(&'a self, queue: &'a str, payloads: Vec<String>) -> BoxFuture<'a, Result<()>>;
    fn sizes<'a>(&'a self, queue: &'a str) -> BoxFuture<'a, Result<Option<QueueSizes>>>;
}

impl<D: Driver> ErasedDriver for D {
    fn push<'a>(&'a self, queue: &'a str, payload: String, delay: Duration) -> BoxFuture<'a, Result<()>> {
        Box::pin(Driver::push(self, queue, payload, delay))
    }

    fn reserve<'a>(&'a self, queues: &'a [String]) -> BoxFuture<'a, Result<Option<Arc<dyn ErasedJob>>>> {
        Box::pin(async move {
            let job = Driver::reserve(self, queues).await?;
            Ok(job.map(|job| Arc::new(job) as Arc<dyn ErasedJob>))
        })
    }

    fn clear<'a>(&'a self, queue: &'a str) -> BoxFuture<'a, Result<u64>> {
        Box::pin(Driver::clear(self, queue))
    }

    fn bulk<'a>(&'a self, queue: &'a str, payloads: Vec<String>) -> BoxFuture<'a, Result<()>> {
        Box::pin(Driver::bulk(self, queue, payloads))
    }

    fn sizes<'a>(&'a self, queue: &'a str) -> BoxFuture<'a, Result<Option<QueueSizes>>> {
        Box::pin(Driver::sizes(self, queue))
    }
}

pub trait ErasedJob: Send + Sync {
    fn queue(&self) -> &str;
    fn payload(&self) -> &str;
    fn attempts(&self) -> u32;
    fn renew(&self) -> BoxFuture<'_, Result<Reservation>>;
    fn delete(&self) -> BoxFuture<'_, Result<Reservation>>;
    fn release(&self, delay: Duration) -> BoxFuture<'_, Result<Reservation>>;
    fn fail<'a>(&'a self, error: &'a Error) -> BoxFuture<'a, Result<Failed>>;
}

impl<J: ReservedJob> ErasedJob for J {
    fn queue(&self) -> &str {
        ReservedJob::queue(self)
    }

    fn payload(&self) -> &str {
        ReservedJob::payload(self)
    }

    fn attempts(&self) -> u32 {
        ReservedJob::attempts(self)
    }

    fn renew(&self) -> BoxFuture<'_, Result<Reservation>> {
        Box::pin(ReservedJob::renew(self))
    }

    fn delete(&self) -> BoxFuture<'_, Result<Reservation>> {
        Box::pin(ReservedJob::delete(self))
    }

    fn release(&self, delay: Duration) -> BoxFuture<'_, Result<Reservation>> {
        Box::pin(ReservedJob::release(self, delay))
    }

    fn fail<'a>(&'a self, error: &'a Error) -> BoxFuture<'a, Result<Failed>> {
        Box::pin(ReservedJob::fail(self, error))
    }
}

pub(crate) type Factory =
    Arc<dyn Fn(Container, ConnectionDefinition) -> BoxFuture<'static, Result<Arc<dyn ErasedDriver>>> + Send + Sync>;

pub struct Factories(pub(super) HashMap<String, Factory>);

impl std::fmt::Debug for Factories {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.debug_struct("Factories").finish_non_exhaustive()
    }
}

/// Queue driver factories, configured before the application boots.
///
/// A connection configured with [`ConnectionConfig::custom`] names its driver. The driver's
/// factory creates the connection's driver the first time a job is pushed to the connection or a
/// worker starts working it. A later registration replaces an earlier one with the same name,
/// including the built-in `database`, `redis`, `sqs`, and `cloud` drivers.
///
/// ```
/// use laravel::Application;
/// use laravel::config::queue::ConnectionConfig;
/// # use std::time::Duration;
/// # struct BeanstalkdDriver;
/// # impl BeanstalkdDriver { async fn connect(host: &str) -> laravel::Result<Self> { Ok(Self) } }
/// # struct BeanstalkdJob;
/// # impl laravel::queue::ReservedJob for BeanstalkdJob {
/// #     fn queue(&self) -> &str { "default" }
/// #     fn payload(&self) -> &str { "{}" }
/// #     fn attempts(&self) -> u32 { 1 }
/// #     async fn renew(&self) -> laravel::Result<laravel::queue::Reservation> { Ok(laravel::queue::Reservation::Held) }
/// #     async fn delete(&self) -> laravel::Result<laravel::queue::Reservation> { Ok(laravel::queue::Reservation::Held) }
/// #     async fn release(&self, _: Duration) -> laravel::Result<laravel::queue::Reservation> { Ok(laravel::queue::Reservation::Held) }
/// # }
/// # impl laravel::queue::Driver for BeanstalkdDriver {
/// #     type Job = BeanstalkdJob;
/// #     async fn push(&self, _: &str, _: String, _: Duration) -> laravel::Result<()> { Ok(()) }
/// #     async fn reserve(&self, _: &[String]) -> laravel::Result<Option<BeanstalkdJob>> { Ok(None) }
/// #     async fn clear(&self, _: &str) -> laravel::Result<u64> { Ok(0) }
/// # }
///
/// Application::configure()
///     .with_config(|config, _| {
///         config.queue.add_connection("beanstalkd", ConnectionConfig::custom("beanstalkd"));
///     })
///     .with_services(|app| {
///         app.queue().extend("beanstalkd", |_app, _definition| {
///             BeanstalkdDriver::connect("127.0.0.1:11300")
///         });
///     });
/// ```
///
/// The factory runs once for each connection that uses the driver, and receives that connection's
/// [`ConnectionDefinition`]. To use one driver differently in several connections, give each
/// connection its own [settings](CustomConnection::settings), and read them in the factory with
/// [`ConnectionDefinition::settings`].
#[derive(Default)]
pub struct Drivers {
    factories: HashMap<String, Factory>,
}

impl fmt::Debug for Drivers {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut names: Vec<_> = self.factories.keys().collect();
        names.sort();
        f.debug_struct("Drivers").field("drivers", &names).finish()
    }
}

impl Drivers {
    /// Register a driver factory under a case-insensitive name, and return `self` for more
    /// registrations.
    ///
    /// The factory replaces any factory already registered under the name. It receives the
    /// container, with the final configuration and asynchronous service resolution, and the
    /// definition of the connection it creates a driver for. The factory runs in its own context, as
    /// a service's factory does. If the factory fails or panics, the push or worker that needed the
    /// connection fails, and the next push or worker calls the factory again.
    pub fn extend<D, F, Fut>(&mut self, name: &str, factory: F) -> &mut Self
    where
        D: Driver,
        F: Fn(Container, ConnectionDefinition) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<D>> + Send + 'static,
    {
        let factory = Arc::new(factory);
        self.factories.insert(
            name.to_ascii_lowercase(),
            Arc::new(move |app, definition| {
                let factory = Arc::clone(&factory);
                Box::pin(async move { Ok(Arc::new(factory(app, definition).await?) as Arc<dyn ErasedDriver>) })
            }),
        );
        self
    }

    #[doc(hidden)]
    pub fn register(self, app: &Bindings) -> Result<Factories, String> {
        for (name, connection) in &app.config().queue.connections {
            if let ConnectionConfig::Custom(connection) = connection
                && !self.factories.contains_key(&connection.driver.to_ascii_lowercase())
            {
                return Err(format!(
                    "queue connection `{name}` uses the driver `{}`, which isn't registered",
                    connection.driver
                ));
            }
        }

        Ok(Factories(self.factories))
    }
}

/// The name and configuration of the connection that a driver's factory creates a driver for.
#[derive(Debug, Clone)]
pub struct ConnectionDefinition {
    name: String,
    config: ConnectionConfig,
}

impl ConnectionDefinition {
    pub(super) fn new(name: &str, config: ConnectionConfig) -> Self {
        Self {
            name: name.to_owned(),
            config,
        }
    }

    /// The connection's name, as configured.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The connection's configuration, such as a built-in driver's settings when an application
    /// replaced that driver's factory.
    #[must_use]
    pub const fn config(&self) -> &ConnectionConfig {
        &self.config
    }

    /// The connection's own settings, as the driver's own type.
    ///
    /// The settings are the value given with [`CustomConnection::settings`].
    ///
    /// # Errors
    ///
    /// Fails when the connection has no settings, or when the settings are of another type.
    pub fn settings<T: 'static>(&self) -> Result<&T> {
        let settings = match &self.config {
            ConnectionConfig::Custom(CustomConnection { settings, .. }) => settings.as_ref(),
            _ => None,
        };

        DriverSettings::downcast(settings, format_args!("queue connection `{}`", self.name))
    }
}