#[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;
#[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>,
}
#[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 {
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
}
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()))
})
}
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
}
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
}
#[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,
)
}
#[must_use]
pub const fn id(&self) -> BatchId {
self.id
}
#[must_use]
pub fn name(&self) -> Option<&str> {
self.name.as_deref()
}
#[must_use]
pub const fn total_jobs(&self) -> u64 {
self.total_jobs
}
#[must_use]
pub const fn pending_jobs(&self) -> u64 {
self.pending_jobs
}
#[must_use]
pub const fn failed_jobs(&self) -> u64 {
self.failed_jobs
}
#[must_use]
pub const fn processed_jobs(&self) -> u64 {
self.processed_jobs
}
#[must_use]
pub const fn progress(&self) -> u8 {
self.progress
}
#[must_use]
pub const fn created_at(&self) -> Timestamp {
self.created_at
}
#[must_use]
pub const fn cancelled_at(&self) -> Option<Timestamp> {
self.cancelled_at
}
#[must_use]
pub const fn finished_at(&self) -> Option<Timestamp> {
self.finished_at
}
#[must_use]
pub const fn is_finished(&self) -> bool {
self.finished_at.is_some()
}
#[must_use]
pub const fn is_cancelled(&self) -> bool {
self.cancelled_at.is_some()
}
#[must_use]
pub const fn has_failures(&self) -> bool {
self.failed_jobs > 0
}
}
pub trait IntoBatchJobs<Kind = ()>: Sealed<Kind> {
#[doc(hidden)]
fn into_chains(self) -> Result<Vec<Chain>>;
}
pub trait IntoBatchJob: Sealed {
#[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);
#[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(),
}
}
pub fn name(mut self, name: impl Into<String>) -> Self {
if let Ok(spec) = &mut self.spec {
spec.name = Some(name.into());
}
self
}
pub fn then(self, callback: impl Then) -> Self {
self.add_callback(callback, |options| &mut options.then)
}
pub fn catch(self, callback: impl Catch) -> Self {
self.add_callback(callback, |options| &mut options.catch)
}
pub fn finally(self, callback: impl Finally) -> Self {
self.add_callback(callback, |options| &mut options.finally)
}
pub fn allow_failures(mut self) -> Self {
if let Ok(spec) = &mut self.spec {
spec.options.allow_failures = true;
}
self
}
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
}
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 {}
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 {}
}
}
}