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
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;

/// A job on its way to the queue.
///
/// Choose where the job goes, then await the `PendingDispatch` to push the job. Awaiting returns
/// the job's [`JobId`]. The errors and panics of awaiting are listed on
/// [`queue::dispatch`](super::dispatch).
///
/// Inside a database transaction, Laravel holds the job until the transaction commits, and
/// discards the job if the transaction rolls back, so a worker never runs the job against
/// uncommitted data. Awaiting then returns as soon as the job is held. The job is pushed at most
/// once, even if the code that committed stops waiting, and the job is lost if the process exits
/// before the push. If the push fails, the transaction returns an
/// [`AfterCommitError`](crate::db::AfterCommitError), and the data stays committed.
///
/// ```no_run
/// # #[derive(laravel::queue::Queueable)]
/// # pub struct ProcessPodcast { pub podcast_id: i64 }
/// # #[laravel::queue::job]
/// # impl ProcessPodcast { async fn handle(self) {} }
/// use laravel::time::ToSpan;
///
/// # async fn example() -> laravel::Result<()> {
/// ProcessPodcast { podcast_id: 42 }.dispatch().await?;
///
/// ProcessPodcast { podcast_id: 42 }
///     .dispatch()
///     .on_connection("database")
///     .on_queue("podcasts")
///     .delay(10.minutes())
///     .await?;
/// # Ok(()) }
/// ```
#[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(),
        }
    }

    /// Push the job to this connection rather than the default one.
    pub fn on_connection(mut self, connection: impl Into<String>) -> Self {
        self.connection = Some(connection.into());
        self
    }

    /// Push the job to this queue, rather than the queue that its options or connection choose.
    pub fn on_queue(mut self, queue: impl Into<String>) -> Self {
        self.queue = Some(queue.into());
        self
    }

    /// Delay the job by a span such as `10.minutes()`, or until a
    /// [`Timestamp`](crate::time::Timestamp).
    ///
    /// The `sync` connection ignores the delay and runs the job immediately. An SQS FIFO queue
    /// refuses a delayed job.
    pub fn delay(mut self, delay: impl Into<Moment>) -> Self {
        self.delay = Some(delay.into());
        self
    }

    /// Put the job in this message group on an SQS queue.
    ///
    /// A FIFO queue runs a group's jobs one at a time, in the order they were dispatched, and a
    /// released or retried job keeps its place at the front of its group. A standard queue divides
    /// its capacity fairly between groups. Other drivers ignore the group.
    pub fn on_group(mut self, group: impl Into<String>) -> Self {
        self.group = Some(group.into());
        self
    }

    /// Give the job this deduplication ID on an SQS FIFO queue.
    ///
    /// The FIFO queue drops any job dispatched with the same ID in the next five minutes. Other
    /// queues ignore the ID.
    pub fn deduplication_id(mut self, id: impl Into<String>) -> Self {
        self.deduplication_id = Some(id.into());
        self
    }

    /// Show the job as `name` in `queue:work` and `queue:failed`.
    ///
    /// Framework jobs that deliver something else, such as an email or a workflow's advance, use
    /// this name to describe what they deliver.
    #[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(());
        }
        // The sync connection runs every dispatch, so a concurrent dispatch mustn't replace this one...
        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())
    }
}

/// Dispatch a borrowed job, used by the scheduler so scheduled jobs don't need `Clone`.
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)
    })
}

/// Several jobs on their way to the queue together.
///
/// Await the `PendingBulk` to push the jobs in as few round trips as the connection's driver
/// allows. Awaiting returns the jobs' [`JobId`]s in order. The errors and panics of awaiting are
/// listed on [`queue::bulk`](super::bulk).
///
/// Each job keeps its own options and middleware, and goes to its own queue unless
/// [`on_queue`](Self::on_queue) chooses one queue for all of them. Inside a database transaction,
/// Laravel holds the jobs until the transaction commits, as it does for a
/// [`dispatch`](super::dispatch).
///
/// ```no_run
/// # #[derive(laravel::queue::Queueable)]
/// # pub struct NotifySubscriber { pub subscriber_id: i64 }
/// # #[laravel::queue::job]
/// # impl NotifySubscriber { async fn handle(self) {} }
/// use laravel::queue;
///
/// # async fn example(subscribers: Vec<i64>) -> laravel::Result<()> {
/// let jobs = subscribers
///     .into_iter()
///     .map(|subscriber_id| NotifySubscriber { subscriber_id });
///
/// queue::bulk(jobs).on_queue("notifications").await?;
/// # Ok(()) }
/// ```
#[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(),
        }
    }

    /// Push the jobs to this connection rather than the default one.
    pub fn on_connection(mut self, connection: impl Into<String>) -> Self {
        self.connection = Some(connection.into());
        self
    }

    /// Push the jobs to this queue, rather than the queues that their options or connection choose.
    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(()),
    }
}

/// The queue a job's options choose, found by the job's registered name.
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
}