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::any::type_name;
use std::collections::HashMap;
use std::future::Future;
use std::sync::LazyLock;

use futures_util::future::BoxFuture;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::fake::Dispatched;
use super::queueable::ModelRows;
use super::{Batch, MissingModels, Queueable};
use crate::context::{Context, Internals};
use crate::errors::panic;
use crate::{Error, Result};

/// A [`Queueable`] struct with `then`, `catch`, or `finally` methods that a batch or chain calls
/// directly, without queueing them, when it reaches each method's point.
///
/// Implement this trait with [`#[callback]`](macro@super::callback) on the struct's `impl` block.
/// The batch or chain stores the struct's fields until the callback runs, and the worker reads
/// the callback's models again before calling it.
pub trait Callback: Queueable {
    /// The name that the batch or chain stores the callback under and finds it by.
    const NAME: &'static str;

    /// Whether the callback reports a [`MissingModels`] error, rather than being skipped, when
    /// the row of one of its models is gone.
    const FAIL_WHEN_MISSING_MODELS: bool = false;
}

/// A callback with a `then` method, which a batch calls once every one of its jobs has
/// succeeded.
pub trait Then: Callback {
    #[doc(hidden)]
    fn then(self, batch: &Batch) -> impl Future<Output = Result<()>> + Send;
}

/// A callback with a `catch` method.
///
/// A batch calls the method when the first of its jobs fails for good, and a chain calls it when
/// any of its jobs fails for good.
pub trait Catch: Callback {
    #[doc(hidden)]
    fn catch(self, batch: Option<&Batch>, error: &Error) -> impl Future<Output = Result<()>> + Send;
}

/// A `catch` callback that doesn't take a `&Batch`, so a chain can call it too.
pub trait ChainCatch: Catch {}

/// A callback with a `finally` method, which a batch calls once every one of its jobs has run.
pub trait Finally: Callback {
    #[doc(hidden)]
    fn finally(self, batch: &Batch) -> impl Future<Output = Result<()>> + Send;
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EncodedCallback {
    pub(crate) callback: String,
    pub(crate) data: Value,
    #[serde(skip)]
    pub(crate) dispatched: Dispatched,
}

impl EncodedCallback {
    /// Encode `callback` into a storable payload.
    ///
    /// # Errors
    ///
    /// Fails when encoding the callback fails.
    #[expect(
        clippy::needless_pass_by_value,
        reason = "a chain or batch takes the callback, and only its payload outlives it"
    )]
    pub fn new<C: Callback>(callback: C) -> Result<Self> {
        let mut rows = ModelRows::new();
        let data = super::queueable::store("callback", C::NAME, &callback, &mut rows)?;

        Ok(Self {
            callback: C::NAME.to_owned(),
            data,
            dispatched: Dispatched::new(rows),
        })
    }

    pub(crate) async fn call(&self, point: Point<'_>, context: &Context) {
        if let Err(error) = self.run(point).await {
            context.report(error);
        }
    }

    /// Decode and call the callback at `point` the way [`call`](Self::call) does, but without
    /// reporting its error.
    ///
    /// # Errors
    ///
    /// Fails when the callback isn't registered, fails to decode, returns an error, or panics.
    pub async fn run(&self, point: Point<'_>) -> Result<()> {
        let called = match registry().get(self.callback.as_str()) {
            Some(registration) => registration.call(self.data.clone(), point),
            None => Err(crate::error::fail(format!(
                "no callback named `{}` is registered: was it renamed, or removed, after it was dispatched?",
                self.callback
            ))),
        };
        match called {
            Ok(future) => panic::catch(future).await,
            Err(error) => Err(error),
        }
    }
}

#[derive(Clone, Copy)]
pub enum Point<'a> {
    Then(&'a Batch),
    Catch(Option<&'a Batch>, &'a Error),
    Finally(&'a Batch),
}

impl<'a> std::fmt::Debug for Point<'a> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.debug_struct("Point").finish_non_exhaustive()
    }
}

type OnBatch = for<'a> fn(Value, &'a Batch) -> BoxFuture<'a, Result<()>>;
type OnCatch = for<'a> fn(Value, Option<&'a Batch>, &'a Error) -> BoxFuture<'a, Result<()>>;

/// A callback type that a batch or chain can call by name, registered by
/// [`#[callback]`](macro@super::callback).
#[doc(hidden)]
#[derive(Debug)]
pub struct __CallbackRegistration {
    name: &'static str,
    type_name: fn() -> &'static str,
    then: Option<OnBatch>,
    catch: Option<OnCatch>,
    finally: Option<OnBatch>,
}

impl __CallbackRegistration {
    #[must_use]
    pub const fn new<C: Callback>() -> Self {
        Self {
            name: C::NAME,
            type_name: type_name::<C>,
            then: None,
            catch: None,
            finally: None,
        }
    }

    #[must_use]
    pub const fn then<C: Then>(mut self) -> Self {
        self.then = Some(then::<C>);
        self
    }

    #[must_use]
    pub const fn catch<C: Catch>(mut self) -> Self {
        self.catch = Some(catch::<C>);
        self
    }

    #[must_use]
    pub const fn finally<C: Finally>(mut self) -> Self {
        self.finally = Some(finally::<C>);
        self
    }

    fn call<'a>(&self, data: Value, point: Point<'a>) -> Result<BoxFuture<'a, Result<()>>> {
        let (method, called) = match point {
            Point::Then(batch) => ("then", self.then.map(|then| then(data, batch))),
            Point::Catch(batch, error) => ("catch", self.catch.map(|catch| catch(data, batch, error))),
            Point::Finally(batch) => ("finally", self.finally.map(|finally| finally(data, batch))),
        };

        called.ok_or_else(|| crate::error::fail(format!("the callback `{}` has no `{method}` method", self.name)))
    }
}

inventory::collect!(__CallbackRegistration);

fn then<C: Then>(data: Value, batch: &Batch) -> BoxFuture<'_, Result<()>> {
    Box::pin(async move {
        match restore_unless_missing::<C>(data).await? {
            Some(callback) => callback.then(batch).await,
            None => Ok(()),
        }
    })
}

fn catch<'a, C: Catch>(data: Value, batch: Option<&'a Batch>, error: &'a Error) -> BoxFuture<'a, Result<()>> {
    Box::pin(async move {
        match restore_unless_missing::<C>(data).await? {
            Some(callback) => callback.catch(batch, error).await,
            None => Ok(()),
        }
    })
}

fn finally<C: Finally>(data: Value, batch: &Batch) -> BoxFuture<'_, Result<()>> {
    Box::pin(async move {
        match restore_unless_missing::<C>(data).await? {
            Some(callback) => callback.finally(batch).await,
            None => Ok(()),
        }
    })
}

/// Restore the callback, or return `None` to skip it when one of its models' rows is gone and it
/// doesn't ask to fail.
async fn restore_unless_missing<C: Callback>(data: Value) -> Result<Option<C>> {
    match restore::<C>(data).await {
        Ok(callback) => Ok(Some(callback)),
        Err(error) if error.is::<MissingModels>() && !C::FAIL_WHEN_MISSING_MODELS => {
            crate::foundation::telemetry::logging(
                &error,
                || tracing::info!(target: "laravel::queue", callback = C::NAME, %error, "Skipped a callback whose models are gone"),
            );

            Ok(None)
        }
        Err(error) => Err(error),
    }
}

pub(crate) async fn restore<C: Callback>(data: Value) -> Result<C> {
    C::__restore(data)
        .await
        .map_err(|error| super::queueable::restore_error("callback", C::NAME, error))
}

fn registry() -> &'static HashMap<&'static str, &'static __CallbackRegistration> {
    static REGISTRY: LazyLock<HashMap<&'static str, &'static __CallbackRegistration>> = LazyLock::new(|| {
        inventory::iter::<__CallbackRegistration>
            .into_iter()
            .map(|registration| (registration.name, registration))
            .collect()
    });

    &REGISTRY
}

pub(crate) fn check_names() -> Result<(), String> {
    super::job::duplicate_names(
        "callbacks",
        "#[callback(name = \"..\")]",
        inventory::iter::<__CallbackRegistration>
            .into_iter()
            .map(|registration| (registration.name, (registration.type_name)())),
    )
}