laractions 0.1.0

Actions for Laravel Rust: encapsulate business logic in classes that run now or on the queue.
Documentation
use std::any::Any;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, LazyLock};

use laravel::queue::JobId;

use crate::action::{Action, Pending, Reference, Settings};
use crate::arguments::Arguments;
use crate::error::ActionError;
use crate::job::ActionJob;

type Boxed<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
type Output = Box<dyn Any + Send>;

/// What an action run by name receives: the settings, the actor, the model and the arguments.
pub(crate) struct Call {
    pub settings: Settings,
    pub actor: Option<Reference>,
    pub actionable: Option<Reference>,
    pub model: Option<Arc<dyn Any + Send + Sync>>,
    pub arguments: Arguments,
}

/// An action the application has, registered by `#[action]`.
#[derive(Debug)]
pub struct Registration {
    name: &'static str,
    type_name: fn() -> &'static str,
    settings: fn() -> Settings,
    run_job: for<'a> fn(&'a ActionJob) -> Boxed<'a, laravel::Result<()>>,
    run: fn(Call) -> Boxed<'static, laravel::Result<Output>>,
    dispatch: fn(Call) -> Boxed<'static, laravel::Result<JobId>>,
}

impl Registration {
    /// The registration of an action. `#[action]` calls this.
    #[must_use]
    pub const fn new<A: Action>() -> Self {
        Self {
            name: A::NAME,
            type_name: std::any::type_name::<A>,
            settings: Settings::of::<A>,
            run_job: |job| {
                Box::pin(async move {
                    Pending::<A>::restore(job)
                        .await?
                        .run_arguments(job.arguments.clone())
                        .await
                        .map(drop)
                })
            },
            run: |call| {
                Box::pin(async move {
                    let output = pending::<A>(&call).run_arguments(call.arguments).await?;

                    Ok(Box::new(output) as Output)
                })
            },
            dispatch: |call| Box::pin(async move { pending::<A>(&call).dispatch(call.arguments.clone()).await }),
        }
    }

    /// The name the action is registered under.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// The type's path, as the compiler spells it.
    #[must_use]
    pub fn type_name(&self) -> &'static str {
        (self.type_name)()
    }

    pub(crate) fn settings(&self) -> Settings {
        (self.settings)()
    }

    pub(crate) fn run<'a>(&self, job: &'a ActionJob) -> Boxed<'a, laravel::Result<()>> {
        (self.run_job)(job)
    }

    pub(crate) fn run_named(&self, call: Call) -> Boxed<'static, laravel::Result<Output>> {
        (self.run)(call)
    }

    pub(crate) fn dispatch_named(&self, call: Call) -> Boxed<'static, laravel::Result<JobId>> {
        (self.dispatch)(call)
    }
}

fn pending<A: Action>(call: &Call) -> Pending<A> {
    let mut pending = Pending::new(A::default());

    pending.configure(
        call.settings.clone(),
        call.actor.clone(),
        call.actionable.clone(),
        call.model.as_deref(),
    );

    pending
}

laravel::__inventory::collect!(Registration);

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

    &REGISTRY
}

/// Every action the application registered, ordered by name.
#[must_use]
pub fn all() -> Vec<&'static Registration> {
    let mut all: Vec<_> = registry().values().copied().collect();

    all.sort_by_key(|registration| registration.name);

    all
}

/// The registration of an action, by name.
///
/// # Errors
///
/// Fails with [`ActionError::Unknown`] when no action has this name.
pub fn find(name: &str) -> laravel::Result<&'static Registration> {
    registry()
        .get(name)
        .copied()
        .ok_or_else(|| ActionError::Unknown { name: name.to_owned() }.into())
}

/// Fail the build of the application when two actions share a name.
///
/// # Errors
///
/// Fails naming the types that collide.
pub fn check_names() -> Result<(), String> {
    let mut named: HashMap<&str, Vec<&str>> = HashMap::new();

    for registration in laravel::__inventory::iter::<Registration> {
        named
            .entry(registration.name)
            .or_default()
            .push(registration.type_name());
    }

    let mut duplicates: Vec<_> = named.into_iter().filter(|(_, types)| types.len() > 1).collect();

    duplicates.sort_unstable();

    match duplicates.first() {
        None => Ok(()),
        Some((name, types)) => Err(format!(
            "the actions {} are all named `{name}`: give each its own `#[action(name = \"..\")]`",
            types
                .iter()
                .map(|ty| format!("`{ty}`"))
                .collect::<Vec<_>>()
                .join(" and ")
        )),
    }
}