use super::QueueManagerInternals as _;
use std::future::IntoFuture;
use std::panic::Location;
use std::sync::Arc;
use std::time::Duration;
use futures_util::future::BoxFuture;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::batch::{BatchId, BatchSpec};
use super::callback::{ChainCatch, EncodedCallback, Point};
use super::dispatch::{own_queue, send};
use super::fake::Dispatched;
use super::payload::Payload;
use super::queueable::ModelRows;
use super::{Job, JobId, QueueManager};
use crate::context::{Context, Internals, Values};
use crate::time::Moment;
use crate::{Error, Result};
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EncodedJob {
pub(crate) id: JobId,
pub(crate) job: String,
pub(crate) data: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) debounce_id: Option<String>,
#[serde(skip)]
pub(crate) dispatched: Dispatched,
}
impl EncodedJob {
#[expect(
clippy::needless_pass_by_value,
reason = "dispatch takes the job, and only its payload outlives it"
)]
pub fn new<J: Job>(job: J) -> Result<Self> {
Self::from_ref(&job)
}
pub fn from_ref<J: Job>(job: &J) -> Result<Self> {
let debounce_id = J::options().debounce_for.map(|_| job.debounce_id());
let mut rows = ModelRows::new();
let data = super::queueable::store("job", J::NAME, job, &mut rows)?;
Ok(Self {
id: JobId::generate(),
job: J::NAME.to_owned(),
data,
debounce_id,
dispatched: Dispatched::new(rows),
})
}
}
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Link {
Job(EncodedJob),
Batch { batch: Box<BatchSpec> },
}
impl Link {
pub(crate) fn new<J: Job>(job: J) -> Result<Self> {
EncodedJob::new(job).map(Self::Job)
}
pub(crate) fn name(&self) -> &str {
match self {
Self::Job(job) => &job.job,
Self::Batch { .. } => "batch",
}
}
}
pub trait IntoJobs<Kind = ()>: sealed::Sealed<Kind> {
#[doc(hidden)]
fn into_links(self) -> Result<Vec<Link>>;
}
impl<J: Job> sealed::Sealed for J {}
impl<J: Job> IntoJobs for J {
fn into_links(self) -> Result<Vec<Link>> {
Ok(vec![Link::new(self)?])
}
}
#[doc(hidden)]
#[derive(Debug)]
pub enum Iterable {}
impl<I: IntoIterator<Item: Job>> sealed::Sealed<Iterable> for I {}
impl<I: IntoIterator<Item: Job>> IntoJobs<Iterable> for I {
fn into_links(self) -> Result<Vec<Link>> {
self.into_iter().map(Link::new).collect()
}
}
macro_rules! tuple_jobs {
($($name:ident),+) => {
impl<$($name: Job),+> sealed::Sealed for ($($name,)+) {}
impl<$($name: Job),+> IntoJobs for ($($name,)+) {
#[expect(non_snake_case, reason = "the bindings reuse the type parameters' names")]
fn into_links(self) -> Result<Vec<Link>> {
let ($($name,)+) = self;
Ok(vec![$(Link::new($name)?),+])
}
}
};
}
tuple_jobs!(A);
tuple_jobs!(A, B);
tuple_jobs!(A, B, C);
tuple_jobs!(A, B, C, D);
tuple_jobs!(A, B, C, D, E);
tuple_jobs!(A, B, C, D, E, F);
tuple_jobs!(A, B, C, D, E, F, G);
tuple_jobs!(A, B, C, D, E, F, G, H);
tuple_jobs!(A, B, C, D, E, F, G, H, I);
tuple_jobs!(A, B, C, D, E, F, G, H, I, K);
tuple_jobs!(A, B, C, D, E, F, G, H, I, K, L);
tuple_jobs!(A, B, C, D, E, F, G, H, I, K, L, M);
pub(super) mod sealed {
pub trait Sealed<Kind = ()> {}
}
#[doc(hidden)]
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Chain {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub jobs: Vec<Link>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) connection: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) queue: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) catch: Vec<EncodedCallback>,
}
impl Chain {
pub(crate) fn is_empty(&self) -> bool {
*self == Self::default()
}
pub(crate) async fn dispatch(
self,
job: EncodedJob,
context: &Context,
values: &Values,
delay: Option<Duration>,
member_of: Option<BatchId>,
) -> Result<JobId> {
let manager = QueueManager::of(context.services());
let (payload, connection, queue) = self.into_payload(&manager, job, values, member_of)?;
let id = payload.id;
send(manager, payload, connection, queue, delay).await?;
Ok(id)
}
fn into_payload(
self,
manager: &QueueManager,
job: EncodedJob,
values: &Values,
member_of: Option<BatchId>,
) -> Result<(Payload, String, String)> {
let (connection, queue) = self.route(manager, &job.job)?;
let mut payload = Payload::new(job, values);
payload.batch = member_of;
payload.chain = self;
Ok((payload, connection, queue))
}
pub(crate) fn into_bulk_payload(
mut self,
manager: &QueueManager,
values: &Values,
member_of: Option<BatchId>,
) -> Result<Result<(Payload, String, String), Self>> {
if self.jobs.is_empty() {
return Ok(Err(self));
}
let job = match self.jobs.remove(0) {
Link::Job(job) if job.debounce_id.is_none() => job,
link => {
self.jobs.insert(0, link);
return Ok(Err(self));
}
};
let (connection, _) = self.route(manager, &job.job)?;
if manager.runs_inline(&connection)? {
self.jobs.insert(0, Link::Job(job));
return Ok(Err(self));
}
self.into_payload(manager, job, values, member_of).map(Ok)
}
pub(crate) fn dispatch_next(
mut self,
context: &Context,
values: Arc<Values>,
member_of: Option<BatchId>,
) -> BoxFuture<'static, Result<()>> {
let context = context.clone();
Box::pin(async move {
if self.jobs.is_empty() {
return Ok(());
}
match self.jobs.remove(0) {
Link::Job(job) => self.dispatch(job, &context, &values, None, member_of).await.map(drop),
Link::Batch { batch } => batch.dispatch(context, values, Some((self, member_of))).await.map(drop),
}
})
}
pub(crate) async fn call_catch(&self, error: &Error, context: &Context) {
for callback in &self.catch {
callback.call(Point::Catch(None, error), context).await;
}
}
pub(crate) fn member_ids(&self) -> impl Iterator<Item = uuid::Uuid> + '_ {
self.jobs.iter().map(|link| match link {
Link::Job(job) => job.id.into_uuid(),
Link::Batch { batch } => batch.id.into_uuid(),
})
}
pub(crate) fn route(&self, manager: &QueueManager, job: &str) -> Result<(String, String)> {
let queue = self.queue.as_deref().or_else(|| own_queue(job));
manager.route(self.connection.as_deref(), queue)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChainDispatched {
Job(JobId),
Batch(BatchId),
}
#[derive(Debug)]
#[must_use = "a chain is dispatched only when it's awaited"]
pub struct PendingChain {
chain: Result<Chain>,
delay: Option<Moment>,
caller: &'static Location<'static>,
}
impl PendingChain {
#[track_caller]
pub(super) fn new<Kind>(jobs: impl IntoJobs<Kind>) -> Self {
let chain = Self {
chain: Ok(Chain::default()),
delay: None,
caller: Location::caller(),
};
chain.then(jobs)
}
pub fn then<Kind>(mut self, jobs: impl IntoJobs<Kind>) -> Self {
self.chain = self.chain.and_then(|mut chain| {
chain.jobs.extend(jobs.into_links()?);
Ok(chain)
});
self
}
pub fn on_connection(mut self, connection: impl Into<String>) -> Self {
if let Ok(chain) = &mut self.chain {
chain.connection = Some(connection.into());
}
self
}
pub fn on_queue(mut self, queue: impl Into<String>) -> Self {
if let Ok(chain) = &mut self.chain {
chain.queue = Some(queue.into());
}
self
}
pub fn delay(mut self, delay: impl Into<Moment>) -> Self {
self.delay = Some(delay.into());
self
}
pub fn catch(mut self, callback: impl ChainCatch) -> Self {
self.chain = self.chain.and_then(|mut chain| {
chain.catch.push(EncodedCallback::new(callback)?);
Ok(chain)
});
self
}
pub(super) fn into_chain(self) -> Result<Chain> {
let chain = self.chain?;
if chain.jobs.is_empty() {
return Err(crate::error::fail("the chain has no jobs to dispatch"));
}
if self.delay.is_some() {
return Err(crate::error::fail("a chain in a batch can't have a delay"));
}
Ok(chain)
}
async fn send(self) -> Result<ChainDispatched> {
let mut rest = self.chain?;
let context = Context::expect_for("laravel::queue::chain()", self.caller);
let delay = self.delay.map(|delay| delay.remaining());
if rest.jobs.is_empty() {
return Err(crate::error::fail("the chain has no jobs to dispatch"));
}
let first = rest.jobs.remove(0);
match first {
Link::Job(first) => rest
.dispatch(first, &context, &context.values(), delay, None)
.await
.map(ChainDispatched::Job),
Link::Batch { batch } => {
if delay.is_some() {
return Err(crate::error::fail("a chain starting with a batch can't have a delay"));
}
batch
.dispatch_after_commit(context, Some((rest, None)))
.await
.map(ChainDispatched::Batch)
}
}
}
}
impl IntoFuture for PendingChain {
type Output = Result<ChainDispatched>;
type IntoFuture = BoxFuture<'static, Result<ChainDispatched>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.send())
}
}