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
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//! `laravel::queue`, which the `laravel-rust` package documents.

mod attempt;
mod batch;
mod callback;
mod chain;
#[cfg(feature = "sqs")]
pub(crate) mod cloud;
#[doc(hidden)]
pub mod commands;
#[cfg(feature = "database")]
mod database;
mod debounce;
#[doc(hidden)]
pub mod delivery;
mod dispatch;
mod driver;
pub mod events;
mod fake;
mod job;
mod middleware;
#[cfg(feature = "database")]
#[doc(hidden)]
pub mod models;
mod payload;
mod queueable;
#[cfg(feature = "redis")]
mod redis;
#[cfg(feature = "sqs")]
mod sqs;
mod worker;

#[cfg(feature = "redis")]
use crate::container::ContainerInternals as _;
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;

use crate::Result;
use crate::config::queue::{ConnectionConfig, FailedJobs, Queue as QueueConfig};
use crate::container::{self, Container, Inject, LazyDriver, Services};

pub use self::attempt::Attempt;
pub use self::batch::{Batch, BatchId, IntoBatchJob, IntoBatchJobs, PendingBatch, cancel_batch, find_batch};
#[doc(hidden)]
pub use self::callback::__CallbackRegistration;
pub use self::callback::{Callback, Catch, ChainCatch, Finally, Then};
#[doc(hidden)]
pub use self::callback::{EncodedCallback, Point};
pub use self::chain::{ChainDispatched, IntoJobs, PendingChain};
#[doc(hidden)]
pub use self::chain::{EncodedJob, Link};
#[doc(hidden)]
pub use self::delivery::Placement;
#[doc(hidden)]
pub use self::dispatch::dispatch_borrowed;
pub use self::dispatch::{PendingBulk, PendingDispatch};
pub use self::driver::{
    ConnectionDefinition, Driver, Drivers, Failed, HEARTBEAT, LEASE, QueueSizes, Reservation, ReservedJob,
};
#[doc(hidden)]
pub use self::driver::{ErasedDriver, ErasedJob, Factories};
pub use self::fake::{CallbackList, JobList, JobTypes, Pushed, PushedBatch, QueueFake, fake};
#[doc(hidden)]
pub use self::job::__Registration;
#[doc(hidden)]
pub use self::job::duplicate_names;
pub use self::job::{Job, JobId, JobOptions, JobResult, JobTimedOut, ParseIdError};
pub use self::middleware::{IntoMiddleware, Middleware, MiddlewareGroup, Next};
#[doc(hidden)]
pub use self::payload::{Outcome, Payload, Place, Ran};
pub use self::queueable::{MissingModels, Queueable};
#[doc(hidden)]
pub use self::queueable::{restore_error, store as store_queueable};

/// What `#[derive(Queueable)]` expands to.
#[doc(hidden)]
pub mod __queueable {
    #[cfg(feature = "database")]
    pub(crate) use super::queueable::Group;
    #[doc(hidden)]
    pub use super::queueable::serde_queueable;
    pub use super::queueable::{
        __assemble, __default, __default_with, __restore, __undecodable, Collect, DefaultKind, DefaultWith, Field,
        Fields, Map, ModelField, ModelKind, ModelRows, Pending, SerdeField, SerdeKind, Value,
    };
}

/// Make a [`Queueable`](derive@Queueable) struct a queued job.
///
/// Place the attribute on the `impl` block that holds the job's async `handle` method. `handle`
/// consumes `self` and may take [`Inject<T>`](crate::container::Inject) services,
/// [`Section<T>`](struct@crate::config::Section) config sections, and an [`&Attempt`](Attempt), in
/// any order. It returns `()` or `laravel::Result<()>`.
///
/// The `impl` block may also define these optional methods:
///
/// - An async `failed` method, which runs once after the job has failed for good. It receives the
///   error as an `&laravel::Error` argument and may take the same kinds of arguments as `handle`.
/// - A `middleware` method that takes `&self` and returns the [`Middleware`] that wraps `handle`
///   on each attempt. It may return one middleware, a tuple of middleware, an `Option`, or a
///   [`MiddlewareGroup`].
/// - A `debounce_id` method that takes `&self` and returns the job's [debounce
///   ID](Job::debounce_id) as any type that implements `Display`. The job also needs the
///   `debounce_for` option.
///
/// The attribute implements [`Job`], adds `dispatch` and `dispatch_sync` methods, and registers
/// the job by name so that a worker can find it. Each of the following options is optional:
///
/// | Option | Meaning |
/// | --- | --- |
/// | `name = "podcasts.process"` | The name the job is stored under. Defaults to the type's path |
/// | `queue = "podcasts"` | The queue the job joins when its dispatch doesn't name another |
/// | `tries = 3` | How many times the job may run, counting releases |
/// | `max_errors = 2` | How many of the job's runs may fail |
/// | `backoff = 30.seconds()` or `backoff = [10.seconds(), 1.minutes()]` | How long to wait before each retry |
/// | `timeout = 2.minutes()` | How long one attempt may run |
/// | `retry_for = 1.hours()` | How long after dispatch the job may be retried. Replaces the `tries` limit |
/// | `debounce_for = 30.seconds()` | How long each dispatch waits. Only the latest dispatch with the same debounce ID runs |
/// | `max_wait = 2.minutes()` | How long later dispatches may keep replacing earlier ones before one runs. Requires `debounce_for` |
/// | `fail_when_missing_models` | Fail the job for good, rather than delete it, when one of its models' rows is gone |
///
/// Each duration is a span such as `30.seconds()`, or any other value that converts into
/// `jiff::ZonedDateTimeArithmetic`. The attribute imports [`ToSpan`](crate::time::ToSpan) so that
/// these spans compile without another `use`.
///
/// ```no_run
/// use laravel::container::Inject;
/// use laravel::queue::{Attempt, job};
/// # pub struct Invoices;
/// # impl Invoices { async fn send(&self, id: i64) -> laravel::Result<()> { Ok(()) } }
/// # impl Invoices { async fn alert(&self, error: &laravel::Error) {} }
///
/// #[derive(laravel::queue::Queueable)]
/// pub struct SendInvoice {
///     pub invoice_id: i64,
/// }
///
/// #[job(name = "invoices.send", tries = 5, backoff = 1.minutes())]
/// impl SendInvoice {
///     async fn handle(self, invoices: Inject<Invoices>, attempt: &Attempt) -> laravel::Result<()> {
///         invoices.send(self.invoice_id).await
///     }
///
///     async fn failed(self, error: &laravel::Error, invoices: Inject<Invoices>) {
///         invoices.alert(error).await;
///     }
/// }
/// ```
///
/// ```compile_fail
/// #[derive(laravel::queue::Queueable)]
/// struct Invalid;
/// #[laravel::queue::job(tries = 0)]
/// impl Invalid { async fn handle(self) {} }
/// ```
///
/// ```compile_fail
/// #[derive(laravel::queue::Queueable)]
/// struct WaitsWithoutDebouncing;
/// #[laravel::queue::job(max_wait = 2.minutes())]
/// impl WaitsWithoutDebouncing { async fn handle(self) {} }
/// ```
///
/// ```compile_fail
/// struct NotSerializable;
/// #[laravel::queue::job]
/// impl NotSerializable { async fn handle(self) {} }
/// ```
pub use laravel_rust_queue_macros::job;

/// Turn an async function into a job [`Middleware`] struct with the function's name.
///
/// The function takes `next: Next` and returns `laravel::Result<()>`, usually by returning
/// `next.run().await`, which runs the rest of the job. Before `next`, the function may take
/// [`Inject<T>`](crate::container::Inject) services, [`Section<T>`](struct@crate::config::Section)
/// config sections, and an [`&Attempt`](Attempt), in any order. Any parameters after `next`
/// become the struct's fields, and a job passes their values when it lists the middleware:
///
/// ```no_run
/// use laravel::container::Inject;
/// use laravel::queue::{Attempt, Next, job, middleware};
/// use laravel::time::ToSpan;
/// # pub struct Accounts;
/// # impl Accounts { async fn is_active(&self, id: i64) -> laravel::Result<bool> { Ok(true) } }
///
/// #[middleware]
/// pub async fn skip_inactive(
///     accounts: Inject<Accounts>,
///     attempt: &Attempt,
///     next: Next,
///     account_id: i64,
/// ) -> laravel::Result<()> {
///     if !accounts.is_active(account_id).await? {
///         attempt.delete();
///         return Ok(());
///     }
///
///     next.run().await
/// }
///
/// #[derive(laravel::queue::Queueable)]
/// pub struct SyncContacts {
///     pub account_id: i64,
/// }
///
/// #[job]
/// impl SyncContacts {
///     fn middleware(&self) -> skip_inactive {
///         skip_inactive(self.account_id)
///     }
///
///     async fn handle(self) -> laravel::Result<()> {
///         // ...
///         Ok(())
///     }
/// }
/// ```
pub use laravel_rust_queue_macros::job_middleware as middleware;

/// Make a [`Queueable`](derive@Queueable) struct a batch or chain [`Callback`].
///
/// Place the attribute on the `impl` block that holds the struct's async `then`, `catch`, or
/// `finally` methods. The callback is stored under the type's path, and
/// `#[callback(name = "..")]` stores it under another name.
///
/// A worker calls each method directly, without queueing it, as soon as the batch or chain
/// reaches that method's point. It calls `then` once every job of a batch has succeeded, `catch`
/// when a job fails for good, and `finally` once every job of a batch has run. `then` and
/// `finally` may take the [`&Batch`](Batch), and `catch` may take the `&Batch` and the job's
/// [`&laravel::Error`](crate::Error). Each method may also take
/// [`Inject<T>`](crate::container::Inject) services and
/// [`Section<T>`](struct@crate::config::Section) config sections, in any order. A chain calls
/// only `catch` methods that don't take a `&Batch`.
///
/// The worker never retries a callback. It reports the callback's error or panic, and the job
/// keeps the outcome it ended with. If the worker stops before it calls a callback, the callback
/// never runs, so dispatch a job from the callback for work that must happen.
///
/// When the row of one of the callback's models is gone, the worker skips the callback.
/// `#[callback(fail_when_missing_models)]` reports a [`MissingModels`] error instead.
///
/// ```no_run
/// use laravel::container::Inject;
/// use laravel::queue::{Batch, callback};
/// # pub struct Imports;
/// # impl Imports { async fn finish(&self, id: i64, jobs: u64) -> laravel::Result<()> { Ok(()) } }
/// # impl Imports { async fn fail(&self, id: i64, error: String) -> laravel::Result<()> { Ok(()) } }
///
/// #[derive(laravel::queue::Queueable)]
/// pub struct ImportFinished {
///     pub import_id: i64,
/// }
///
/// #[callback]
/// impl ImportFinished {
///     async fn then(self, batch: &Batch, imports: Inject<Imports>) -> laravel::Result<()> {
///         imports.finish(self.import_id, batch.total_jobs()).await
///     }
///
///     async fn catch(self, error: &laravel::Error, imports: Inject<Imports>) -> laravel::Result<()> {
///         imports.fail(self.import_id, error.to_string()).await
///     }
/// }
/// ```
///
/// A chain can't call a `catch` that takes a `&Batch`:
///
/// ```compile_fail
/// # #[derive(laravel::queue::Queueable)] pub struct Ship;
/// # #[laravel::queue::job] impl Ship { async fn handle(self) {} }
/// #[derive(laravel::queue::Queueable)]
/// pub struct BatchOnly;
///
/// #[laravel::queue::callback]
/// impl BatchOnly {
///     async fn catch(self, batch: &laravel::queue::Batch) {}
/// }
///
/// let chain = laravel::queue::chain(Ship).catch(BatchOnly);
/// ```
///
/// For a callback with a single action, place the attribute on an async function instead. The
/// function's owned parameters become arguments that you pass when you construct the callback,
/// and the worker supplies services, config sections, `&Batch`, and `&Error` when it calls the
/// function. A function that takes `&Error` works as a `catch` callback, and any other function
/// works as a `then` or `finally` callback.
///
/// ```no_run
/// use laravel::container::Inject;
/// use laravel::queue::{self, Batch, callback};
/// # pub struct Imports;
/// # impl Imports { async fn finish(&self, id: i64, jobs: u64) -> laravel::Result<()> { Ok(()) } }
/// # #[derive(laravel::queue::Queueable)] struct ImportRow;
/// # #[queue::job] impl ImportRow { async fn handle(self) {} }
///
/// #[callback]
/// async fn finish_import(import_id: i64, batch: &Batch, imports: Inject<Imports>) -> laravel::Result<()> {
///     imports.finish(import_id, batch.total_jobs()).await
/// }
///
/// # async fn example(import_id: i64) -> laravel::Result<()> {
/// queue::batch([ImportRow]).then(finish_import(import_id)).await?;
/// # Ok(()) }
/// ```
pub use laravel_rust_queue_macros::queue_callback as callback;

/// A connection whose driver its factory creates on first use.
type LazyConnection = LazyDriver<ConnectionDefinition, Arc<dyn ErasedDriver>>;

/// The application's queue connections, by name.
///
/// Resolve the manager with [`manager`] or inject it with `Inject<QueueManager>`. The manager
/// creates each connection's driver the first time the connection is used, and keeps the driver
/// for the life of the application.
pub struct QueueManager {
    config: QueueConfig,
    fakes: Arc<fake::Fakes>,
    drivers: Factories,
    created: Mutex<HashMap<String, Arc<LazyConnection>>>,
    services: Container,
    /// Whether the application runs in the `testing` environment, where every job goes to the
    /// default connection.
    testing: bool,
}

/// What Laravel's own crates construct and query on [`QueueManager`].
///
/// The `laravel` crate doesn't export this trait, so applications can't call these methods.
pub trait QueueManagerInternals: Sized {
    /// Build a queue manager from configuration, registered drivers, and the container.
    fn new(config: &QueueConfig, drivers: Factories, services: Container, testing: bool) -> Self;

    /// Resolve the application's registered queue manager.
    fn of(services: &Services) -> Inject<Self>;

    /// Return the connection and queue a job goes to.
    ///
    /// The job goes to `connection`, or to the default connection when it's `None`, and to
    /// `queue`, or to the connection's own queue when it's `None`.
    ///
    /// # Errors
    ///
    /// Fails when the chosen connection isn't defined.
    fn route(&self, connection: Option<&str>, queue: Option<&str>) -> Result<(String, String)>;

    /// Whether a job sent to `connection` runs as soon as it's sent, because it reaches a `sync`
    /// connection.
    ///
    /// # Errors
    ///
    /// Fails when `connection` isn't defined.
    fn runs_inline(&self, connection: &str) -> Result<bool>;
}

impl QueueManagerInternals for QueueManager {
    fn new(config: &QueueConfig, drivers: Factories, services: Container, testing: bool) -> Self {
        Self {
            config: config.clone(),
            testing,
            fakes: Arc::default(),
            drivers,
            created: Mutex::default(),
            services,
        }
    }

    fn of(services: &Services) -> Inject<Self> {
        Inject::from(
            services
                .built()
                .expect("the application registers its queue manager as an instance"),
        )
    }

    fn route(&self, connection: Option<&str>, queue: Option<&str>) -> Result<(String, String)> {
        let connection = connection.unwrap_or(&self.config.default);
        let queue = queue.unwrap_or(self.connection(connection)?.queue());

        Ok((connection.to_owned(), queue.to_owned()))
    }

    fn runs_inline(&self, connection: &str) -> Result<bool> {
        Ok(matches!(
            self.connection(self.target(connection)?)?,
            ConnectionConfig::Sync
        ))
    }
}

impl QueueManager {
    /// The default connection's name, from `config.queue.default`.
    #[must_use]
    pub fn default_connection(&self) -> &str {
        &self.config.default
    }

    /// The names of every connection, sorted.
    #[must_use]
    pub fn connection_names(&self) -> Vec<String> {
        self.config.connections.keys().cloned().collect()
    }

    fn connection(&self, name: &str) -> Result<&ConnectionConfig> {
        self.config
            .connections
            .get(name)
            .ok_or_else(|| crate::error::fail(format!("queue connection `{name}` isn't defined")))
    }

    fn messaging_system(&self, connection: &str) -> Option<&str> {
        match self.connection(connection).ok()? {
            ConnectionConfig::Sqs(_) | ConnectionConfig::Cloud(_) => Some("aws_sqs"),
            config => Some(config.driver()),
        }
    }

    /// The connection that a job sent to `connection` reaches.
    ///
    /// In the `testing` environment, every job reaches the default connection, which is `sync`
    /// unless the test sets `QUEUE_CONNECTION`. Jobs, chains, batches, queued listeners, mail, and
    /// notifications that name their own connection therefore still run inline. The named
    /// connection must still be defined.
    fn target<'a>(&'a self, connection: &'a str) -> Result<&'a str> {
        self.connection(connection)?;

        Ok(if self.testing { &self.config.default } else { connection })
    }

    async fn push(&self, connection: &str, queue: &str, payload: &Payload, delay: Duration) -> Result<()> {
        let connection = self.target(connection)?;
        match self.connection(connection)? {
            ConnectionConfig::Discard => Ok(()),
            ConnectionConfig::Sync => payload.run_once(connection, queue).await,
            _ => {
                self.driver(connection)
                    .await?
                    .push(queue, payload.encode()?, delay)
                    .await
            }
        }
    }

    pub(crate) async fn bulk(&self, connection: &str, queue: &str, payloads: &[Payload]) -> Result<()> {
        let connection = self.target(connection)?;
        if matches!(self.connection(connection)?, ConnectionConfig::Discard) {
            return Ok(());
        }
        let payloads = payloads.iter().map(Payload::encode).collect::<Result<Vec<_>>>()?;

        self.driver(connection).await?.bulk(queue, payloads).await
    }

    /// Count the jobs on a connection's queue by state.
    ///
    /// Returns `None` when the connection's driver can't count its jobs. The `sync` and `discard`
    /// connections keep no jobs, so all their counts are zero. On SQS, the counts are estimates,
    /// `oldest_pending` is `None`, and a released job counts as reserved until its delay passes.
    ///
    /// ```no_run
    /// # async fn example() -> laravel::Result<()> {
    /// let manager = laravel::queue::manager();
    ///
    /// if let Some(sizes) = manager.sizes(manager.default_connection(), "podcasts").await? {
    ///     println!("{} waiting, {} running", sizes.pending, sizes.reserved);
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// # Errors
    ///
    /// Fails when the connection isn't defined, its driver can't be created, or its queue can't
    /// be read.
    pub async fn sizes(&self, connection: &str, queue: &str) -> Result<Option<QueueSizes>> {
        if matches!(
            self.connection(connection)?,
            ConnectionConfig::Sync | ConnectionConfig::Discard
        ) {
            return Ok(Some(QueueSizes::default()));
        }

        self.driver(connection).await?.sizes(queue).await
    }

    async fn driver(&self, name: &str) -> Result<Arc<dyn ErasedDriver>> {
        let config = self.connection(name)?;
        if matches!(config, ConnectionConfig::Sync | ConnectionConfig::Discard) {
            return Err(crate::error::fail(format!(
                "queue connection `{name}` uses the `{}` driver, which keeps no jobs to work",
                config.driver()
            )));
        }
        let driver = self.created().get(name).cloned();
        let driver = driver.unwrap_or_else(|| {
            let factory = self
                .drivers
                .0
                .get(&config.driver().to_ascii_lowercase())
                .cloned()
                .unwrap_or_else(|| Arc::new(|services, definition| Box::pin(built_in(services, definition))));
            let driver = LazyDriver::new(
                format!("queue connection `{name}`"),
                ConnectionDefinition::new(name, config.clone()),
                factory,
                self.services.clone(),
            );

            Arc::clone(self.created().entry(name.to_owned()).or_insert(Arc::new(driver)))
        });

        driver.get().await
    }

    #[cfg(all(feature = "sqs", feature = "database"))]
    pub(crate) fn cloud(&self) -> Option<&crate::config::queue::CloudQueue> {
        self.config
            .connections
            .values()
            .find_map(|connection| match connection {
                ConnectionConfig::Cloud(cloud) => Some(cloud),
                _ => None,
            })
    }

    fn created(&self) -> MutexGuard<'_, HashMap<String, Arc<LazyConnection>>> {
        self.created.lock().unwrap_or_else(PoisonError::into_inner)
    }

    #[cfg(feature = "database")]
    pub(crate) fn failed(&self) -> Result<Option<database::Failed>> {
        match &self.config.failed {
            FailedJobs::Database(config) => {
                let database = database::manager(&self.services)?;
                Ok(Some(database::Failed::new(&database, config)?))
            }
            FailedJobs::Discard => Ok(None),
            _ => unreachable!("every failed job store the configuration defines is handled above"),
        }
    }

    #[cfg(not(feature = "database"))]
    pub(crate) fn failed(&self) -> Result<Option<std::convert::Infallible>> {
        match &self.config.failed {
            FailedJobs::Database(_) => Err(crate::error::fail(
                "failed jobs are kept in a database table, which needs a database driver feature: \
                 `database-sqlite`, `database-postgres` or `database-mysql`; to discard them, set \
                 `config.queue.failed` to `FailedJobs::Discard`",
            )),
            FailedJobs::Discard => Ok(None),
            _ => unreachable!("every failed job store the configuration defines is handled above"),
        }
    }
}

#[cfg_attr(
    not(any(feature = "database", feature = "redis")),
    expect(unused_variables, reason = "only the database and redis drivers resolve services")
)]
async fn built_in(services: Container, definition: ConnectionDefinition) -> Result<Arc<dyn ErasedDriver>> {
    match definition.config() {
        #[cfg(feature = "database")]
        ConnectionConfig::Database(config) => Ok(Arc::new(database::Jobs::new(database::manager(&services)?, config))),
        #[cfg(not(feature = "database"))]
        ConnectionConfig::Database(_) => Err(crate::error::fail(
            "the database queue needs a database driver feature: `database-sqlite`, `database-postgres` or `database-mysql`",
        )),
        #[cfg(feature = "redis")]
        ConnectionConfig::Redis(config) => {
            let redis = services
                .built::<crate::redis::RedisManager>()
                .ok_or_else(|| crate::error::fail("the Redis queue needs the Redis manager"))?;
            Ok(Arc::new(redis::RedisDriver::new(redis, config)))
        }
        #[cfg(not(feature = "redis"))]
        ConnectionConfig::Redis(_) => Err(crate::error::fail("the `redis` queue driver needs the `redis` feature")),
        #[cfg(feature = "sqs")]
        ConnectionConfig::Sqs(config) => Ok(Arc::new(sqs::SqsDriver(Arc::new(sqs::Sqs::connect(config).await)))),
        #[cfg(feature = "sqs")]
        ConnectionConfig::Cloud(config) => Ok(Arc::new(cloud::CloudDriver::connect(config).await?)),
        #[cfg(not(feature = "sqs"))]
        ConnectionConfig::Sqs(_) | ConnectionConfig::Cloud(_) => Err(crate::error::fail(format!(
            "the `{}` queue driver needs the `sqs` feature",
            definition.config().driver()
        ))),
        ConnectionConfig::Sync | ConnectionConfig::Discard | ConnectionConfig::Custom(_) => {
            Err(crate::error::fail(format!(
                "queue connection `{}` uses the driver `{}`, which isn't registered",
                definition.name(),
                definition.config().driver()
            )))
        }
        _ => unreachable!("every queue connection the configuration defines is handled above"),
    }
}

impl fmt::Debug for QueueManager {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("QueueManager")
            .field("default", &self.config.default)
            .field("connections", &self.connection_names())
            .finish_non_exhaustive()
    }
}

/// Validate the queue configuration and registered job names.
///
/// # Errors
///
/// Returns an error when the default connection isn't defined, a connection is invalid, or two
/// jobs share a name.
pub fn validate(config: &QueueConfig) -> Result<(), String> {
    if !config.connections.contains_key(&config.default) {
        return Err(format!(
            "the default queue connection `{}` isn't defined",
            config.default
        ));
    }

    #[cfg(feature = "database")]
    {
        let mut tables = Vec::new();
        for (name, connection) in &config.connections {
            if let ConnectionConfig::Database(database) = connection {
                tables.push((format!("queue connection `{name}` uses"), &database.table));
            }
        }
        tables.push(("batches use".to_owned(), &config.batches.table));
        tables.push(("batches use".to_owned(), &config.batches.jobs_table));
        if let FailedJobs::Database(failed) = &config.failed {
            tables.push(("failed jobs use".to_owned(), &failed.table));
        }
        for (user, table) in tables {
            if !crate::db::identifier::is_identifier_path(table) {
                return Err(format!(
                    "{user} the table `{table}`, which must be letters, digits and underscores, optionally schema-qualified"
                ));
            }
        }
    }

    job::check_names()?;
    callback::check_names()
}

/// Run `work` once the current database transaction commits, or now outside a transaction, so a
/// worker or a queue fake never sees a job for data that rolled back.
#[doc(hidden)]
pub async fn after_commit<F, Fut>(work: F) -> Result<()>
where
    F: FnOnce() -> Fut + Send + 'static,
    Fut: Future<Output = Result<()>> + Send + 'static,
{
    #[cfg(feature = "database")]
    return crate::db::after_commit(work).await;
    #[cfg(not(feature = "database"))]
    work().await
}

/// Resolve the application's queue manager from its context.
///
/// # Panics
///
/// Panics outside an application context.
#[must_use]
#[track_caller]
pub fn manager() -> Inject<QueueManager> {
    container::built("laravel::queue::manager()")
}

/// Dispatch a job to its queue.
///
/// Await the returned [`PendingDispatch`] to push the job. Before you await it, you may choose
/// the job's connection, queue, and delay. The `dispatch` method that [`#[job]`](macro@job) adds
/// to each job calls this function.
///
/// Awaiting returns the job's [`JobId`]. Inside a database transaction, the job waits for the
/// transaction to commit, and Laravel discards the job if the transaction rolls back.
///
/// # Errors
///
/// Awaiting fails when the connection isn't defined, the job can't be encoded, or the connection
/// can't accept the job. A job on the `sync` connection runs as soon as it's pushed, so awaiting
/// also returns the job's own error.
///
/// # Panics
///
/// Awaiting panics outside a request, a command, or an
/// [`Application::scope`](crate::Application::scope).
#[track_caller]
pub fn dispatch<J: Job>(job: J) -> PendingDispatch<J> {
    PendingDispatch::new(job)
}

/// Chain jobs so that each one runs after the one before it succeeds.
///
/// Await the returned [`PendingChain`] to dispatch the first of `jobs`. Each later job is
/// dispatched once the job before it succeeds. `jobs` is a job, a tuple of jobs of any types, an
/// iterable of jobs of one type, or a batch, and [`then`](PendingChain::then) adds more steps.
///
/// Awaiting returns a [`ChainDispatched`] that identifies the first step. The rest of the chain
/// travels in each job's payload, so the worker that runs a job dispatches the next one. A job
/// may add steps to its chain while it runs, with [`Attempt::prepend_to_chain`] and
/// [`Attempt::append_to_chain`].
///
/// # Errors
///
/// Awaiting fails in the same cases as [`dispatch`]: when the connection isn't defined, a job
/// can't be encoded, or the connection can't accept the first job. It also fails when the chain
/// has no steps, or when a chain that starts with a batch has a delay. A chain that starts with a
/// batch also needs the batches tables.
///
/// On the `sync` connection, each job runs as soon as it's dispatched. Awaiting returns a job's
/// error, but a batch reports its jobs' errors instead, and cancels itself unless it allows
/// failures.
///
/// # Panics
///
/// Awaiting panics outside a request, a command, or an
/// [`Application::scope`](crate::Application::scope).
#[track_caller]
pub fn chain<Kind>(jobs: impl IntoJobs<Kind>) -> PendingChain {
    PendingChain::new(jobs)
}

/// Push several jobs at once.
///
/// Await the returned [`PendingBulk`] to push `jobs` in order, in as few round trips as the
/// connection's driver allows. `jobs` is a job, a tuple of jobs of any types, or an iterable of
/// jobs of one type. This function consumes and encodes an iterable immediately.
///
/// Awaiting returns the jobs' [`JobId`]s in order. Unlike a [`batch`], the jobs aren't tracked
/// together, so they don't need the batches tables. A debounced job is pushed on its own. Inside
/// a database transaction, the jobs wait for the transaction to commit, and Laravel discards them
/// if the transaction rolls back.
///
/// # Errors
///
/// Awaiting fails when the connection isn't defined, a job can't be encoded, `jobs` holds a
/// batch, or the connection can't accept the jobs. When the connection fails partway, the jobs
/// before the failing one may already be pushed. On the `sync` connection, each job runs as soon
/// as it's pushed, and awaiting returns the first job error.
///
/// # Panics
///
/// Awaiting panics outside a request, a command, or an
/// [`Application::scope`](crate::Application::scope).
#[track_caller]
pub fn bulk<Kind>(jobs: impl IntoJobs<Kind>) -> PendingBulk {
    PendingBulk::new(jobs)
}

/// Dispatch jobs as a batch and call its callbacks once they've all run.
///
/// Await the returned [`PendingBatch`] to dispatch every one of `jobs` at once. Once they've all
/// run, the worker calls the batch's [`then`](PendingBatch::then),
/// [`catch`](PendingBatch::catch), and [`finally`](PendingBatch::finally)
/// [callbacks](macro@callback). `jobs` is a job or a [`chain`], a tuple of jobs and chains of any
/// types, or an iterable of jobs or chains of one type. This function consumes and encodes an
/// iterable immediately.
///
/// Awaiting returns the batch's [`BatchId`], which you pass to [`find_batch`] to read the batch.
/// Each job of the batch can read the ID with [`Attempt::batch_id`], add jobs to the batch with
/// [`Attempt::add_to_batch`], and cancel the batch with [`Attempt::cancel_batch`]. A batch that
/// you pass to [`PendingChain::then`] becomes a step of the chain.
///
/// # Errors
///
/// Awaiting fails when a job can't be encoded, a job's connection isn't defined, the batches
/// tables can't be written, or a job can't be dispatched. A job that can't be dispatched also
/// cancels the batch. On the `sync` connection, each job runs as soon as it's dispatched, and the
/// worker reports the jobs' errors rather than returning them.
///
/// # Panics
///
/// Awaiting panics outside a request, a command, or an
/// [`Application::scope`](crate::Application::scope).
#[track_caller]
pub fn batch<Kind>(jobs: impl IntoBatchJobs<Kind>) -> PendingBatch {
    PendingBatch::new(jobs)
}

/// Run a job immediately in this process instead of queueing it.
///
/// The job runs the way the `sync` connection runs it. The `dispatch_sync` method that
/// [`#[job]`](macro@job) adds to each job calls this function. The job runs in a fresh
/// application context that starts with the dispatching context's values, and it doesn't wait
/// for a database transaction to commit. When the job fails, its `failed` hook runs.
///
/// # Errors
///
/// Returns the job's error, or the error from encoding or decoding the job.
///
/// # Panics
///
/// Panics outside a request, a command, or an [`Application::scope`](crate::Application::scope).
#[track_caller]
pub fn dispatch_sync<J: Job>(job: J) -> impl Future<Output = Result<()>> + Send {
    dispatch::run_now(job, std::panic::Location::caller())
}