laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
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
use std::collections::HashMap;
use std::fmt;
use std::future::IntoFuture;
use std::sync::{Mutex, MutexGuard, PoisonError};

use futures_util::future::BoxFuture;
use serde::Serialize;
use serde_json::Value;

use crate::Application;
use crate::context::{Context, Internals};
use crate::queue::__queueable::ModelRows;
use crate::queue::{QueueManager, QueueManagerInternals as _};
use crate::workflow::store::{Created, Delivery, EntryStatus, Kind, NewRun};
use crate::workflow::{Manager, RunId, RunInfo, Status, StepInfo, Token, Workflow};

/// Runs a workflow in the test's process, without a queue or a worker.
///
/// The run advances until it finishes or suspends. The test can then move the application's
/// time or resume a wait, and advance the run again.
///
/// ```
/// use laravel::testing::RunsWorkflows;
/// use laravel::time::ToSpan;
/// use laravel::workflow::{Run, workflow};
///
/// #[derive(laravel::queue::Queueable)]
/// struct Remind { user_id: i64 }
///
/// #[workflow]
/// impl Remind {
///     async fn handle(self, run: &Run) -> laravel::Result<u32> {
///         run.sleep(3.days()).await?;
///
///         run.step("send reminder", async { Ok(1) }).await
///     }
/// }
///
/// let app = laravel::Application::configure()
///     .replace_env(laravel::config::Env::from_iter([("WORKFLOW_STORE", "memory")]))
///     .create();
/// laravel::testing::__run(async {
///     let run = app.workflow(Remind { user_id: 42 }).await;
///     run.assert_sleeping();
///
///     app.travel(3.days());
///     run.advance().await;
///     run.assert_completed_with(1);
/// });
/// ```
pub trait RunsWorkflows {
    /// Start a run of `workflow` in the application's workflow store, and advance it once.
    fn workflow<W: Workflow>(&self, workflow: W) -> TestWorkflow<W>;
}

impl RunsWorkflows for Application {
    fn workflow<W: Workflow>(&self, workflow: W) -> TestWorkflow<W> {
        TestWorkflow {
            application: self.clone(),
            workflow,
            replacements: HashMap::new(),
            tokens: Vec::new(),
        }
    }
}

/// A run about to start, from [`RunsWorkflows::workflow`].
///
/// Await it to start the run and advance it until it finishes or suspends. Awaiting it returns
/// a [`TestRun`].
#[must_use = "a test workflow does nothing unless awaited"]
pub struct TestWorkflow<W> {
    application: Application,
    workflow: W,
    replacements: HashMap<String, String>,
    tokens: Vec<String>,
}

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

impl<W: Workflow> TestWorkflow<W> {
    /// Record `output` as the result of the step `name`, so the step's work doesn't run.
    ///
    /// The test then doesn't need to fake the service that the step calls.
    ///
    /// # Panics
    ///
    /// Panics when `output` doesn't serialize.
    #[track_caller]
    pub fn with_step(mut self, name: impl Into<String>, output: impl Serialize) -> Self {
        let output = serde_json::to_string(&output)
            .unwrap_or_else(|error| panic!("the replaced step's output doesn't serialize: {error}"));
        self.replacements.insert(name.into(), output);
        self
    }

    /// Make the run own `token` from its start, as
    /// [`PendingStart::claim`](crate::workflow::PendingStart::claim) does, so the test can resume
    /// the token before the run reaches its wait.
    pub fn claim(mut self, token: impl AsRef<str>) -> Self {
        self.tokens.push(token.as_ref().to_owned());
        self
    }

    async fn start(self) -> TestRun {
        let Self {
            application,
            workflow,
            replacements,
            tokens,
        } = self;

        let id = application
            .scope(async move || {
                let context = Context::expect("laravel::testing::RunsWorkflows::workflow()");
                let (connection, queue) = QueueManager::of(context.services())
                    .route(None, W::queue())
                    .unwrap_or_else(|error| panic!("the workflow's queue isn't defined: {error}"));
                let input = crate::queue::store_queueable("workflow", W::NAME, &workflow, &mut ModelRows::new())
                    .unwrap_or_else(|error| panic!("the workflow doesn't encode: {error}"));
                let id = RunId::generate();
                let now = crate::workflow::now();
                let mut run = NewRun::__starting(
                    id,
                    W::NAME.to_owned(),
                    input.to_string(),
                    crate::workflow::encode_context(&context).unwrap_or_default(),
                    (connection, queue),
                    now,
                );
                run.tokens = tokens;
                match store(&context).create(run).await {
                    Ok(Created::Saved) => {}
                    Ok(Created::Taken { token, owner }) => {
                        panic!("the token `{token}` is owned by the unfinished run {owner}")
                    }
                    Ok(other) => panic!("the run couldn't be saved: {other:?}"),
                    Err(error) => panic!("the run couldn't be saved: {error}"),
                }

                id
            })
            .await;

        let run = TestRun {
            application,
            id,
            replacements,
            info: Mutex::new(None),
        };
        run.advance().await;

        run
    }
}

impl<W: Workflow> IntoFuture for TestWorkflow<W> {
    type Output = TestRun;
    type IntoFuture = BoxFuture<'static, TestRun>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.start())
    }
}

fn store(context: &Context) -> std::sync::Arc<dyn crate::workflow::ErasedStore> {
    Manager::of(context.services())
        .store()
        .unwrap_or_else(|error| panic!("the workflow store isn't available: {error}"))
}

/// A run that a test started with [`RunsWorkflows::workflow`].
///
/// The run advances only when the test calls [`advance`](Self::advance) or
/// [`resume`](Self::resume). Its assertions check the run as it was after the most recent of
/// those calls.
pub struct TestRun {
    application: Application,
    id: RunId,
    replacements: HashMap<String, String>,
    info: Mutex<Option<RunInfo>>,
}

/// Formats the run as `workflow:show` lists it, with one line per step, for assertion messages.
impl fmt::Debug for TestRun {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let state = self.state();
        let Some(info) = state.as_ref() else {
            return write!(f, "run {} is gone from its store", self.id);
        };
        write!(f, "run {} of `{}` is {}", info.id(), info.workflow(), info.status())?;
        if let Some(error) = info.error() {
            write!(f, ": {error}")?;
        }
        for step in info.steps() {
            write!(
                f,
                "\n  {} `{}` {}",
                step.kind().as_str(),
                step.name(),
                step.status().as_str()
            )?;
            if step.kind() == Kind::Step {
                write!(f, " after {} tries", step.tries())?;
            }
            if let Some(error) = step.error() {
                write!(f, ": {error}")?;
            }
        }
        Ok(())
    }
}

impl TestRun {
    /// The run's ID.
    #[must_use]
    pub const fn id(&self) -> RunId {
        self.id
    }

    /// The run as it was after the most recent advance, or `None` once its store no longer has it.
    #[must_use]
    pub fn info(&self) -> Option<RunInfo> {
        self.state().clone()
    }

    fn state(&self) -> MutexGuard<'_, Option<RunInfo>> {
        self.info.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Advance the run once at the application's current time, as a worker does when the run
    /// wakes up.
    ///
    /// # Panics
    ///
    /// Panics when the store fails.
    pub async fn advance(&self) -> &Self {
        let id = self.id;
        let replacements = self.replacements.clone();
        let info = self
            .application
            .scope(async move || {
                if let Err(error) = crate::workflow::advance(id, replacements).await {
                    panic!("the workflow run couldn't advance: {error:#}");
                }

                crate::workflow::find(id).await
            })
            .await
            .unwrap_or_else(|error| panic!("the workflow run couldn't be read: {error:#}"));
        *self.state() = info;

        self
    }

    /// Give `value` to the run's wait for `token`, as [`workflow::resume`](crate::workflow::resume)
    /// does, and then advance the run.
    ///
    /// # Panics
    ///
    /// Panics when the value doesn't serialize, when this run doesn't own the token, or when the
    /// store fails.
    pub async fn resume<T: Serialize>(&self, token: impl Into<Token<T>>, value: T) -> &Self {
        let token = String::from(token.into());
        let value =
            serde_json::to_string(&value).unwrap_or_else(|error| panic!("the value doesn't serialize: {error}"));
        let id = self.id;
        self.application
            .scope(async move || {
                let context = Context::expect("laravel::testing::TestRun::resume()");
                let delivery = store(&context)
                    .resume(&token, value)
                    .await
                    .unwrap_or_else(|error| panic!("the token couldn't be resumed: {error:#}"));
                match delivery {
                    Delivery::Due(owner) | Delivery::Queued(owner) if owner == id => {}
                    Delivery::Due(owner) | Delivery::Queued(owner) => {
                        panic!("the token `{token}` is owned by run {owner}, not run {id}")
                    }
                    _ => panic!(
                        "run {id} doesn't own the token `{token}`: it hasn't reached a wait for the token, \
                         so claim the token at the start with `app.workflow(..).claim(..)`"
                    ),
                }
            })
            .await;

        self.advance().await
    }

    fn read<T>(&self, read: impl FnOnce(&RunInfo) -> T) -> T {
        let info = self.info();
        let info = info
            .as_ref()
            .unwrap_or_else(|| panic!("the workflow run `{}` is gone from its store", self.id));

        read(info)
    }

    fn status(&self) -> Status {
        self.read(RunInfo::status)
    }

    fn step(&self, name: &str) -> Option<StepInfo> {
        self.read(|info| {
            info.steps()
                .iter()
                .find(|step| step.kind() == Kind::Step && step.name() == name)
                .cloned()
        })
    }

    /// Assert that the run completed.
    ///
    /// # Panics
    ///
    /// Panics when the run didn't complete. The message shows the run.
    #[track_caller]
    pub fn assert_completed(&self) -> &Self {
        assert_eq!(self.status(), Status::Completed, "the run didn't complete\n{self:?}");
        self
    }

    /// Assert that the run completed, and that its workflow returned `expected`.
    ///
    /// # Panics
    ///
    /// Panics when the run didn't complete, with a message that shows the run, or when the
    /// workflow returned another value.
    #[track_caller]
    pub fn assert_completed_with(&self, expected: impl Serialize) -> &Self {
        self.assert_completed();
        let expected = serde_json::to_value(expected).expect("the expected output serializes");
        let output: Option<Value> = self.read(|info| info.output().expect("the output is JSON"));
        assert_eq!(output, Some(expected), "the run returned something else");
        self
    }

    /// Assert that the run failed and won't be tried again.
    ///
    /// # Panics
    ///
    /// Panics when the run didn't fail. The message shows the run.
    #[track_caller]
    pub fn assert_failed(&self) -> &Self {
        assert_eq!(self.status(), Status::Failed, "the run didn't fail\n{self:?}");
        self
    }

    /// Assert that the run failed and won't be tried again, with an error that contains `message`.
    ///
    /// # Panics
    ///
    /// Panics when the run didn't fail, with a message that shows the run, or when it failed
    /// with another error.
    #[track_caller]
    pub fn assert_failed_with(&self, message: &str) -> &Self {
        self.assert_failed();
        let error = self.read(|info| info.error().unwrap_or_default().to_owned());
        assert!(
            error.contains(message),
            "the run failed with `{error}`, not `{message}`"
        );
        self
    }

    /// Assert that the run is sleeping.
    ///
    /// # Panics
    ///
    /// Panics when the run isn't sleeping. The message shows the run.
    #[track_caller]
    pub fn assert_sleeping(&self) -> &Self {
        let sleeping = self.read(|info| {
            info.status() == Status::Waiting
                && info
                    .steps()
                    .iter()
                    .any(|step| step.kind() == Kind::Sleep && step.status() == EntryStatus::Pending)
        });
        assert!(sleeping, "the run isn't sleeping\n{self:?}");
        self
    }

    /// Assert that the run is waiting for `token`.
    ///
    /// # Panics
    ///
    /// Panics when the run isn't waiting for `token`. The message shows the run.
    #[track_caller]
    pub fn assert_waiting_for(&self, token: impl AsRef<str>) -> &Self {
        let token = token.as_ref();
        let waiting =
            self.read(|info| info.status() == Status::Waiting && info.waiting_for().any(|wait| wait == token));
        assert!(waiting, "the run isn't waiting for `{token}`\n{self:?}");
        self
    }

    /// Assert that the step `name` failed a try and is waiting for its backoff before it tries
    /// again.
    ///
    /// # Panics
    ///
    /// Panics when the step isn't waiting to retry. The message shows the run.
    #[track_caller]
    pub fn assert_retrying(&self, name: &str) -> &Self {
        let retrying = self.status() == Status::Waiting
            && self
                .step(name)
                .is_some_and(|step| step.status() == EntryStatus::Pending);
        assert!(retrying, "the step `{name}` isn't waiting to try again\n{self:?}");
        self
    }

    /// Assert that the step `name` completed.
    ///
    /// # Panics
    ///
    /// Panics when the step didn't complete. The message shows the run.
    #[track_caller]
    pub fn assert_step_ran(&self, name: &str) -> &Self {
        let ran = self
            .step(name)
            .is_some_and(|step| step.status() == EntryStatus::Completed);
        assert!(ran, "the step `{name}` didn't complete\n{self:?}");
        self
    }

    /// Assert that the step `name` hasn't run.
    ///
    /// # Panics
    ///
    /// Panics when the step was tried. The message shows the run.
    #[track_caller]
    pub fn assert_step_not_ran(&self, name: &str) -> &Self {
        assert!(self.step(name).is_none(), "the step `{name}` was tried\n{self:?}");
        self
    }

    /// Assert that the step `name` was tried this many times.
    ///
    /// # Panics
    ///
    /// Panics when the step was tried another number of times. The message shows the run.
    #[track_caller]
    pub fn assert_step_tries(&self, name: &str, count: u32) -> &Self {
        let tries = self.step(name).map_or(0, |step| step.tries());
        assert_eq!(
            tries, count,
            "the step `{name}` was tried {tries} times, not {count}: {self:?}"
        );
        self
    }
}