laravel-rust-workflow 0.2.0

Internal crate of Laravel for Rust: durable workflows. 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
//! `laravel::workflow`, which the `laravel-rust` package documents.

use std::fmt;
use std::sync::{Arc, Mutex, PoisonError};

use serde::Serialize;

use crate::Result;
use crate::config::workflow::{StoreConfig, Workflow as WorkflowConfig};
#[cfg(feature = "database")]
use crate::container::ContainerInternals as _;
use crate::container::{Container, Services};
use crate::context::{Context, Internals};

mod advance;
#[doc(hidden)]
pub mod commands;
mod drivers;
mod erased_store;
pub mod events;
mod fake;
mod id;
mod info;
mod registration;
mod run;
mod start;
pub mod store;
#[cfg(any(test, feature = "testing"))]
#[doc(hidden)]
pub mod store_contract;
mod token;
mod url;

#[doc(hidden)]
pub use self::advance::{advance, encode_context, now};
#[doc(hidden)]
pub use self::drivers::Factories;
pub use self::drivers::{Drivers, StoreDefinition};
pub use self::erased_store::ErasedStore;
#[doc(hidden)]
pub use self::fake::Fakes;
pub use self::fake::{WorkflowFake, fake};
pub use self::id::RunId;
pub use self::info::{RunInfo, StepInfo};
pub use self::registration::Workflow;
#[doc(hidden)]
pub use self::registration::{__Registration, __WorkflowResult};
pub use self::run::{
    CurrentStep, Inbox, Run, Sleep, Step, StepFailed, TimedWait, Wait, current_step, fatal, retry_after,
};
pub use self::start::{PendingStart, Started};
#[cfg(feature = "database")]
pub use self::store::database::DatabaseStore;
pub use self::token::Token;
#[doc(hidden)]
pub use self::url::TakesResume;
#[doc(hidden)]
pub use self::url::routes;
pub use self::url::{Resume, ResumeUrl, resume_url, webhook_url};

/// Make a [`Queueable`](crate::queue::Queueable) struct a durable workflow.
///
/// Place the attribute on the `impl` block that holds the struct's async `handle` method. `handle`
/// consumes `self` and takes a [`&Run`](Run). It may also take
/// [`Inject<T>`](crate::container::Inject) services and
/// [`Section<T>`](struct@crate::config::Section) config sections, in any order. It returns
/// `laravel::Result<T>`, where `T` is `()` or any type that serializes, and `T` becomes the run's
/// output.
///
/// The `impl` block may also hold an async `failed` method, which runs once when the run fails for
/// good. It takes the error as an `&laravel::Error` argument, and the same kinds of services and
/// config sections as `handle`.
///
/// The attribute adds a `start` method, implements [`Workflow`], and registers the workflow so a
/// worker can find it by name. Both of its options are optional:
///
/// | Option | Meaning |
/// | --- | --- |
/// | `name = "users.onboard"` | The name the store saves runs under. Defaults to the type's path. |
/// | `queue = "workflows"` | The queue for the run's jobs, unless the start names another queue. |
///
/// ```no_run
/// use laravel::container::Inject;
/// use laravel::workflow::{Run, workflow};
/// # pub struct Payments;
/// # impl Payments { async fn charge(&self, id: i64) -> laravel::Result<String> { Ok(String::new()) } }
/// # impl Payments { async fn alert(&self, error: &laravel::Error) {} }
///
/// #[derive(laravel::queue::Queueable)]
/// pub struct Checkout {
///     pub order_id: i64,
/// }
///
/// #[workflow(name = "orders.checkout", queue = "workflows")]
/// impl Checkout {
///     async fn handle(self, run: &Run, payments: Inject<Payments>) -> laravel::Result<String> {
///         run.step("charge card", payments.charge(self.order_id)).await
///     }
///
///     async fn failed(self, error: &laravel::Error, payments: Inject<Payments>) {
///         payments.alert(error).await;
///     }
/// }
/// ```
///
/// `handle` must take a `&Run`:
///
/// ```compile_fail
/// #[derive(laravel::queue::Queueable)]
/// struct NoRun;
///
/// #[laravel::workflow::workflow]
/// impl NoRun { async fn handle(self, id: i64) -> laravel::Result<()> { Ok(()) } }
/// ```
pub use laravel_rust_queue_macros::workflow;

/// How far a run has come.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Status {
    /// The run has started and is waiting for its first advance.
    Pending,
    /// A worker is advancing the run.
    Running,
    /// The run is sleeping, waiting for a token, or waiting to try a step again.
    Waiting,
    /// The workflow's `handle` method returned successfully.
    Completed,
    /// The workflow returned an error or broke a rule that the runtime checks.
    Failed,
    /// [`cancel`] stopped the run.
    Cancelled,
}

impl Status {
    /// The status's name, as a store may save it.
    ///
    /// The names are `pending`, `running`, `waiting`, `completed`, `failed`, and `cancelled`.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::Running => "running",
            Self::Waiting => "waiting",
            Self::Completed => "completed",
            Self::Failed => "failed",
            Self::Cancelled => "cancelled",
        }
    }

    /// Parse a status from the name that [`as_str`](Self::as_str) returns, or return `None` for an
    /// unknown name.
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "pending" => Some(Self::Pending),
            "running" => Some(Self::Running),
            "waiting" => Some(Self::Waiting),
            "completed" => Some(Self::Completed),
            "failed" => Some(Self::Failed),
            "cancelled" => Some(Self::Cancelled),
            _ => None,
        }
    }

    /// Whether the run has completed, failed, or been cancelled, so nothing advances it again.
    #[must_use]
    pub const fn has_ended(self) -> bool {
        matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
    }
}

impl fmt::Display for Status {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Give `value` to the run that owns `token`, and report whether one did.
///
/// A run owns a token from when it first waits for the token with [`Run::wait_for`] or an
/// [`Inbox`](Run::inbox_for), or from its start when the start
/// [claims](PendingStart::claim) the token, until it completes, fails, or is cancelled. The token
/// is a string, or a [`Token<T>`] whose `T` must be the value's type.
///
/// The run keeps the values it's given in the order they arrived: a wait takes the first, and an
/// inbox reads them all. When no unfinished run owns the token, such as after the run moved on and
/// finished, `resume` keeps nothing and returns [`Resumed::NotFound`], so a value never reaches a
/// run it wasn't sent to.
///
/// Inside a database transaction, the resume happens when the transaction commits. If the
/// transaction rolls back, the resume doesn't happen.
///
/// ```no_run
/// use laravel::workflow;
///
/// #[derive(serde::Serialize, serde::Deserialize)]
/// struct Subscribed {
///     plan: String,
/// }
///
/// # async fn example(user_id: i64) -> laravel::Result<()> {
/// let token = format!("users.{user_id}.subscribed");
/// let resumed = workflow::resume(token, Subscribed { plan: "pro".into() }).await?;
///
/// if resumed == workflow::Resumed::NotFound {
///     tracing::info!("no run is waiting for the subscription");
/// }
/// # Ok(()) }
/// ```
///
/// # Errors
///
/// Returns an error if the value doesn't serialize, or if the store or the queue fails.
///
/// # Panics
///
/// Panics if called outside an application context.
#[track_caller]
pub fn resume<T: Serialize>(
    token: impl Into<Token<T>>,
    value: T,
) -> impl std::future::Future<Output = Result<Resumed>> + Send + 'static {
    let context = Context::expect("laravel::workflow::resume()");
    let token = String::from(token.into());
    let value = serde_json::to_string(&value);

    async move {
        let value = value?;
        let manager = Manager::of(context.services());
        let resume = move || async move {
            let store = manager.store()?;
            match store.resume(&token, value).await? {
                store::Delivery::NotFound => Ok(Resumed::NotFound),
                store::Delivery::Queued(_) => Ok(Resumed::Delivered),
                store::Delivery::Due(id) => {
                    if let Some(run) = store.find(id).await? {
                        advance::schedule(id, &run.workflow, &run.connection, &run.queue, None).await?;
                    }

                    Ok(Resumed::Delivered)
                }
            }
        };

        #[cfg(feature = "database")]
        if crate::db::callbacks::current().is_some() {
            crate::db::after_commit(move || async move { resume().await.map(drop) }).await?;
            return Ok(Resumed::Pending);
        }

        resume().await
    }
}

/// What [`resume`] did with its value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Resumed {
    /// The run that owns the token keeps the value, and the run's next advance is queued if it
    /// was waiting for it.
    Delivered,
    /// No unfinished run owns the token, so the value went nowhere.
    NotFound,
    /// The resume waits for the current database transaction to commit.
    Pending,
}

/// Find a run and its steps by the run's ID.
///
/// Returns `None` if no run has the ID. [`RunInfo`] serializes, so a route may return it for a
/// progress page.
///
/// ```no_run
/// use laravel::prelude::*;
/// use laravel::workflow::{self, RunId, RunInfo};
///
/// pub async fn show(Params(run_id): Params<RunId>) -> laravel::Result<Json<RunInfo>> {
///     let run = workflow::find(run_id).await?.or_abort(404)?;
///
///     Ok(Json(run))
/// }
/// ```
///
/// # Errors
///
/// Returns an error if the store fails.
///
/// # Panics
///
/// Panics if called outside an application context.
#[track_caller]
pub fn find(id: RunId) -> impl std::future::Future<Output = Result<Option<RunInfo>>> + Send + 'static {
    let context = Context::expect("laravel::workflow::find()");

    async move { run_info(&*Manager::of(context.services()).store()?, id).await }
}

/// Find the run that's waiting for a value of `token` now.
///
/// The run waits with [`Run::wait_for`] or an [`Inbox`](Run::inbox_for). A run that owns the token
/// but hasn't reached its wait yet isn't returned. A route may check the run before it resumes the
/// token, such as to confirm that the signed-in user may decide on the expense the run is for.
///
/// ```no_run
/// use laravel::prelude::*;
/// use laravel::workflow;
///
/// pub async fn decision(Params(expense_id): Params<i64>) -> laravel::Result<Json<workflow::RunInfo>> {
///     let run = workflow::waiting_for(format!("expenses.{expense_id}.decision"))
///         .await?
///         .or_abort(404)?;
///
///     Ok(Json(run))
/// }
/// ```
///
/// # Errors
///
/// Returns an error if the store fails.
///
/// # Panics
///
/// Panics if called outside an application context.
#[track_caller]
pub fn waiting_for(
    token: impl AsRef<str>,
) -> impl std::future::Future<Output = Result<Option<RunInfo>>> + Send + 'static {
    let context = Context::expect("laravel::workflow::waiting_for()");
    let token = token.as_ref().to_owned();

    async move {
        let store = Manager::of(context.services()).store()?;
        match store.waiting(&token).await? {
            Some(id) => run_info(&*store, id).await,
            None => Ok(None),
        }
    }
}

async fn run_info(store: &dyn ErasedStore, id: RunId) -> Result<Option<RunInfo>> {
    let Some(run) = store.find(id).await? else {
        return Ok(None);
    };

    Ok(Some(RunInfo::new(run, store.entries(id).await?)))
}

/// Cancel a run, so nothing advances it again, and dispatch [`RunCancelled`](events::RunCancelled).
///
/// A step that's already running finishes, but nothing starts after it. Awaiting the cancel returns
/// `false` if the run doesn't exist or has already completed, failed, or been cancelled. You may
/// give the cancel a [`reason`](PendingCancel::reason), which `workflow:show` and the event show:
///
/// ```no_run
/// # async fn example(run_id: laravel::workflow::RunId) -> laravel::Result<()> {
/// laravel::workflow::cancel(run_id).reason("the customer closed their account").await?;
/// # Ok(()) }
/// ```
///
/// # Panics
///
/// Panics if called outside an application context.
#[track_caller]
pub fn cancel(id: RunId) -> PendingCancel {
    PendingCancel {
        context: Context::expect("laravel::workflow::cancel()"),
        id,
        reason: None,
    }
}

/// A cancel that [`cancel`] builds. Await it to cancel the run.
///
/// # Errors
///
/// Awaiting the cancel returns an error if the store fails.
#[derive(Debug)]
#[must_use = "a run is cancelled only when its cancel is awaited"]
pub struct PendingCancel {
    context: Context,
    id: RunId,
    reason: Option<String>,
}

impl PendingCancel {
    /// Set why the run is cancelled, which [`RunInfo::error`] and `workflow:show` show.
    pub fn reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }
}

impl std::future::IntoFuture for PendingCancel {
    type Output = Result<bool>;
    type IntoFuture = futures_util::future::BoxFuture<'static, Result<bool>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move { advance::cancel(&self.context, self.id, self.reason).await })
    }
}

/// The application's workflow store manager, which creates the default store of
/// `config.workflow` when a run first needs it.
pub struct Manager {
    name: String,
    config: StoreConfig,
    drivers: Factories,
    services: Container,
    store: Mutex<Option<Arc<dyn ErasedStore>>>,
}

impl Manager {
    /// Build the workflow manager from configuration and registered drivers.
    ///
    /// # Panics
    ///
    /// Panics if `config.default` isn't present in `config.stores`.
    pub fn new(config: &WorkflowConfig, drivers: Factories, services: Container) -> Self {
        Self {
            name: config.default.clone(),
            config: config
                .stores
                .get(&config.default)
                .cloned()
                .expect("startup checks that the default workflow store is defined"),
            drivers,
            services,
            store: Mutex::default(),
        }
    }

    /// Resolve the application's registered workflow manager.
    ///
    /// # Panics
    ///
    /// Panics if the application wasn't built with a workflow manager instance.
    pub fn of(services: &Services) -> Arc<Self> {
        services
            .built()
            .expect("the application registers its workflow manager as an instance")
    }

    /// The default store, which the first call creates and later calls share.
    ///
    /// # Errors
    ///
    /// Returns an error if building the store's driver fails.
    pub fn store(&self) -> Result<Arc<dyn ErasedStore>> {
        if let Some(store) = &*self.store.lock().unwrap_or_else(PoisonError::into_inner) {
            return Ok(Arc::clone(store));
        }

        let created = self.create()?;
        let mut store = self.store.lock().unwrap_or_else(PoisonError::into_inner);

        Ok(Arc::clone(store.get_or_insert(created)))
    }

    fn create(&self) -> Result<Arc<dyn ErasedStore>> {
        let (name, config) = (&self.name, &self.config);
        if let Some(factory) = self.drivers.0.get(&config.driver().to_ascii_lowercase()) {
            return Ok(Arc::new(store::lazy::LazyStore::new(
                format!("workflow store `{name}`"),
                StoreDefinition::new(name, config.clone()),
                Arc::clone(factory),
                self.services.clone(),
            )));
        }

        match config {
            StoreConfig::Memory => Ok(Arc::new(store::memory::MemoryStore::default())),
            #[cfg(feature = "database")]
            StoreConfig::Database(store) => {
                let database = self
                    .services
                    .built::<crate::db::DatabaseManager>()
                    .ok_or_else(|| crate::error::fail("the database workflow store needs the database manager"))?;

                Ok(Arc::new(store::database::DatabaseStore::new(database, store)?))
            }
            #[cfg(not(feature = "database"))]
            StoreConfig::Database(_) => Err(crate::error::fail(
                "the database workflow store needs a database driver feature: `database-sqlite`, \
                 `database-postgres` or `database-mysql`; set `WORKFLOW_STORE=memory` to keep runs in memory",
            )),
            StoreConfig::Custom(store) => Err(crate::error::fail(format!(
                "workflow store `{name}` uses driver `{}`, which isn't registered",
                store.driver
            ))),
            _ => unreachable!("every workflow store the configuration defines is handled above"),
        }
    }
}

impl fmt::Debug for Manager {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Manager")
            .field("store", &self.name)
            .finish_non_exhaustive()
    }
}