laractions 0.1.0

Actions for Laravel Rust: encapsulate business logic in classes that run now or on the queue.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use std::any::Any;
use std::future::Future;

use laravel::model::Model;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::arguments::{self, Arguments, IntoArguments, Parameter, Resolved};
use crate::job::ActionJob;
use crate::trace;
use crate::validation;

/// A model, as an action knows it: its morph name and its key.
///
/// This is what PHP keeps as `getMorphClass()` and `getKey()` for the actor and the actionable.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Reference {
    /// The morph name of the model, such as `user`.
    pub morph: String,
    /// The model's key.
    pub key: Value,
}

impl Reference {
    /// The reference to a model.
    #[must_use]
    pub fn of<M: Model>(model: &M) -> Self {
        Self {
            morph: M::META.morph.to_owned(),
            key: serde_json::to_value(M::META.key.get(model)).unwrap_or(Value::Null),
        }
    }

    /// The key as the text the traces table stores.
    #[must_use]
    pub fn key_text(&self) -> String {
        match &self.key {
            Value::String(text) => text.clone(),
            other => other.to_string(),
        }
    }
}

/// An action: business logic in a struct that runs now or on the queue.
///
/// Do not implement this trait by hand. Write the struct, derive `Default`, `Serialize` and
/// `Deserialize` for it, and put `#[action]` on an impl with a `handle` method:
///
/// ```ignore
/// #[derive(Default, Serialize, Deserialize)]
/// pub struct SendEmail {}
///
/// #[action(tries = 3)]
/// impl SendEmail {
///     async fn handle(&self, email: String, subject: String) -> laravel::Result<()> {
///         Ok(())
///     }
/// }
///
/// SendEmail::create().run(("user@example.com", "Welcome!")).await?;
/// ```
///
/// The struct is serialized into the queue payload, so what `with()` sets and what the action
/// carries travels with the job, as PHP serializes the action object.
pub trait Action: Default + Serialize + DeserializeOwned + Send + Sync + 'static {
    /// What `handle` returns.
    type Output: Send + 'static;

    /// The name the queue stores the action under. It defaults to the type's path, so give the
    /// action `#[action(name = "..")]` to keep it when the type moves.
    const NAME: &'static str;

    /// How many times the queued action may run, PHP's `$tries`.
    #[must_use]
    fn tries() -> u32 {
        1
    }

    /// Seconds a queued action waits before it runs, PHP's `$delay`.
    #[must_use]
    fn delay() -> Option<u64> {
        None
    }

    /// The queue a queued action joins, PHP's `$queue`.
    #[must_use]
    fn queue() -> Option<&'static str> {
        None
    }

    /// Validation rules by parameter, PHP's `$rules`.
    #[must_use]
    fn rules() -> &'static [(&'static str, &'static str)] {
        &[]
    }

    /// The parameters of `handle`, without the ones the container injects.
    #[must_use]
    fn parameters() -> &'static [Parameter];

    /// Call `handle` with the resolved arguments.
    fn invoke<'a>(&'a self, arguments: Resolved) -> impl Future<Output = laravel::Result<Self::Output>> + Send + 'a;

    /// Put a model into the field named after its type, when the action declares it with
    /// `#[action(model = ..)]`. Returns whether it did.
    fn bind(&mut self, model: &(dyn Any + Send + Sync)) -> bool {
        let _ = model;

        false
    }

    /// Load the model of a queued action again and bind it. Returns whether the action declares it.
    fn rebind<'a>(
        &'a mut self,
        morph: &'a str,
        key: &'a Value,
    ) -> impl Future<Output = laravel::Result<bool>> + Send + 'a {
        let _ = (morph, key);

        async { Ok(false) }
    }

    /// Create the action, ready to be configured and run. PHP resolves it through the container;
    /// here it is the type's `Default`, and services reach `handle` as `Inject<T>` parameters.
    #[must_use]
    fn create() -> Pending<Self> {
        Pending::new(Self::default())
    }

    /// Log a message from the action, as PHP's protected `log()`.
    fn log(&self, message: &str) {
        tracing::info!(target: "laractions", action = Self::NAME, "[Action: {}] {message}", Self::NAME);
    }
}

/// How an action runs, PHP's `$tries`, `$delay`, `$queue` and the two switches.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Settings {
    /// Times the queued action may run.
    pub tries: u32,
    /// Seconds before the queued action runs.
    pub delay: Option<u64>,
    /// The queue.
    pub queue: Option<String>,
    /// Whether dispatching is logged.
    pub logging: bool,
    /// Whether runs are recorded in `action_traces`.
    pub tracing: bool,
}

impl Settings {
    pub(crate) fn of<A: Action>() -> Self {
        Self {
            tries: A::tries(),
            delay: A::delay(),
            queue: A::queue().map(str::to_owned),
            logging: false,
            tracing: false,
        }
    }
}

/// An action and everything that decides how it runs: the settings, the actor and the model.
///
/// This is what PHP's `Action` instance is. `Action::create()` returns it, and its methods are
/// the fluent chain: `with`, `on`, `actor`, `retry`, `delay`, `queue`, `trace`,
/// `enable_logging`, then `run` or `dispatch`.
pub struct Pending<A: Action> {
    action: A,
    settings: Settings,
    actor: Option<Reference>,
    actionable: Option<Reference>,
    error: Option<laravel::Error>,
}

impl<A: Action> Pending<A> {
    pub(crate) fn new(action: A) -> Self {
        Self {
            action,
            settings: Settings::of::<A>(),
            actor: None,
            actionable: None,
            error: None,
        }
    }

    /// The action itself, to read what `with()` set.
    #[must_use]
    pub fn action(&self) -> &A {
        &self.action
    }

    /// The action itself.
    #[must_use]
    pub fn into_action(self) -> A {
        self.action
    }

    /// How the action runs.
    #[must_use]
    pub fn settings(&self) -> &Settings {
        &self.settings
    }

    /// Set fields of the action, by name. Names the action has no field for are ignored.
    ///
    /// ```ignore
    /// SendEmail::create().with(args! { email: "user@example.com" }).run(()).await?;
    /// ```
    #[must_use]
    pub fn with(mut self, attributes: impl IntoArguments) -> Self {
        let result = attributes.into_arguments().and_then(|arguments| self.fill(arguments));

        if let Err(error) = result {
            self.error.get_or_insert(error);
        }

        self
    }

    fn fill(&mut self, arguments: Arguments) -> laravel::Result<()> {
        let attributes = match arguments {
            Arguments::Named(map) | Arguments::Array(Value::Object(map)) => map,
            _ => return Ok(()),
        };

        let mut fields = match serde_json::to_value(&self.action)? {
            Value::Object(fields) => fields,
            _ => Map::new(),
        };

        for (name, value) in attributes {
            if fields.contains_key(&name) {
                fields.insert(name, value);
            }
        }

        self.action = serde_json::from_value(Value::Object(fields))?;

        Ok(())
    }

    /// Set the model the action works on, and bind it to the field named after its type.
    #[must_use]
    pub fn on<M: Model>(mut self, model: &M) -> Self {
        self.action.bind(model);
        self.actionable = Some(Reference::of(model));

        self
    }

    /// 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 the model the action works on, from a reference, when the model itself is not at hand.
    #[must_use]
    pub fn on_reference(mut self, reference: Reference) -> Self {
        self.actionable = Some(reference);

        self
    }

    /// Set the actor from a reference.
    #[must_use]
    pub fn actor_reference(mut self, reference: Reference) -> Self {
        self.actor = Some(reference);

        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
    }

    /// Log when the action is dispatched.
    #[must_use]
    pub fn enable_logging(self) -> Self {
        self.enable_logging_as(true)
    }

    /// Turn dispatch logging on or off.
    #[must_use]
    pub fn enable_logging_as(mut self, enabled: bool) -> Self {
        self.settings.logging = enabled;

        self
    }

    /// Record each run in `action_traces`.
    #[must_use]
    pub fn trace(self) -> Self {
        self.trace_as(true)
    }

    /// Turn tracing on or off.
    #[must_use]
    pub fn trace_as(mut self, enabled: bool) -> Self {
        self.settings.tracing = enabled;

        self
    }

    /// How many times the queued action may run.
    #[must_use]
    pub fn get_tries(&self) -> u32 {
        self.settings.tries
    }

    /// The model the action works on.
    #[must_use]
    pub fn get_actionable(&self) -> Option<&Reference> {
        self.actionable.as_ref()
    }

    /// Who performs the action.
    #[must_use]
    pub fn get_actor(&self) -> Option<&Reference> {
        self.actor.as_ref()
    }

    /// Run the action now: match the arguments to `handle`, validate them, call it.
    ///
    /// # Errors
    ///
    /// Fails with the validation errors, with an [`ActionError`](crate::ActionError) when an
    /// argument does not fit, or with whatever `handle` returns.
    pub async fn run(&self, arguments: impl IntoArguments) -> laravel::Result<A::Output> {
        if let Some(error) = &self.error {
            return Err(laravel::Error::msg(error.to_string()));
        }

        self.run_arguments(arguments.into_arguments()?).await
    }

    pub(crate) async fn run_arguments(&self, arguments: Arguments) -> laravel::Result<A::Output> {
        let parameters = A::parameters();
        let bound = arguments::bind(parameters, arguments);

        validation::validate(A::NAME, A::rules(), &bound.resolved).await?;

        if let Some(array) = &bound.spread
            && let Some(error) = arguments::explain_unbound_array(A::NAME, parameters, array, &bound.resolved)
        {
            return Err(error.into());
        }

        let output = self.action.invoke(Resolved::new(bound.resolved.clone())).await?;

        if self.settings.tracing {
            trace::record(A::NAME, self.actor.as_ref(), self.actionable.as_ref(), &bound.resolved).await?;
        }

        Ok(output)
    }

    /// Run the action on the queue.
    ///
    /// The job carries the action, the arguments and the model's key. The worker loads the model
    /// again and runs the action with the same settings.
    ///
    /// # Errors
    ///
    /// Fails when the job cannot be pushed. With the `sync` queue connection the action runs here,
    /// and its error comes back.
    pub async fn dispatch(&self, arguments: impl IntoArguments) -> laravel::Result<laravel::queue::JobId> {
        let job = self.job(arguments.into_arguments()?)?;
        let delay = self.settings.delay.unwrap_or(0);

        if self.settings.logging {
            tracing::info!(
                target: "laractions",
                queue = self.settings.queue.as_deref().unwrap_or("default"),
                delay,
                tries = self.settings.tries,
                params = %job.arguments,
                "[Action: {}] Dispatching job.",
                A::NAME
            );
        }

        let mut pending = job.dispatch();

        if let Some(queue) = &self.settings.queue {
            pending = pending.on_queue(queue.clone());
        }

        if delay > 0 {
            pending = pending.delay(delay_span(delay));
        }

        pending.await
    }

    /// Run the action through its job, on this process, without touching the queue.
    ///
    /// # Errors
    ///
    /// Fails with what the job fails with.
    pub async fn dispatch_sync(&self, arguments: impl IntoArguments) -> laravel::Result<()> {
        self.job(arguments.into_arguments()?)?.dispatch_sync().await
    }

    fn job(&self, arguments: Arguments) -> laravel::Result<ActionJob> {
        if let Some(error) = &self.error {
            return Err(laravel::Error::msg(error.to_string()));
        }

        Ok(ActionJob {
            action: A::NAME.to_owned(),
            state: serde_json::to_value(&self.action)?,
            arguments,
            actionable: self.actionable.clone(),
            actor: self.actor.clone(),
            tries: self.settings.tries,
            logging: self.settings.logging,
            tracing: self.settings.tracing,
        })
    }

    pub(crate) fn configure(
        &mut self,
        settings: Settings,
        actor: Option<Reference>,
        actionable: Option<Reference>,
        model: Option<&(dyn Any + Send + Sync)>,
    ) {
        if let Some(model) = model {
            self.action.bind(model);
        }

        self.settings = settings;
        self.actor = actor;
        self.actionable = actionable;
    }

    /// Rebuild an action from what a job carries.
    pub(crate) async fn restore(job: &ActionJob) -> laravel::Result<Self> {
        let mut action: A = serde_json::from_value(job.state.clone())?;

        if let Some(reference) = &job.actionable {
            action.rebind(&reference.morph, &reference.key).await?;
        }

        Ok(Self {
            action,
            settings: Settings {
                tries: job.tries,
                delay: None,
                queue: None,
                logging: job.logging,
                tracing: job.tracing,
            },
            actor: job.actor.clone(),
            actionable: job.actionable.clone(),
            error: None,
        })
    }
}

fn delay_span(seconds: u64) -> laravel::time::Moment {
    use laravel::time::ToSpan;

    i64::try_from(seconds).unwrap_or(i64::MAX).seconds().into()
}