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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
#[cfg(feature = "database")]
#[doc(hidden)]
pub mod store;

use super::QueueManagerInternals as _;
use std::fmt;
use std::future::IntoFuture;
use std::panic::Location;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;

use futures_util::future::BoxFuture;
use jiff::Timestamp;
use serde::{Deserialize, Serialize};

use super::callback::{Catch, EncodedCallback, Finally, Point, Then};
use super::chain::{Chain, IntoJobs, Iterable, Link};
use super::payload::Payload;
use super::{Job, JobId, ParseIdError, QueueManager};
use crate::context::{Context, Internals, Values};
use crate::{Error, Result};

#[cfg(feature = "database")]
use self::store::Store;
#[cfg(not(feature = "database"))]
use self::unsupported::Store;

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

impl BatchId {
    #[doc(hidden)]
    pub fn generate() -> Self {
        Self(crate::str::uuid7())
    }

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

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

impl FromStr for BatchId {
    type Err = ParseIdError;

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

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub(crate) struct Options {
    #[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 = "std::ops::Not::not")]
    pub(crate) allow_failures: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) then: Vec<EncodedCallback>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) catch: Vec<EncodedCallback>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) finally: Vec<EncodedCallback>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) continuation: Option<Continuation>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct Continuation {
    pub(crate) chain: Chain,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) member_of: Option<BatchId>,
}

/// A batch waiting to be dispatched, with its ID, name, jobs, and options.
///
/// Each of the batch's jobs is a chain, which most often holds a single job.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BatchSpec {
    pub(crate) id: BatchId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) name: Option<String>,
    pub(crate) jobs: Vec<Chain>,
    #[serde(default)]
    pub(crate) options: Options,
}

impl BatchSpec {
    pub(crate) fn member_ids(&self) -> Vec<uuid::Uuid> {
        self.jobs.iter().flat_map(Chain::member_ids).collect()
    }

    pub(crate) async fn dispatch_after_commit(
        self,
        context: Context,
        continuation: Option<(Chain, Option<BatchId>)>,
    ) -> Result<BatchId> {
        let id = self.id;
        let values = context.values();

        super::after_commit(move || async move { self.dispatch(context, values, continuation).await.map(drop) })
            .await?;
        Ok(id)
    }

    pub(crate) fn dispatch(
        mut self,
        context: Context,
        values: Arc<Values>,
        continuation: Option<(Chain, Option<BatchId>)>,
    ) -> BoxFuture<'static, Result<BatchId>> {
        Box::pin(async move {
            let manager = QueueManager::of(context.services());
            let id = self.id;
            let continues = continuation.is_some();
            self.options.continuation = continuation.map(|(chain, member_of)| Continuation { chain, member_of });
            if manager.fakes.record_batch(&self) {
                return Ok(id);
            }

            let store = Store::open(&manager)?;
            match store.create(&self).await? {
                Created::Already => return Ok(id),
                Created::Empty => {
                    let reached = Reached {
                        then: true,
                        catch: false,
                        finally: true,
                        cancelled: false,
                        options: self.options,
                    };
                    fire(id, reached, None, &context).await;
                    return Ok(id);
                }
                Created::Pending => {}
            }

            let options = self.options.clone();
            match push(&manager, &store, id, &options, self.jobs, &context, &values).await {
                Err(error) if continues => {
                    if let Some(continuation) = &options.continuation {
                        continuation.chain.call_catch(&error, &context).await;
                    }
                    context.report(error);
                }
                pushed => pushed?,
            }
            Ok(id)
        })
    }
}

async fn push(
    manager: &QueueManager,
    store: &Store,
    id: BatchId,
    options: &Options,
    jobs: Vec<Chain>,
    context: &Context,
    values: &Arc<Values>,
) -> Result<()> {
    let mut jobs = jobs.into_iter();
    let mut bulk = Bulk::default();
    while let Some(mut chain) = jobs.next() {
        if options.connection.is_some() {
            chain.connection.clone_from(&options.connection);
        }
        if options.queue.is_some() {
            chain.queue.clone_from(&options.queue);
        }
        let members: Vec<_> = chain.member_ids().collect();

        let chain = match chain.into_bulk_payload(manager, values, Some(id)) {
            Ok(Ok((payload, connection, queue))) => {
                if manager.fakes.record(&payload, &connection, &queue, Duration::ZERO) {
                    continue;
                }
                if !bulk.goes_to(&connection, &queue) {
                    if let Err((error, unpushed)) = bulk.flush(context).await {
                        return skip(store, id, error, [unpushed, members], jobs, context).await;
                    }
                    bulk = Bulk::new(connection, queue);
                }
                bulk.add(payload, members);
                continue;
            }
            Ok(Err(chain)) => chain,
            Err(error) => {
                let waiting = std::mem::take(&mut bulk.members);
                return skip(store, id, error, [waiting, members], jobs, context).await;
            }
        };

        if let Err((error, unpushed)) = bulk.flush(context).await {
            return skip(store, id, error, [unpushed, members], jobs, context).await;
        }
        let connection = chain
            .connection
            .clone()
            .unwrap_or_else(|| manager.default_connection().to_owned());
        let Err(error) = chain.dispatch_next(context, Arc::clone(values), Some(id)).await else {
            continue;
        };
        if manager.runs_inline(&connection).unwrap_or(false) {
            context.report(error);
            continue;
        }

        return skip(store, id, error, [members, Vec::new()], jobs, context).await;
    }

    match bulk.flush(context).await {
        Ok(()) => Ok(()),
        Err((error, unpushed)) => skip(store, id, error, [unpushed, Vec::new()], jobs, context).await,
    }
}

async fn skip(
    store: &Store,
    id: BatchId,
    error: Error,
    unpushed: [Vec<uuid::Uuid>; 2],
    rest: impl Iterator<Item = Chain>,
    context: &Context,
) -> Result<()> {
    store.cancel(id).await?;
    let unpushed: Vec<_> = unpushed
        .into_iter()
        .flatten()
        .chain(rest.flat_map(|chain| chain.member_ids().collect::<Vec<_>>()))
        .collect();
    if let Some((first, rest)) = unpushed.split_first() {
        record(
            id,
            *first,
            Ended::Skipped,
            None,
            rest.to_vec(),
            Vec::new(),
            context.clone(),
        )
        .await?;
    }

    Err(error)
}

#[derive(Default)]
struct Bulk {
    target: Option<(String, String)>,
    payloads: Vec<Payload>,
    members: Vec<uuid::Uuid>,
}

impl Bulk {
    fn new(connection: String, queue: String) -> Self {
        Self {
            target: Some((connection, queue)),
            ..Self::default()
        }
    }

    fn goes_to(&self, connection: &str, queue: &str) -> bool {
        self.target
            .as_ref()
            .is_some_and(|(own_connection, own_queue)| own_connection == connection && own_queue == queue)
    }

    fn add(&mut self, payload: Payload, members: Vec<uuid::Uuid>) {
        self.payloads.push(payload);
        self.members.extend(members);
    }

    async fn flush(&mut self, context: &Context) -> Result<(), (Error, Vec<uuid::Uuid>)> {
        let Some((connection, queue)) = self.target.take() else {
            return Ok(());
        };
        let payloads = std::mem::take(&mut self.payloads);
        let members = std::mem::take(&mut self.members);
        let manager = QueueManager::of(context.services());
        let push = move || async move { manager.bulk(&connection, &queue, &payloads).await };

        super::after_commit(push).await.map_err(|error| (error, members))
    }
}

#[cfg_attr(
    not(feature = "database"),
    expect(dead_code, reason = "only the database store creates batches")
)]
pub(crate) enum Created {
    Already,
    Empty,
    Pending,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Ended {
    Succeeded,
    Failed,
    Skipped,
}

#[derive(Debug)]
pub(crate) struct Reached {
    pub(crate) then: bool,
    pub(crate) catch: bool,
    pub(crate) finally: bool,
    pub(crate) cancelled: bool,
    pub(crate) options: Options,
}

#[derive(Debug, Default)]
pub struct BatchChanges {
    pub added: Vec<Chain>,
    pub cancel: bool,
    pub(crate) chained: Vec<uuid::Uuid>,
}

pub(crate) fn settle<'a>(
    id: BatchId,
    job: JobId,
    ended: Option<Ended>,
    error: Option<&'a Error>,
    rest: &Chain,
    changes: BatchChanges,
    context: &Context,
) -> BoxFuture<'a, Result<()>> {
    let rest: Vec<_> = rest.member_ids().collect();
    let context = context.clone();

    Box::pin(async move {
        if changes.cancel {
            Store::open(&QueueManager::of(context.services()))?.cancel(id).await?;
        }
        let Some(ended) = ended else {
            return Ok(());
        };
        if ended == Ended::Succeeded && !changes.added.is_empty() {
            add(id, changes.added, &context).await?;
        }

        record(id, job.into_uuid(), ended, error, rest, changes.chained, context).await
    })
}

async fn add(id: BatchId, jobs: Vec<Chain>, context: &Context) -> Result<()> {
    let manager = QueueManager::of(context.services());
    let store = Store::open(&manager)?;
    let members: Vec<_> = jobs.iter().flat_map(Chain::member_ids).collect();
    let options = store.add(id, &members).await?;

    push(&manager, &store, id, &options, jobs, context, &context.values()).await
}

fn record<'a>(
    id: BatchId,
    member: uuid::Uuid,
    ended: Ended,
    error: Option<&'a Error>,
    rest: Vec<uuid::Uuid>,
    joined: Vec<uuid::Uuid>,
    context: Context,
) -> BoxFuture<'a, Result<()>> {
    Box::pin(async move {
        let store = Store::open(&QueueManager::of(context.services()))?;
        if let Some(reached) = store.record(id, member, ended, &rest, &joined).await? {
            fire(id, reached, error, &context).await;
        }

        Ok(())
    })
}

async fn fire(id: BatchId, reached: Reached, error: Option<&Error>, context: &Context) {
    let Reached {
        then,
        catch,
        finally,
        cancelled,
        options,
    } = reached;
    let batch = match Store::open(&QueueManager::of(context.services())) {
        Ok(store) => store.find(id).await,
        Err(error) => Err(error),
    };

    match batch {
        Ok(Some(batch)) => {
            if catch {
                let fallback;
                let error = match error {
                    Some(error) => error,
                    None => {
                        fallback = crate::error::fail(format!("a batch in a chain of the batch `{id}` was cancelled"));
                        &fallback
                    }
                };
                for callback in &options.catch {
                    callback.call(Point::Catch(Some(&batch), error), context).await;
                }
                if !options.allow_failures
                    && let Some(continuation) = &options.continuation
                {
                    continuation.chain.call_catch(error, context).await;
                }
            }
            for callback in options.then.iter().filter(|_| then) {
                callback.call(Point::Then(&batch), context).await;
            }
            for callback in options.finally.iter().filter(|_| finally) {
                callback.call(Point::Finally(&batch), context).await;
            }
        }
        Ok(None) => {}
        Err(error) => context.report(error),
    }

    if finally
        && let Some(continuation) = options.continuation
        && let Err(error) = go_on(id, continuation, cancelled, context).await
    {
        context.report(error);
    }
}

async fn go_on(id: BatchId, continuation: Continuation, cancelled: bool, context: &Context) -> Result<()> {
    let Continuation { chain, member_of } = continuation;
    let members: Vec<_> = chain.member_ids().collect();
    if cancelled {
        return record_step(member_of, id, Ended::Failed, None, members, context).await;
    }

    let catch = chain.catch.clone();
    if let Err(error) = chain.dispatch_next(context, context.values(), member_of).await {
        // The batch has finished, so no retry can dispatch the rest: the chain fails here...
        for callback in &catch {
            callback.call(Point::Catch(None, &error), context).await;
        }
        record_step(member_of, id, Ended::Failed, Some(&error), members, context).await?;
        return Err(error);
    }

    record_step(member_of, id, Ended::Succeeded, None, Vec::new(), context).await
}

/// Record how the batch `id` ended as a step of the outer batch whose chain it's in, if any, with
/// the steps of the chain that will never run.
async fn record_step(
    outer: Option<BatchId>,
    id: BatchId,
    ended: Ended,
    error: Option<&Error>,
    rest: Vec<uuid::Uuid>,
    context: &Context,
) -> Result<()> {
    let Some(outer) = outer else {
        return Ok(());
    };

    record(outer, id.into_uuid(), ended, error, rest, Vec::new(), context.clone()).await
}

pub(crate) fn is_cancelled(id: BatchId) -> BoxFuture<'static, Result<bool>> {
    let manager = super::manager();

    Box::pin(async move {
        Ok(Store::open(&manager)?
            .find(id)
            .await?
            .is_some_and(|batch| batch.cancelled_at.is_some()))
    })
}

/// Find a batch by its ID, such as to show how far along the batch is.
///
/// Returns `None` when no batch has the ID, such as after `queue:prune-batches` deleted the
/// batch. Under a [queue fake](super::fake), this function returns a batch that the fake
/// recorded, with every job pending.
///
/// # Errors
///
/// Fails when the batches table can't be read.
///
/// # Panics
///
/// Panics outside a request, a command, or an [`Application::scope`](crate::Application::scope).
pub async fn find_batch(id: BatchId) -> Result<Option<Batch>> {
    let manager = crate::container::built::<QueueManager>("laravel::queue::find_batch()");
    if let Some((spec, cancelled)) = manager.fakes.find_batch(id) {
        return Ok(Some(Batch::pending(&spec, cancelled)));
    }

    Store::open(&manager)?.find(id).await
}

/// Cancel a batch.
///
/// The batch skips its jobs that haven't run yet, and its `then` callbacks never run. Its
/// `finally` callbacks run once the jobs that are already running finish. Under a
/// [queue fake](super::fake), this function marks a batch that the fake recorded as cancelled.
///
/// # Errors
///
/// Fails when the batches table can't be written.
///
/// # Panics
///
/// Panics outside a request, a command, or an [`Application::scope`](crate::Application::scope).
pub async fn cancel_batch(id: BatchId) -> Result<()> {
    let manager = crate::container::built::<QueueManager>("laravel::queue::cancel_batch()");
    if manager.fakes.cancel_batch(id) {
        return Ok(());
    }

    Store::open(&manager)?.cancel(id).await
}

/// A snapshot of a batch at the time it was read, with its job counts and the times it was
/// created, cancelled, and finished.
///
/// `Batch` serializes to JSON, so a route can return it to show a batch's progress.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Batch {
    id: BatchId,
    name: Option<String>,
    total_jobs: u64,
    pending_jobs: u64,
    failed_jobs: u64,
    processed_jobs: u64,
    progress: u8,
    created_at: Timestamp,
    cancelled_at: Option<Timestamp>,
    finished_at: Option<Timestamp>,
}

impl Batch {
    #[doc(hidden)]
    pub fn new(
        id: BatchId,
        name: Option<String>,
        (total_jobs, pending_jobs, failed_jobs): (u64, u64, u64),
        created_at: Timestamp,
        cancelled_at: Option<Timestamp>,
        finished_at: Option<Timestamp>,
    ) -> Self {
        let processed_jobs = total_jobs.saturating_sub(pending_jobs);
        let progress = match total_jobs {
            0 => 0,
            total => u8::try_from((processed_jobs * 100 + total / 2) / total).unwrap_or(100),
        };

        Self {
            id,
            name,
            total_jobs,
            pending_jobs,
            failed_jobs,
            processed_jobs,
            progress,
            created_at,
            cancelled_at,
            finished_at,
        }
    }

    fn pending(spec: &BatchSpec, cancelled: bool) -> Self {
        let total = u64::try_from(spec.member_ids().len()).unwrap_or(u64::MAX);
        let now = Timestamp::try_from(crate::clock::system_now()).unwrap_or(Timestamp::UNIX_EPOCH);

        Self::new(
            spec.id,
            spec.name.clone(),
            (total, total, 0),
            now,
            cancelled.then_some(now),
            None,
        )
    }

    /// The batch's ID.
    #[must_use]
    pub const fn id(&self) -> BatchId {
        self.id
    }

    /// The name the batch was dispatched with, if any.
    #[must_use]
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// The number of jobs in the batch, including the later jobs of its chains and the jobs added
    /// to it.
    #[must_use]
    pub const fn total_jobs(&self) -> u64 {
        self.total_jobs
    }

    /// The number of the batch's jobs that haven't succeeded or been skipped.
    ///
    /// A failed job counts as pending until a retry of it succeeds.
    #[must_use]
    pub const fn pending_jobs(&self) -> u64 {
        self.pending_jobs
    }

    /// The number of the batch's jobs that have failed for good and haven't succeeded on a retry
    /// since.
    #[must_use]
    pub const fn failed_jobs(&self) -> u64 {
        self.failed_jobs
    }

    /// The number of the batch's jobs that have succeeded or been skipped.
    #[must_use]
    pub const fn processed_jobs(&self) -> u64 {
        self.processed_jobs
    }

    /// The percentage of the batch's jobs that have been processed, from 0 to 100.
    #[must_use]
    pub const fn progress(&self) -> u8 {
        self.progress
    }

    /// When the batch was dispatched.
    #[must_use]
    pub const fn created_at(&self) -> Timestamp {
        self.created_at
    }

    /// When the batch was cancelled, if it was.
    #[must_use]
    pub const fn cancelled_at(&self) -> Option<Timestamp> {
        self.cancelled_at
    }

    /// When every job of the batch had run, or `None` if some jobs haven't run yet.
    #[must_use]
    pub const fn finished_at(&self) -> Option<Timestamp> {
        self.finished_at
    }

    /// Whether every job of the batch has run, meaning each job has succeeded, failed, or been
    /// skipped.
    #[must_use]
    pub const fn is_finished(&self) -> bool {
        self.finished_at.is_some()
    }

    /// Whether the batch has been cancelled.
    #[must_use]
    pub const fn is_cancelled(&self) -> bool {
        self.cancelled_at.is_some()
    }

    /// Whether any of the batch's jobs has failed for good.
    #[must_use]
    pub const fn has_failures(&self) -> bool {
        self.failed_jobs > 0
    }
}

/// The jobs of a batch.
///
/// The jobs are a job or chain, a tuple of jobs and chains of any types, or an iterable of jobs
/// or chains of one type. An iterable is consumed and encoded immediately.
/// [`queue::batch`](super::batch) and [`Attempt::add_to_batch`](super::Attempt::add_to_batch)
/// accept this trait. A generic helper forwards the inferred `Kind` with a bound such as
/// `impl IntoBatchJobs<Kind>`.
pub trait IntoBatchJobs<Kind = ()>: Sealed<Kind> {
    /// Encode the jobs, each as a chain.
    #[doc(hidden)]
    fn into_chains(self) -> Result<Vec<Chain>>;
}

/// One job of a batch, which is either a job or a chain of jobs.
pub trait IntoBatchJob: Sealed {
    /// Encode the job as a chain.
    #[doc(hidden)]
    fn into_chain(self) -> Result<Chain>;
}

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

use private::Sealed;

impl<J: Job> Sealed for J {}

impl<J: Job> IntoBatchJob for J {
    fn into_chain(self) -> Result<Chain> {
        Ok(Chain {
            jobs: vec![Link::new(self)?],
            ..Chain::default()
        })
    }
}

impl Sealed for super::PendingChain {}

impl IntoBatchJob for super::PendingChain {
    fn into_chain(self) -> Result<Chain> {
        Self::into_chain(self)
    }
}

impl<J: Job> IntoBatchJobs for J {
    fn into_chains(self) -> Result<Vec<Chain>> {
        Ok(vec![IntoBatchJob::into_chain(self)?])
    }
}

impl IntoBatchJobs for super::PendingChain {
    fn into_chains(self) -> Result<Vec<Chain>> {
        Ok(vec![IntoBatchJob::into_chain(self)?])
    }
}

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

impl<I: IntoIterator<Item: IntoBatchJob>> IntoBatchJobs<Iterable> for I {
    fn into_chains(self) -> Result<Vec<Chain>> {
        self.into_iter().map(IntoBatchJob::into_chain).collect()
    }
}

macro_rules! tuple_batch_jobs {
    ($($name:ident),+) => {
        impl<$($name: IntoBatchJob),+> Sealed for ($($name,)+) {}

        impl<$($name: IntoBatchJob),+> IntoBatchJobs for ($($name,)+) {
            #[expect(non_snake_case, reason = "the bindings reuse the type parameters' names")]
            fn into_chains(self) -> Result<Vec<Chain>> {
                let ($($name,)+) = self;
                Ok(vec![$($name.into_chain()?),+])
            }
        }
    };
}

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

/// A batch of jobs on its way to the queue.
///
/// Await the batch to dispatch every job at once. Awaiting returns the batch's [`BatchId`]. The
/// errors and panics of awaiting are listed on [`queue::batch`](super::batch).
///
/// The jobs run side by side, on as many workers as pick them up. Once every job has run, the
/// worker that ran the last job calls the batch's [`then`](Self::then) callbacks if every job
/// succeeded, and its [`finally`](Self::finally) callbacks in every case. When the first job
/// fails for good, its worker calls the [`catch`](Self::catch) callbacks with the job's error and
/// cancels the batch, unless the batch [allows failures](Self::allow_failures). Inside a
/// database transaction, the batch waits for the transaction to commit, as a
/// [`dispatch`](super::dispatch) does.
///
/// ```no_run
/// # #[derive(laravel::queue::Queueable)] pub struct ImportCsv { pub import_id: i64, pub chunk: u32 }
/// # #[laravel::queue::job] impl ImportCsv { async fn handle(self) {} }
/// # #[derive(laravel::queue::Queueable)] pub struct ImportFinished { pub import_id: i64 }
/// # #[laravel::queue::callback] impl ImportFinished {
/// #     async fn then(self) {}
/// #     async fn catch(self, error: &laravel::Error) {}
/// # }
/// use laravel::queue;
///
/// # async fn example(import_id: i64) -> laravel::Result<()> {
/// let batch_id = queue::batch([
///     ImportCsv { import_id, chunk: 1 },
///     ImportCsv { import_id, chunk: 2 },
///     ImportCsv { import_id, chunk: 3 },
/// ])
/// .name("Import CSV")
/// .then(ImportFinished { import_id })
/// .catch(ImportFinished { import_id })
/// .await?;
/// # Ok(()) }
/// ```
#[derive(Debug)]
#[must_use = "a batch is dispatched only when it's awaited"]
pub struct PendingBatch {
    spec: Result<BatchSpec>,
    caller: &'static Location<'static>,
}

impl PendingBatch {
    #[track_caller]
    pub(super) fn new<Kind>(jobs: impl IntoBatchJobs<Kind>) -> Self {
        let spec = jobs.into_chains().map(|jobs| BatchSpec {
            id: BatchId::generate(),
            name: None,
            jobs,
            options: Options::default(),
        });

        Self {
            spec,
            caller: Location::caller(),
        }
    }

    /// Give the batch a name, which [`Batch::name`] returns.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        if let Ok(spec) = &mut self.spec {
            spec.name = Some(name.into());
        }
        self
    }

    /// Call `callback`'s `then` method once every job of the batch has succeeded.
    ///
    /// A cancelled batch never calls the callback. Each call adds another callback.
    pub fn then(self, callback: impl Then) -> Self {
        self.add_callback(callback, |options| &mut options.then)
    }

    /// Call `callback`'s `catch` method with the error when the first of the batch's jobs fails
    /// for good.
    ///
    /// Each call adds another callback.
    pub fn catch(self, callback: impl Catch) -> Self {
        self.add_callback(callback, |options| &mut options.catch)
    }

    /// Call `callback`'s `finally` method once every job of the batch has run.
    ///
    /// The callback runs whether each job succeeded, failed, or was skipped because the batch was
    /// cancelled. Each call adds another callback. A retried job that adds jobs to a finished batch,
    /// or continues its chain, makes the batch unfinished again. Once those new jobs have run, the
    /// worker calls `finally` again.
    pub fn finally(self, callback: impl Finally) -> Self {
        self.add_callback(callback, |options| &mut options.finally)
    }

    /// Keep the batch running when one of its jobs fails for good, rather than cancelling it.
    pub fn allow_failures(mut self) -> Self {
        if let Ok(spec) = &mut self.spec {
            spec.options.allow_failures = true;
        }
        self
    }

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

    /// Push every job of the batch 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(spec) = &mut self.spec {
            spec.options.queue = Some(queue.into());
        }
        self
    }

    fn add_callback<C: super::Callback>(
        mut self,
        callback: C,
        callbacks: impl FnOnce(&mut Options) -> &mut Vec<EncodedCallback>,
    ) -> Self {
        self.spec = self.spec.and_then(|mut spec| {
            callbacks(&mut spec.options).push(EncodedCallback::new(callback)?);
            Ok(spec)
        });
        self
    }

    async fn send(self) -> Result<BatchId> {
        let context = Context::expect_for("laravel::queue::batch()", self.caller);
        self.spec?.dispatch_after_commit(context, None).await
    }
}

impl IntoFuture for PendingBatch {
    type Output = Result<BatchId>;
    type IntoFuture = BoxFuture<'static, Result<BatchId>>;

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

impl super::chain::sealed::Sealed for PendingBatch {}

/// A batch can be a step of a chain, and the chain continues once every job of the batch has run.
impl IntoJobs for PendingBatch {
    fn into_links(self) -> Result<Vec<Link>> {
        Ok(vec![Link::Batch {
            batch: Box::new(self.spec?),
        }])
    }
}

#[cfg(not(feature = "database"))]
mod unsupported {
    use std::convert::Infallible;

    use super::{Batch, BatchId, BatchSpec, Created, Ended, Options, Reached};
    use crate::queue::QueueManager;

    use crate::Result;

    pub(crate) struct Store(Infallible);

    impl Store {
        pub(crate) fn open(_manager: &QueueManager) -> Result<Self> {
            Err(crate::error::fail(
                "batches are kept in database tables, which need a database driver feature: \
                 `database-sqlite`, `database-postgres` or `database-mysql`",
            ))
        }

        pub(crate) async fn create(&self, _batch: &BatchSpec) -> Result<Created> {
            match self.0 {}
        }

        pub(crate) async fn add(&self, _id: BatchId, _members: &[uuid::Uuid]) -> Result<Options> {
            match self.0 {}
        }

        pub(crate) async fn record(
            &self,
            _id: BatchId,
            _member: uuid::Uuid,
            _ended: Ended,
            _rest: &[uuid::Uuid],
            _joined: &[uuid::Uuid],
        ) -> Result<Option<Reached>> {
            match self.0 {}
        }

        pub(crate) async fn cancel(&self, _id: BatchId) -> Result<()> {
            match self.0 {}
        }

        pub(crate) async fn find(&self, _id: BatchId) -> Result<Option<Batch>> {
            match self.0 {}
        }
    }
}