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
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Storing jobs, queued listeners' events, and callbacks in a payload, with their models as keys.

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;

use futures_util::future::BoxFuture;
use serde::Serialize;
use serde::de::DeserializeOwned;
pub use serde_json::{Map, Value};

use crate::Result;

/// A [job](super::Job), a [queued listener](crate::event::QueuedListener)'s event, or a
/// [callback](super::Callback) that the queue can store until a worker runs it.
///
/// Derive this trait with [`#[derive(Queueable)]`](derive@Queueable). When a field's type is a
/// model, an `Option` of a model, or a `Vec` of models, the queue stores the models' keys, and the
/// worker reads the rows again before the job runs. The queue stores every other field as JSON,
/// so the field's type must implement `Serialize` and `Deserialize`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` can't be stored on the queue",
    label = "expected a type that derives `laravel::queue::Queueable`",
    note = "add `#[derive(laravel::queue::Queueable)]` to `{Self}`"
)]
pub trait Queueable: Send + Sync + Sized + 'static {
    /// Encode the value for its payload, with each model as its key. Each model goes into `rows`
    /// too, without its relationships, for [`__assemble`](Self::__assemble).
    #[doc(hidden)]
    fn __store(&self, rows: &mut ModelRows) -> Result<Value>;

    /// Decode the value from its payload, as a queue fake does: each model comes from the `rows`
    /// that `__store` filled, not from the database, so it's the dispatched model without its
    /// relationships, as a worker would read it.
    #[doc(hidden)]
    fn __assemble(stored: Value, rows: &ModelRows) -> Result<Self>;

    /// Decode the value from its payload, reading each model's row from the database.
    #[doc(hidden)]
    fn __restore(stored: Value) -> impl Future<Output = Result<Self>> + Send;
}

/// How a derived `Queueable` decodes its fields: each takes its stored value, and model fields
/// add their keys to `rows`.
#[doc(hidden)]
pub type Collect<T> = fn(Value, &mut ModelRows) -> Result<Pending<T>>;

/// A derived `__assemble`: decode the fields, and take each model from `rows`.
///
/// # Errors
///
/// Fails when a field doesn't decode.
#[doc(hidden)]
pub fn __assemble<T>(stored: Value, collect: Collect<T>, rows: &ModelRows) -> Result<T> {
    Ok(collect(stored, &mut ModelRows::new())?.finish(rows))
}

/// A derived `__restore`: decode the fields, read every model in one query per type, then
/// assemble the value.
///
/// # Errors
///
/// Fails when a field doesn't decode, with [`MissingModels`] when a row is gone, or when a query
/// fails.
#[doc(hidden)]
pub async fn __restore<T>(stored: Value, collect: Collect<T>) -> Result<T> {
    let mut rows = ModelRows::new();
    let pending = collect(stored, &mut rows)?;
    rows.load().await?;

    Ok(pending.finish(&rows))
}

/// Implement [`Queueable`] for a framework job stored as JSON, with no model fields.
#[doc(hidden)]
#[macro_export]
macro_rules! __serde_queueable {
    ($ty:ty $(, $param:ident: $bound:path)?) => {
        impl$(<$param: $bound>)? $crate::queue::Queueable for $ty
        where
            Self: ::serde::Serialize + ::serde::de::DeserializeOwned + Send + Sync,
        {
            fn __store(&self, _: &mut $crate::queue::__queueable::ModelRows) -> $crate::Result<::serde_json::Value> {
                Ok(::serde_json::to_value(self)?)
            }

            fn __assemble(
                stored: ::serde_json::Value,
                _: &$crate::queue::__queueable::ModelRows,
            ) -> $crate::Result<Self> {
                ::serde_json::from_value(stored).map_err($crate::queue::__queueable::__undecodable)
            }

            async fn __restore(stored: ::serde_json::Value) -> $crate::Result<Self> {
                ::serde_json::from_value(stored).map_err($crate::queue::__queueable::__undecodable)
            }
        }
    };
}

#[doc(hidden)]
pub use crate::__serde_queueable as serde_queueable;

/// Implement [`Queueable`] so that the queue can store the struct, with its model fields stored
/// as keys.
///
/// ```no_run
/// # use laravel::model::{model, update};
/// # #[model] pub struct User { pub id: i64, pub name: String, pub welcomed: bool }
/// use laravel::queue::{Queueable, job};
///
/// #[derive(Queueable)]
/// pub struct SendWelcomeEmail {
///     pub user: User,
///     pub note: String,
/// }
///
/// #[job]
/// impl SendWelcomeEmail {
///     async fn handle(mut self) -> laravel::Result<()> {
///         update!(self.user { welcomed: true }).await?;
///
///         Ok(())
///     }
/// }
/// ```
///
/// The queue stores a model field as the model's key, an `Option` of a model as the key or
/// `null`, and a `Vec` of models as an array of keys. For example, it stores the job above as
/// `{"user": 42, "note": "Hi"}`. The queue stores every other field as JSON through the field's
/// `Serialize` and `Deserialize` implementations, including a model nested inside another field's
/// type.
///
/// Before the job runs, the worker reads the rows from the database's writer connection, with one
/// query per model type and without relationships. A `Vec` field leaves out the models whose rows
/// are gone and keeps the rest in their stored order. When the row of a model field or an
/// `Option` field is gone, the worker deletes the job without running it. With the
/// `fail_when_missing_models` option, the job fails for good with a [`MissingModels`] error
/// instead.
///
/// A field may take the following `#[serde(..)]` attributes, which have Serde's meaning. They
/// let jobs that are already on the queue still run after you change the field:
///
/// | Attribute | Meaning |
/// | --- | --- |
/// | `default` | A job stored without the field gets `Default::default()`. A model field must be an `Option` or a `Vec` |
/// | `default = "path"` | A job stored without the field gets the value the function returns. Not on a model field |
/// | `rename = "name"` | Store and read the field under `name` |
/// | `alias = "name"` | Also read the field from `name`. May repeat |
///
/// Any other `#[serde(..)]` attribute, on a field or on the struct, is a compile error:
///
/// ```compile_fail
/// #[derive(laravel::queue::Queueable)]
/// pub struct SendReport {
///     #[serde(skip)]
///     pub draft: String,
/// }
/// ```
///
/// A model has no default value, so a model field that isn't an `Option` or a `Vec` can't take
/// `default`:
///
/// ```compile_fail
/// # use laravel::model::model;
/// # #[model] pub struct User { pub id: i64 }
/// #[derive(laravel::queue::Queueable)]
/// pub struct SendWelcomeEmail {
///     #[serde(default)]
///     pub user: User,
/// }
/// ```
///
/// The struct can't be generic:
///
/// ```compile_fail
/// #[derive(laravel::queue::Queueable)]
/// pub struct Generic<T> { pub value: T }
/// ```
pub use laravel_rust_queue_macros::Queueable;

/// The error for a queued job, listener, or callback that can't run because the rows of some of
/// its models are gone.
///
/// The worker deletes the job, or skips the callback, without running it. With the
/// `fail_when_missing_models` option, the job fails for good with this error instead, without a
/// retry and without running its `failed` hook, and a callback reports it.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub struct MissingModels {
    model: &'static str,
    keys: Vec<String>,
}

impl MissingModels {
    /// The missing model's name, such as `User`.
    #[must_use]
    pub const fn model(&self) -> &'static str {
        self.model
    }

    /// The keys that matched no row.
    #[must_use]
    pub fn keys(&self) -> &[String] {
        &self.keys
    }
}

impl fmt::Display for MissingModels {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let keys = self
            .keys
            .iter()
            .map(|key| format!("`{key}`"))
            .collect::<Vec<_>>()
            .join(", ");
        let noun = if self.keys.len() == 1 { "key" } else { "keys" };
        write!(f, "no `{}` has the {noun} {keys} any more", self.model)
    }
}

/// A payload whose data doesn't match the type it names, which a retry can't fix.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub(crate) struct Undecodable(pub(crate) String);

/// `Undecodable`, as a [`crate::Error`].
#[doc(hidden)]
pub fn __undecodable(message: impl fmt::Display) -> crate::Error {
    Undecodable(message.to_string()).into()
}

/// The fields of a stored struct, which a derived `__restore` takes one at a time.
#[doc(hidden)]
#[derive(Debug)]
pub struct Fields(Map<String, Value>);

impl Fields {
    /// The fields of a struct stored as a JSON object.
    ///
    /// # Errors
    ///
    /// Fails when `stored` isn't an object.
    pub fn object(stored: Value) -> Result<Self> {
        match stored {
            Value::Object(fields) => Ok(Self(fields)),
            other => Err(__undecodable(format!("expected an object, found {other}"))),
        }
    }

    /// The fields of a tuple struct stored as a JSON array of `len` elements, by position.
    ///
    /// # Errors
    ///
    /// Fails when `stored` isn't an array of that length.
    pub fn array(stored: Value, len: usize) -> Result<Self> {
        match stored {
            Value::Array(values) if values.len() == len => Ok(Self(
                values
                    .into_iter()
                    .enumerate()
                    .map(|(index, value)| (index.to_string(), value))
                    .collect(),
            )),
            other => Err(__undecodable(format!(
                "expected an array of {len} values, found {other}"
            ))),
        }
    }

    /// Take the field named `name`, or `None` when it's missing.
    pub fn take(&mut self, name: &str) -> Option<Value> {
        self.0.remove(name)
    }

    /// Take the field under the first of `names` it's stored under: its name, then its aliases.
    pub fn take_any(&mut self, names: &[&str]) -> Option<Value> {
        names.iter().find_map(|name| self.take(name))
    }
}

/// A field's type, whose stored form the derive chooses by autoref specialization: a model,
/// `Option` or `Vec` of models through [`ModelField`], otherwise JSON through [`SerdeField`].
#[doc(hidden)]
pub struct Field<T>(PhantomData<fn() -> T>);

impl<T> Field<T> {
    #[must_use]
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T> fmt::Debug for Field<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Field")
    }
}

impl<T> Default for Field<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// A field decoded from its payload, which may wait for [`ModelRows::load`] to read its models.
#[doc(hidden)]
pub struct Pending<T>(PendingValue<T>);

impl<T> fmt::Debug for Pending<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Pending")
    }
}

enum PendingValue<T> {
    Ready(T),
    Models(Box<dyn FnOnce(&ModelRows) -> T + Send>),
}

impl<T> Pending<T> {
    /// A value with no models to wait for.
    pub const fn ready(value: T) -> Self {
        Self(PendingValue::Ready(value))
    }

    /// Map the value once it's finished, such as to build a struct from its fields.
    pub fn map<U>(self, map: impl FnOnce(T) -> U + Send + 'static) -> Pending<U>
    where
        T: 'static,
    {
        match self.0 {
            PendingValue::Ready(value) => Pending::ready(map(value)),
            PendingValue::Models(finish) => Pending::models(move |rows| map(finish(rows))),
        }
    }

    /// A value to finish once its models are read.
    pub fn models(finish: impl FnOnce(&ModelRows) -> T + Send + 'static) -> Self {
        Self(PendingValue::Models(Box::new(finish)))
    }

    /// The field's value, once `rows` hold its models: after [`ModelRows::load`], or with the rows a
    /// dispatch recorded.
    pub fn finish(self, rows: &ModelRows) -> T {
        match self.0 {
            PendingValue::Ready(value) => value,
            PendingValue::Models(finish) => finish(rows),
        }
    }
}

/// A model field, stored as its keys. The derive calls it on `&Field<T>`, so it takes precedence
/// over [`SerdeField`].
#[doc(hidden)]
pub trait ModelField<T> {
    /// # Errors
    ///
    /// Fails when a key can't be encoded.
    fn store(&self, value: &T, name: &str, rows: &mut ModelRows) -> Result<Value>;

    /// # Errors
    ///
    /// Fails when the stored keys can't be decoded.
    fn collect(&self, stored: Option<Value>, name: &str, rows: &mut ModelRows) -> Result<Pending<T>>;

    /// What a missing field's default may be.
    fn kind(&self) -> ModelKind {
        ModelKind
    }
}

/// Any other field, stored as JSON.
#[doc(hidden)]
pub trait SerdeField<T> {
    /// # Errors
    ///
    /// Fails when the value can't be encoded.
    fn store(&self, value: &T, name: &str, rows: &mut ModelRows) -> Result<Value>;

    /// # Errors
    ///
    /// Fails when the stored value can't be decoded.
    fn collect(&self, stored: Option<Value>, name: &str, rows: &mut ModelRows) -> Result<Pending<T>>;

    /// What a missing field's default may be.
    fn kind(&self) -> SerdeKind {
        SerdeKind
    }
}

/// A field that holds models, whose `#[serde(default)]` is `None` or an empty `Vec`.
#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub struct ModelKind;

/// A field stored as JSON, whose default is its type's `Default` or a function.
#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub struct SerdeKind;

/// The value of a missing field marked `#[serde(default)]`.
#[doc(hidden)]
#[diagnostic::on_unimplemented(
    message = "the model field of type `{T}` can't take `#[serde(default)]`, because a model has no default",
    label = "this field holds a model",
    note = "make the field an `Option<{T}>`, which is `None` when the job doesn't store it"
)]
pub trait DefaultKind<T> {
    fn default_value(self) -> T;
}

impl<T: Default> DefaultKind<T> for SerdeKind {
    fn default_value(self) -> T {
        T::default()
    }
}

/// A field that may take `#[serde(default = "..")]`: one that holds no models.
#[doc(hidden)]
#[diagnostic::on_unimplemented(
    message = "the model field of type `{T}` can't take `#[serde(default = \"..\")]`",
    label = "this field holds models",
    note = "a model field defaults only to `None` or an empty `Vec`: use `#[serde(default)]` on an `Option` or a `Vec`"
)]
pub trait DefaultWith<T> {}

impl<T> DefaultWith<T> for SerdeKind {}

/// A missing field's `#[serde(default)]` value.
#[doc(hidden)]
pub fn __default<T, K: DefaultKind<T>>(kind: K) -> Pending<T> {
    Pending::ready(kind.default_value())
}

/// A missing field's `#[serde(default = "..")]` value.
#[doc(hidden)]
pub fn __default_with<T, K: DefaultWith<T>>(_: K, default: fn() -> T) -> Pending<T> {
    Pending::ready(default())
}

impl<T: Serialize + DeserializeOwned> SerdeField<T> for &Field<T> {
    fn store(&self, value: &T, name: &str, _: &mut ModelRows) -> Result<Value> {
        serde_json::to_value(value).map_err(|error| __undecodable(format!("field `{name}`: {error}")))
    }

    fn collect(&self, stored: Option<Value>, name: &str, _: &mut ModelRows) -> Result<Pending<T>> {
        let value = match stored {
            Some(stored) => {
                serde_json::from_value(stored).map_err(|error| __undecodable(format!("field `{name}`: {error}")))
            }
            None => serde_json::from_value(Value::Null).map_err(|_| __undecodable(format!("missing field `{name}`"))),
        };

        value.map(|value| Pending(PendingValue::Ready(value)))
    }
}

/// The rows of the models a stored value holds, grouped by model type. A worker fills them from
/// the keys its fields decode, with one query per type. A dispatch fills them from the models it
/// stores, for a queue fake to read back.
#[doc(hidden)]
#[derive(Default)]
pub struct ModelRows {
    groups: Vec<Box<dyn Group>>,
    #[cfg_attr(not(feature = "database"), expect(dead_code, reason = "only models restore rows"))]
    index: HashMap<TypeId, usize>,
}

impl fmt::Debug for ModelRows {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ModelRows").field("groups", &self.groups.len()).finish()
    }
}

impl ModelRows {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Read the rows of every model the fields asked for, from the writer.
    ///
    /// # Errors
    ///
    /// Fails with [`MissingModels`] when the row of a model or `Option` field is gone, naming the
    /// first model type with missing rows in field order, or when a query fails. A row only `Vec`
    /// fields wanted may be gone.
    pub async fn load(&mut self) -> Result<()> {
        for group in &mut self.groups {
            group.load().await?;
        }

        Ok(())
    }

    #[cfg_attr(not(feature = "database"), expect(dead_code, reason = "only models restore rows"))]
    pub(crate) fn group<G: Group + Default>(&mut self) -> &mut G {
        let groups = &mut self.groups;
        let index = *self.index.entry(TypeId::of::<G>()).or_insert_with(|| {
            groups.push(Box::new(G::default()));
            groups.len() - 1
        });
        let group: &mut dyn Any = &mut *self.groups[index];

        group
            .downcast_mut()
            .expect("the index maps each group's type to its group")
    }

    #[cfg_attr(not(feature = "database"), expect(dead_code, reason = "only models restore rows"))]
    pub(crate) fn loaded<G: Group>(&self) -> &G {
        let index = self.index[&TypeId::of::<G>()];
        let group: &dyn Any = &*self.groups[index];

        group
            .downcast_ref()
            .expect("the index maps each group's type to its group")
    }
}

/// The keys of one model type that a restore needs, and the rows it read.
pub(crate) trait Group: Any + Send + Sync {
    fn load(&mut self) -> BoxFuture<'_, Result<()>>;
}

impl MissingModels {
    #[cfg_attr(not(feature = "database"), expect(dead_code, reason = "only models restore rows"))]
    pub(crate) const fn new(model: &'static str, keys: Vec<String>) -> Self {
        Self { model, keys }
    }
}

/// The error restoring the value of the job, listener or callback named `name` failed with:
/// `MissingModels` and query errors pass through, and a payload that doesn't decode names it.
pub fn restore_error(kind: &str, name: &str, error: crate::Error) -> crate::Error {
    match error.downcast_ref::<Undecodable>() {
        Some(Undecodable(message)) => Undecodable(format!("the {kind} `{name}` couldn't be decoded: {message}")).into(),
        None => error,
    }
}

/// Encode `value` for a payload, naming the job, listener or callback when it fails, and record
/// its models in `rows`.
///
/// # Errors
///
/// Fails when `value` can't be encoded into a queueable payload.
pub fn store<Q: Queueable>(kind: &str, name: &str, value: &Q, rows: &mut ModelRows) -> Result<Value> {
    value
        .__store(rows)
        .map_err(|error| match error.downcast_ref::<Undecodable>() {
            Some(Undecodable(message)) => {
                crate::error::fail(format!("the {kind} `{name}` couldn't be encoded: {message}"))
            }
            None => error,
        })
}