laractions 0.1.0

Actions for Laravel Rust: encapsulate business logic in classes that run now or on the queue.
Documentation
use laravel::queue::{Attempt, Queueable, job};
use serde_json::Value;

use crate::action::Reference;
use crate::arguments::Arguments;
use crate::registry;

/// The most times any queued action may run.
///
/// Laravel Rust fixes a job's `tries` on its type, while PHP sets them per dispatch with
/// `retry()`. The job allows this many, and counts the action's own `tries` itself.
pub const MAX_TRIES: u32 = 100;

/// The queued wrapper of an action, PHP's `ActionJob`. `dispatch()` builds one for you.
///
/// It carries the action's own state, the arguments, the model and the actor, and runs the action
/// again where the worker is.
#[derive(Queueable)]
pub struct ActionJob {
    /// The action's name.
    pub action: String,
    /// The action, serialized: whatever `with()` set.
    pub state: Value,
    /// The arguments `dispatch` received.
    pub arguments: Arguments,
    /// The model the action works on. The worker loads it again.
    pub actionable: Option<Reference>,
    /// Who performs the action.
    pub actor: Option<Reference>,
    /// How many times the action may run.
    pub tries: u32,
    /// Whether dispatching was logged.
    pub logging: bool,
    /// Whether the run is traced.
    pub tracing: bool,
}

#[job(name = "laractions.action", tries = 100)]
impl ActionJob {
    async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
        let registration = registry::find(&self.action)?;
        let tries = self.tries.clamp(1, MAX_TRIES);

        match registration.run(&self).await {
            Ok(()) => Ok(()),
            Err(error) if attempt.number() >= tries => {
                attempt.fail(error);

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

    /// Log a job that failed for good, as PHP's `failed()` does.
    pub async fn failed(self, error: &laravel::Error) {
        tracing::error!(
            target: "laractions",
            exception = ?error,
            "[ActionJob: {}] Job failed: {error}",
            self.action
        );
    }
}