use super::QueueManagerInternals as _;
use std::future::IntoFuture;
use std::panic::Location;
use std::time::Duration;
use futures_util::future::BoxFuture;
use super::chain::{EncodedJob, IntoJobs, Link};
use super::debounce;
use super::job::__Registration;
use super::payload::Payload;
use super::{Job, JobId, QueueManager};
use crate::Result;
use crate::container::Inject;
use crate::context::{Context, Internals};
use crate::time::Moment;
#[derive(Debug)]
#[must_use = "a job is dispatched only when the dispatch is awaited"]
pub struct PendingDispatch<J> {
job: J,
connection: Option<String>,
queue: Option<String>,
delay: Option<Moment>,
group: Option<String>,
deduplication_id: Option<String>,
display_name: Option<String>,
caller: &'static Location<'static>,
}
impl<J: Job> PendingDispatch<J> {
#[track_caller]
pub(super) fn new(job: J) -> Self {
Self {
job,
connection: None,
queue: None,
delay: None,
group: None,
deduplication_id: None,
display_name: None,
caller: Location::caller(),
}
}
pub fn on_connection(mut self, connection: impl Into<String>) -> Self {
self.connection = Some(connection.into());
self
}
pub fn on_queue(mut self, queue: impl Into<String>) -> Self {
self.queue = Some(queue.into());
self
}
pub fn delay(mut self, delay: impl Into<Moment>) -> Self {
self.delay = Some(delay.into());
self
}
pub fn on_group(mut self, group: impl Into<String>) -> Self {
self.group = Some(group.into());
self
}
pub fn deduplication_id(mut self, id: impl Into<String>) -> Self {
self.deduplication_id = Some(id.into());
self
}
#[doc(hidden)]
pub fn display_name(mut self, name: impl Into<String>) -> Self {
self.display_name = Some(name.into());
self
}
async fn send(self) -> Result<JobId> {
let context = Context::expect_for("laravel::queue::dispatch()", self.caller);
let manager = QueueManager::of(context.services());
let (connection, queue) =
manager.route(self.connection.as_deref(), self.queue.as_deref().or(J::options().queue))?;
let delay = self.delay.map(|delay| delay.remaining());
let mut payload = Payload::new(EncodedJob::new(self.job)?, &context.values());
payload.group = self.group;
payload.deduplication_id = self.deduplication_id;
payload.display_name = self.display_name;
let id = payload.id;
send(manager, payload, connection, queue, delay).await?;
Ok(id)
}
}
pub(super) async fn send(
manager: Inject<QueueManager>,
mut payload: Payload,
connection: String,
queue: String,
delay: Option<Duration>,
) -> Result<()> {
let push = move || async move {
let (delay, claim) = debounce::claim(&mut payload, delay).await?;
if manager.fakes.record(&payload, &connection, &queue, delay) {
return Ok(());
}
if manager.runs_inline(&connection)? {
payload.debounce_id = None;
}
let pushed = manager.push(&connection, &queue, &payload, delay).await;
if pushed.is_err()
&& let Some(claim) = claim
{
claim.release().await;
}
pushed
};
super::after_commit(push).await
}
impl<J: Job> IntoFuture for PendingDispatch<J> {
type Output = Result<JobId>;
type IntoFuture = BoxFuture<'static, Result<JobId>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.send())
}
}
pub fn dispatch_borrowed<J: Job>(
job: &J,
connection: Option<&str>,
queue: Option<&str>,
caller: &'static Location<'static>,
) -> BoxFuture<'static, Result<JobId>> {
let context = Context::expect_for("laravel::schedule::Schedule::job()", caller);
let manager = QueueManager::of(context.services());
let routed = manager.route(connection, queue.or(J::options().queue));
let encoded = EncodedJob::from_ref(job);
let values = context.values();
Box::pin(async move {
let (connection, queue) = routed?;
let payload = Payload::new(encoded?, &values);
let id = payload.id;
send(manager, payload, connection, queue, None).await?;
Ok(id)
})
}
#[derive(Debug)]
#[must_use = "jobs are dispatched only when the bulk dispatch is awaited"]
pub struct PendingBulk {
jobs: Result<Vec<Link>>,
connection: Option<String>,
queue: Option<String>,
caller: &'static Location<'static>,
}
impl PendingBulk {
#[track_caller]
pub(super) fn new<Kind>(jobs: impl IntoJobs<Kind>) -> Self {
Self {
jobs: jobs.into_links(),
connection: None,
queue: None,
caller: Location::caller(),
}
}
pub fn on_connection(mut self, connection: impl Into<String>) -> Self {
self.connection = Some(connection.into());
self
}
pub fn on_queue(mut self, queue: impl Into<String>) -> Self {
self.queue = Some(queue.into());
self
}
async fn send(self) -> Result<Vec<JobId>> {
let jobs = self
.jobs?
.into_iter()
.map(|link| match link {
Link::Job(job) => Ok(job),
Link::Batch { .. } => Err(crate::error::fail("bulk dispatches take jobs, not batches")),
})
.collect::<Result<Vec<_>>>()?;
let context = Context::expect_for("laravel::queue::bulk()", self.caller);
let manager = QueueManager::of(context.services());
let values = context.values();
let mut ids = Vec::with_capacity(jobs.len());
let mut payloads = Vec::with_capacity(jobs.len());
for job in jobs {
let queue = self.queue.as_deref().or_else(|| own_queue(&job.job));
let (connection, queue) = manager.route(self.connection.as_deref(), queue)?;
let payload = Payload::new(job, &values);
ids.push(payload.id);
payloads.push((payload, connection, queue));
}
super::after_commit(move || send_bulk(manager, payloads)).await?;
Ok(ids)
}
}
impl IntoFuture for PendingBulk {
type Output = Result<Vec<JobId>>;
type IntoFuture = BoxFuture<'static, Result<Vec<JobId>>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.send())
}
}
async fn send_bulk(manager: Inject<QueueManager>, payloads: Vec<(Payload, String, String)>) -> Result<()> {
let mut target: Option<(String, String)> = None;
let mut group = Vec::new();
for (payload, connection, queue) in payloads {
let alone = payload.debounce_id.is_some() || manager.runs_inline(&connection)?;
if alone {
flush(&manager, target.take(), &mut group).await?;
send(manager.clone(), payload, connection, queue, None).await?;
continue;
}
if manager.fakes.record(&payload, &connection, &queue, Duration::ZERO) {
continue;
}
let next = (connection, queue);
if target.as_ref() != Some(&next) {
flush(&manager, target.replace(next), &mut group).await?;
}
group.push(payload);
}
flush(&manager, target, &mut group).await
}
async fn flush(manager: &QueueManager, target: Option<(String, String)>, group: &mut Vec<Payload>) -> Result<()> {
let payloads = std::mem::take(group);
match target {
Some((connection, queue)) if !payloads.is_empty() => manager.bulk(&connection, &queue, &payloads).await,
_ => Ok(()),
}
}
pub(super) fn own_queue(job: &str) -> Option<&'static str> {
__Registration::find(job).ok()?.options().queue
}
pub(super) async fn run_now<J: Job>(job: J, caller: &'static Location<'static>) -> Result<()> {
let context = Context::expect_for("laravel::queue::dispatch_sync()", caller);
let manager = QueueManager::of(context.services());
let queue = J::options().queue.unwrap_or("default");
let mut payload = Payload::new(EncodedJob::new(job)?, &context.values());
payload.debounce_id = None;
if manager.fakes.record(&payload, "sync", queue, Duration::ZERO) {
return Ok(());
}
payload.run_once("sync", queue).await
}