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 std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::Duration;

use jiff::ZonedDateTimeArithmetic;

use super::JobId;
use super::batch::{BatchChanges, BatchId, IntoBatchJobs};
use super::chain::{IntoJobs, Link};
use super::payload::{Payload, Place};
use crate::Error;

/// One run of a job, with the job's ID, where the job came from, and how many times it has run.
///
/// A job's `handle` may take `&Attempt` to ask the queue to release the job for later, delete
/// it, or fail it without retrying. Each request takes effect once `handle` returns, and a later
/// request replaces an earlier one:
///
/// ```no_run
/// use laravel::container::Inject;
/// use laravel::queue::{Attempt, job};
/// use laravel::time::ToSpan;
/// # pub struct AudioProcessor;
/// # impl AudioProcessor { async fn is_busy(&self) -> bool { false } }
///
/// #[derive(laravel::queue::Queueable)]
/// pub struct ProcessPodcast {
///     pub podcast_id: i64,
/// }
///
/// #[job]
/// impl ProcessPodcast {
///     async fn handle(self, audio: Inject<AudioProcessor>, attempt: &Attempt) {
///         if audio.is_busy().await {
///             attempt.release(30.seconds());
///         }
///     }
/// }
/// ```
#[derive(Debug)]
pub struct Attempt {
    id: JobId,
    name: &'static str,
    connection: String,
    queue: String,
    number: u32,
    debounce_id: Option<String>,
    batch: Option<BatchId>,
    effects: Mutex<Effects>,
}

/// What the job asked of the queue as it ran, applied once the attempt ends.
#[derive(Debug, Default)]
pub(crate) struct Effects {
    pub(crate) requested: Option<Requested>,
    pub(crate) chain: Vec<Link>,
    pub(crate) batch: BatchChanges,
}

#[derive(Debug)]
pub(crate) enum Requested {
    Release(Duration),
    Delete,
    Fail(Error),
    Settle(Error),
}

impl Attempt {
    pub(crate) fn new(payload: &Payload, name: &'static str, place: Place<'_>) -> Self {
        Self {
            id: payload.id,
            name,
            connection: place.connection.to_owned(),
            queue: place.queue.to_owned(),
            number: place.number,
            debounce_id: payload.debounce_id.clone(),
            batch: payload.batch,
            effects: Mutex::new(Effects {
                chain: payload.chain.jobs.clone(),
                ..Effects::default()
            }),
        }
    }

    /// The job's ID, assigned when it was dispatched.
    #[must_use]
    pub const fn id(&self) -> JobId {
        self.id
    }

    /// The job's name, as `#[job]` registered the job.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// The connection the job came from, such as `database`.
    #[must_use]
    pub fn connection(&self) -> &str {
        &self.connection
    }

    /// The queue the job came from, such as `default`.
    #[must_use]
    pub fn queue(&self) -> &str {
        &self.queue
    }

    /// The number of this run, starting at 1.
    #[must_use]
    pub const fn number(&self) -> u32 {
        self.number
    }

    pub(crate) fn debounce_id(&self) -> Option<&str> {
        self.debounce_id.as_deref()
    }

    /// Put the job back on its queue to run again after `delay`.
    ///
    /// The next run is another attempt, so it counts toward the job's tries. The `sync` connection
    /// doesn't run released jobs again.
    pub fn release(&self, delay: impl Into<ZonedDateTimeArithmetic>) {
        self.request(Requested::Release(crate::clock::exact_duration(delay)));
    }

    /// Remove the job from its queue without running it again or failing it.
    pub fn delete(&self) {
        self.request(Requested::Delete);
    }

    /// Fail the job for good without retrying it, and run its `failed` hook with `error`.
    pub fn fail(&self, error: impl Into<Error>) {
        self.request(Requested::Fail(error.into()));
    }

    /// Fail the job for good after the job has already handled its own failure.
    ///
    /// For example, a workflow advance that has already recorded its run's failure calls this
    /// method. The worker shows the failure and deletes the job. It doesn't retry the job, store it
    /// with the failed jobs, run its `failed` hook, or report the error again. The job's chain ends,
    /// and its batch counts the job as failed.
    #[doc(hidden)]
    pub fn fail_settled(&self, error: Error) {
        self.request(Requested::Settle(error));
    }

    /// Run `jobs` next, in order, before the rest of the chain.
    ///
    /// `jobs` is a job, a tuple of jobs, or an iterable of jobs of one type. A job that isn't in a
    /// chain starts one. The jobs join the chain only if this attempt succeeds or deletes the job.
    ///
    /// If a job can't be encoded, this calls [`fail`](Self::fail) with the encoding error.
    pub fn prepend_to_chain<Kind>(&self, jobs: impl IntoJobs<Kind>) {
        match jobs.into_links() {
            Ok(links) => {
                self.effects().chain.splice(0..0, links);
            }
            Err(error) => self.fail(error),
        }
    }

    /// Run `jobs` in order at the end of the chain, after every job already in the chain.
    ///
    /// `jobs` is a job, a tuple of jobs, or an iterable of jobs of one type. A job that isn't in a
    /// chain starts one. The jobs join the chain only if this attempt succeeds or deletes the job.
    ///
    /// If a job can't be encoded, this calls [`fail`](Self::fail) with the encoding error.
    pub fn append_to_chain<Kind>(&self, jobs: impl IntoJobs<Kind>) {
        match jobs.into_links() {
            Ok(links) => self.effects().chain.extend(links),
            Err(error) => self.fail(error),
        }
    }

    /// The ID of the batch the job belongs to, or `None` when the job isn't in a batch.
    #[must_use]
    pub const fn batch_id(&self) -> Option<BatchId> {
        self.batch
    }

    /// Add `jobs` to this job's batch.
    ///
    /// `jobs` is a job or chain, a tuple of jobs and chains, or an iterable of jobs or chains. The
    /// new jobs join the batch only if this attempt succeeds or deletes the job, and they're
    /// dispatched to the same place as the batch's other jobs. The batch doesn't finish until the
    /// new jobs have run.
    ///
    /// If the job isn't one of a batch's jobs, or a job can't be encoded, this calls
    /// [`fail`](Self::fail) with the error.
    pub fn add_to_batch<Kind>(&self, jobs: impl IntoBatchJobs<Kind>) {
        if self.batch.is_none() {
            self.fail(crate::error::fail(format!(
                "the job `{}` added jobs to its batch, but it isn't one of a batch's jobs",
                self.name
            )));
            return;
        }

        match jobs.into_chains() {
            Ok(chains) => self.effects().batch.added.extend(chains),
            Err(error) => self.fail(error),
        }
    }

    /// Cancel this job's batch once this attempt ends, however the attempt ends.
    ///
    /// The batch skips its jobs that haven't run yet, and its `then` callbacks never run. When the
    /// job isn't in a batch, this method does nothing.
    pub fn cancel_batch(&self) {
        self.effects().batch.cancel = true;
    }

    fn request(&self, requested: Requested) {
        let replaced = self.effects().requested.replace(requested);
        drop(replaced);
    }

    fn effects(&self) -> MutexGuard<'_, Effects> {
        self.effects.lock().unwrap_or_else(PoisonError::into_inner)
    }

    pub(crate) fn take_effects(&self) -> Effects {
        std::mem::take(&mut *self.effects())
    }
}