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::sync::Arc;

use laravel::model::Model;

use crate::action::{Action, Pending, Reference, Settings};
use crate::arguments::{Arguments, IntoArguments};
use crate::error::ActionError;
use crate::registry::{self, Call, Registration};

/// The actions a model lists under a key, PHP's `$actions` array.
///
/// ```ignore
/// impl HasActions for User {
///     fn actions() -> Actions {
///         actions! { "send_email" => SendEmail }
///     }
/// }
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Actions(Vec<(&'static str, &'static str)>);

impl Actions {
    /// An empty list.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an action under a key.
    #[must_use]
    pub fn with<A: Action>(mut self, key: &'static str) -> Self {
        self.0.push((key, A::NAME));

        self
    }

    /// The name of the action listed under a key.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&'static str> {
        self.0.iter().find(|(listed, _)| *listed == key).map(|(_, name)| *name)
    }
}

/// Build the [`Actions`] of a model: `actions! { "send_email" => SendEmail }`.
#[macro_export]
macro_rules! actions {
    ($($key:expr => $action:ty),* $(,)?) => {
        $crate::Actions::new()$(.with::<$action>($key))*
    };
}

/// A model that has actions, PHP's `HasActions` trait.
///
/// ```ignore
/// impl HasActions for User {}
///
/// user.action::<SendEmail>().run(("user@example.com", "Welcome!")).await?;
/// ```
pub trait HasActions: Model {
    /// The actions the model lists under a key. Empty by default.
    #[must_use]
    fn actions() -> Actions {
        Actions::new()
    }

    /// The action of this type, with the model bound to it: PHP's `$user->action(SendEmail::class)`.
    #[must_use]
    fn action<A: Action>(&self) -> Pending<A> {
        A::create().on(self)
    }

    /// The action listed under a key, with the model bound to it: PHP's `$user->action('send_email')`.
    ///
    /// The name of an action works as a key too. The result is not typed, so `run` hands back a
    /// `Box<dyn Any>` to downcast.
    ///
    /// # Errors
    ///
    /// Fails when the model does not list the key and no action is registered under it.
    fn action_named(&self, key: &str) -> laravel::Result<NamedAction> {
        let name = Self::actions().get(key).unwrap_or(key);
        let registration = registry::find(name).map_err(|_| ActionError::NotDefined { key: key.to_owned() })?;

        Ok(NamedAction {
            registration,
            settings: registration.settings(),
            actor: None,
            actionable: Some(Reference::of(self)),
            model: Some(Arc::new(self.clone())),
        })
    }
}

/// A model that performs actions, PHP's `IsActor` trait.
///
/// ```ignore
/// impl IsActor for User {}
///
/// user.act::<SendInvoice>().on(&order).trace().run(()).await?;
/// ```
pub trait IsActor: Model {
    /// The action of this type, with this model as its actor.
    #[must_use]
    fn act<A: Action>(&self) -> Pending<A> {
        A::create().actor(self)
    }

    /// The action registered under a name, with this model as its actor.
    ///
    /// # Errors
    ///
    /// Fails when no action is registered under the name.
    fn act_named(&self, name: &str) -> laravel::Result<NamedAction> {
        let registration = registry::find(name)?;

        Ok(NamedAction {
            registration,
            settings: registration.settings(),
            actor: Some(Reference::of(self)),
            actionable: None,
            model: None,
        })
    }
}

/// An action looked up by name, which is how a key of `$actions` reaches it.
pub struct NamedAction {
    registration: &'static Registration,
    settings: Settings,
    actor: Option<Reference>,
    actionable: Option<Reference>,
    model: Option<Arc<dyn Any + Send + Sync>>,
}

impl NamedAction {
    /// Set who performs the action.
    #[must_use]
    pub fn actor<M: Model>(mut self, actor: &M) -> Self {
        self.actor = Some(Reference::of(actor));

        self
    }

    /// Set how many times the queued action may run.
    #[must_use]
    pub fn retry(mut self, times: u32) -> Self {
        self.settings.tries = times;

        self
    }

    /// Set the seconds a queued action waits before it runs.
    #[must_use]
    pub fn delay(mut self, seconds: u64) -> Self {
        self.settings.delay = Some(seconds);

        self
    }

    /// Set the queue a queued action joins.
    #[must_use]
    pub fn queue(mut self, queue: impl Into<String>) -> Self {
        self.settings.queue = Some(queue.into());

        self
    }

    /// Record each run in `action_traces`.
    #[must_use]
    pub fn trace(mut self) -> Self {
        self.settings.tracing = true;

        self
    }

    /// Log when the action is dispatched.
    #[must_use]
    pub fn enable_logging(mut self) -> Self {
        self.settings.logging = true;

        self
    }

    fn call(&self, arguments: Arguments) -> Call {
        Call {
            settings: self.settings.clone(),
            actor: self.actor.clone(),
            actionable: self.actionable.clone(),
            model: self.model.clone(),
            arguments,
        }
    }

    /// Run the action now. Downcast the output to what `handle` returns.
    ///
    /// # Errors
    ///
    /// Fails as [`Pending::run`] does.
    pub async fn run(&self, arguments: impl IntoArguments) -> laravel::Result<Box<dyn Any + Send>> {
        self.registration
            .run_named(self.call(arguments.into_arguments()?))
            .await
    }

    /// Run the action on the queue.
    ///
    /// # Errors
    ///
    /// Fails as [`Pending::dispatch`] does.
    pub async fn dispatch(&self, arguments: impl IntoArguments) -> laravel::Result<laravel::queue::JobId> {
        self.registration
            .dispatch_named(self.call(arguments.into_arguments()?))
            .await
    }
}