laravel-rust 0.1.4

Laravel for Rust: a full-stack Rust web framework.
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
# Workflows

- [Introduction](#introduction)
    - [How a run advances](#how-a-run-advances)
- [Setup](#setup)
    - [The workflow tables](#the-workflow-tables)
    - [Choosing a store](#choosing-a-store)
- [Defining workflows](#defining-workflows)
- [Starting runs](#starting-runs)
    - [Starting a run once](#starting-a-run-once)
    - [Attributes](#attributes)
    - [Deleting a run's data](#deleting-a-runs-data)
- [Steps](#steps)
    - [Retries and timeouts](#retries-and-timeouts)
    - [Permanent step failures](#permanent-step-failures)
    - [Parallel steps](#parallel-steps)
- [Rules for `handle`](#rules-for-handle)
    - [Changing a workflow with runs in flight](#changing-a-workflow-with-runs-in-flight)
- [Sleeping](#sleeping)
- [Waiting and resuming](#waiting-and-resuming)
    - [Early resumes](#early-resumes)
    - [Typed tokens](#typed-tokens)
    - [Resume URLs](#resume-urls)
    - [Inboxes](#inboxes)
- [Inspecting and cancelling runs](#inspecting-and-cancelling-runs)
    - [Commands](#commands)
- [Events](#events)
- [Writing a store](#writing-a-store)
- [Testing](#testing)
    - [Faking starts](#faking-starts)
    - [Running a workflow in a test](#running-a-workflow-in-a-test)
    - [Testing waits and resumes](#testing-waits-and-resumes)

<a name="introduction"></a>
## Introduction

Some processes in your application span days rather than seconds. Onboarding a new user might involve sending a welcome email, waiting three days, and sending getting-started tips if they haven't created a project yet. Implementing that flow with [queues](queues.md) alone requires chaining delayed jobs, tracking progress in status columns, and scheduling sweep commands for stalled users.

Workflows let you express that entire flow as a single async function. Laravel executes each step once, persists its result, and resumes execution across sleeps, external webhooks, deploys, and worker restarts:

```rust
// src/workflows/onboard_user.rs
use laravel::queue::Queueable;
use laravel::time::ToSpan;
use laravel::workflow::{Run, workflow};

#[derive(Queueable)]
pub struct OnboardUser {
    pub user_id: i64,
}

#[workflow]
impl OnboardUser {
    async fn handle(self, run: &Run) -> laravel::Result<()> {
        run.step("send welcome email", self.send_welcome_email()).await?;

        run.sleep(3.days()).await?;

        if run.step("count projects", self.count_projects()).await? == 0 {
            run.step("send tips", self.send_tips()).await?;
        }

        Ok(())
    }
}
```

<a name="how-a-run-advances"></a>
### How a run advances

Workflows run on your existing queue workers and connections, so there is no extra infrastructure to deploy. Each advance executes as a queued job: the worker invokes `handle` from the top, immediately replays any steps whose results are already stored, and runs the next unrecorded step.

When execution reaches a sleep, a wait, or a step retry backoff, the run suspends. The worker finishes the current job and schedules the next advance with the appropriate delay. No worker sits idle while a workflow sleeps, so a run waiting for two weeks consumes no resources in the meantime.

<a name="setup"></a>
## Setup

Workflows require a [queue worker](queues.md#running-the-worker) backed by a connection that supports delayed jobs, such as `database`, `redis`, or `sqs`.

<a name="the-workflow-tables"></a>
### The workflow tables

The `database` workflow store persists runs across five tables on your default database connection. Because new applications do not include these tables by default, add a [migration](migrations.md) that holds only the `workflow::tables!` macro before starting a workflow. The macro creates all five tables:

```rust
// database/migrations/2026_01_01_000000_create_workflow_tables.rs
laravel::workflow::tables!();
```

If you'd like to change the tables, such as adding an index, replace the macro with the migration it stands for and edit it:

```rust
// database/migrations/2026_01_01_000000_create_workflow_tables.rs
use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .create("workflow_runs", |table| {
            table.string("id").length(36).primary();
            table.string("workflow");
            table.long_text("input");
            table.long_text("context");
            table.string("connection");
            table.string("queue");
            table.string("status").length(16);
            table.long_text("output").nullable();
            table.text("error").nullable();
            table.timestamp("wake_at").nullable();
            table.timestamp("leased_until").nullable();
            table.string("lease_token").length(36).nullable();
            table.timestamp("created_at");
            table.timestamp("finished_at").nullable();
            table.string("unique_key").nullable().unique();
            table.boolean("purge_data").default(false);

            table.index(["workflow", "id"]);
            table.index(["status", "wake_at"]);
            table.index("finished_at");
        })
        .await?;

    tx.schema()
        .create("workflow_steps", |table| {
            table.id();
            table.string("run_id").length(36);
            table.string("kind").length(8);
            table.string("name");
            table.string("status").length(16);
            table.integer("tries");
            table.long_text("output").nullable();
            table.text("error").nullable();
            table.timestamp("wake_at").nullable();
            table.timestamp("started_at");
            table.timestamp("finished_at").nullable();

            table.unique(["run_id", "kind", "name"]);
        })
        .await?;

    tx.schema()
        .create("workflow_waits", |table| {
            table.string("token").primary();
            table.string("run_id").length(36);
            table.integer("number").nullable();
            table.timestamp("resumed_at").nullable();

            table.index("run_id");
        })
        .await?;

    tx.schema()
        .create("workflow_resumes", |table| {
            table.string("run_id").length(36);
            table.string("token");
            table.big_integer("number");
            table.long_text("value");
            table.timestamp("created_at");

            table.primary(["run_id", "token", "number"]);
        })
        .await?;

    tx.schema()
        .create("workflow_attributes", |table| {
            table.string("run_id").length(36);
            table.string("name");
            table.string("value");

            table.primary(["run_id", "name"]);
            table.index(["name", "value"]);
        })
        .await
}
```

To store these tables on a separate database connection, set `DB_WORKFLOW_CONNECTION`.

<a name="choosing-a-store"></a>
### Choosing a store

By default, Laravel stores workflow runs in the `database` store, switching to the `memory` store in tests so workflow tests do not require database tables. Set `WORKFLOW_STORE` to choose a different store. Because the `memory` store loses all state when the process exits, never use it in production.

You can define additional stores in `src/config/workflow.rs`, such as a database store targeting another connection or a custom store provided by a package:

```rust
// src/config/workflow.rs
use laravel::config::workflow::{DatabaseStore, Workflow};
use laravel::config::{self, Env};

#[config::section]
fn workflow(env: &Env) -> Workflow {
    let mut workflow = Workflow::from_env(env);

    workflow.add_store("database", DatabaseStore::new().connection("workflows"));

    workflow
}
```

<a name="defining-workflows"></a>
## Defining workflows

Like a [job](queues.md#creating-jobs), a workflow is a struct deriving `Queueable` paired with a `#[workflow]` impl. Place each workflow in its own file under `src/workflows/`.

The struct's fields form the workflow's input. Laravel persists them when the run starts and provides a fresh deserialized copy to `handle` on each advance. Model fields serialize only their primary keys and reload on every advance, so they always reflect the latest database state rather than the state when the run began. Only branch on mutable model columns inside a recorded step, and prefer storing IDs rather than models when rows may change while a run sleeps.

`handle` takes `self` and `&Run`, along with any `Inject<T>` services or `Section<T>` config sections in any order. It returns `laravel::Result<T>`, where `T` is `()` or any serializable output type.

`#[workflow]` accepts two options:

| Option | Description |
| --- | --- |
| `name = "users.onboard"` | Stable identifier persisted for runs. Defaults to the type's module path |
| `queue = "workflows"` | Default queue for the run's jobs when `on_queue` is not set at start |

In-flight runs resolve their workflow implementation by name, so renaming or moving a struct without an explicit `name` orphans active runs. Assign a stable `name` before deploying a workflow to production.

A workflow may also define a `failed` method that runs once when the run fails permanently. It receives `&laravel::Error` along with any `Inject<T>` services or `Section<T>` config sections, returning `()` or `laravel::Result<()>`, and Laravel reports any error it returns. Because `failed` restores the workflow from its stored input, it does not run if a model field's row was deleted. Listen for [`RunFailed`](#events) to observe every failure:

```rust
use laravel::container::Inject;
use laravel::workflow::{Run, workflow};

#[workflow(name = "orders.checkout")]
impl Checkout {
    async fn handle(self, run: &Run, payments: Inject<Payments>) -> laravel::Result<()> {
        run.step("charge card", payments.charge(self.order_id)).await?;

        Ok(())
    }

    async fn failed(self, error: &laravel::Error, slack: Inject<Slack>) {
        slack.alert(format!("checkout {} failed: {error}", self.order_id)).await;
    }
}
```

<a name="starting-runs"></a>
## Starting runs

`#[workflow]` generates a `start` method analogous to a job's `dispatch`. Awaiting it persists the run, queues its first advance, and returns the `RunId`:

```rust
use laravel::prelude::*;

use crate::workflows::OnboardUser;

pub async fn store(user: User) -> laravel::Result<Redirect> {
    OnboardUser { user_id: user.id }.start().await?;

    Ok(Redirect::to("/dashboard"))
}
```

You can route the run's jobs to a specific queue connection or queue, or delay when it starts. The connection and queue chosen at start apply for the entire lifetime of the run:

```rust
use laravel::time::ToSpan;

let run_id = OnboardUser { user_id: user.id }
    .start()
    .on_connection("redis")
    .on_queue("workflows")
    .delay(1.hours())
    .await?;
```

Starting a workflow inside `db::transaction` waits until the transaction commits and is discarded on rollback, as [dispatching a job](queues.md#database-transactions) does. Laravel captures the current [context values](context.md), such as the active tenant, and restores them on every advance.

<a name="starting-a-run-once"></a>
### Starting a run once

Duplicate form submissions or repeated webhooks can trigger the same workflow twice. To prevent duplicate runs, pass a uniqueness key to `unique`. If an active run already holds that key, `start` returns the existing run instead of creating a new one:

```rust
use laravel::prelude::*;
use laravel::workflow::Started;

pub async fn submit(Params(expense_id): Params<i64>) -> laravel::Result<Redirect> {
    let started = ApproveExpense { expense_id }
        .start()
        .unique(format!("expenses.{expense_id}"))
        .await?;

    if let Started::Existing(run_id) = started {
        tracing::info!(%run_id, "the expense is already waiting for approval");
    }

    Ok(Redirect::to("/expenses"))
}
```

A unique start returns `Started::New(run_id)` or `Started::Existing(run_id)`. Call `started.id()` when you want the `RunId` without matching on the variant. A run releases its key once it completes, fails, or is cancelled, so resubmitting an expense after rejection starts a new run. Inside `db::transaction`, `start` returns `Started::Pending` and checks uniqueness on commit.

<a name="attributes"></a>
### Attributes

Attributes attach searchable metadata to a run, such as its tenant or current stage. You can filter by them with `workflow:list --attribute` and inspect them via `workflow:show` or `RunInfo::attributes()`. Set initial attributes when starting a run:

```rust
let run_id = OnboardUser { user_id: user.id }
    .start()
    .attribute("tenant", "acme")
    .attribute("plan", "pro")
    .await?;
```

You can also update attributes as the workflow progresses so operators can see a run's current phase without inspecting individual steps. Later assignments overwrite earlier values for the same name:

```rust
run.step("charge card", self.charge_card()).await?;
run.set_attribute("phase", "shipping");
```

Attributes are persisted whenever an advance ends by sleeping, waiting, completing, or failing. Replays re-apply them in the same order without extra writes.

Keep attribute values short and non-sensitive, since they remain stored for the lifetime of the run.

<a name="deleting-a-runs-data"></a>
### Deleting a run's data

Workflow runs retain their input, step outputs, and final output until `workflow:prune` removes them. For workflows that handle sensitive data such as bank details, chain `purge_when_finished` to wipe those payloads as soon as the run completes, fails, or is cancelled:

```rust
let run_id = VerifyBankAccount { account_id }
    .start()
    .purge_when_finished()
    .await?;
```

The run still retains its ID, status, attributes, and step names and timestamps, so `workflow:list` and `workflow:show` continue to display it with `<data deleted>` in place of its input. `RunInfo::purged()` returns `true` and `output()` returns `None`, so persist any needed workflow output inside a step. A purged run that failed cannot be retried.

<a name="steps"></a>
## Steps

`run.step(name, work)` executes `work` once and persists its result under `name`. The work can be any future returning `laravel::Result<T>` where `T` is serializable, such as an async method on the workflow struct or an inline async block:

```rust
let receipt = run.step("charge card", self.charge_card()).await?;

let total = run
    .step("total the order", async {
        let order = Order::find_or_fail(self.order_id).await?;

        order.total().await
    })
    .await?;
```

Pass the future without awaiting it. Laravel awaits `work` only if the step has not been recorded yet; on subsequent advances, it returns the stored result immediately.

Step names identify recorded results across replays, appear in `workflow:show`, and let tests stub individual steps. Every step name must be unique within a run, so include a distinguishing index or key when calling steps in a loop:

```rust
for day in [1, 3, 7] {
    run.sleep(day.days()).await?;
    run.step(format!("send reminder {day}"), self.send_reminder(day)).await?;
}
```

<a name="retries-and-timeouts"></a>
### Retries and timeouts

By default, a failing step is retried up to three times with backoffs of 10 seconds and 1 minute. Panics count as failed attempts. You can customize a step's retry count, backoff schedule, and timeout:

```rust
let receipt = run
    .step("charge card", self.charge_card())
    .tries(5)
    .backoff([10.seconds(), 1.minutes(), 10.minutes()])
    .timeout(30.seconds())
    .await?;
```

The run suspends during each backoff delay so no worker is tied up waiting. When `backoff` is a list, the final duration repeats for any remaining retries.

Some external failures tell you when to retry, such as an API returning a `Retry-After` header. Return `workflow::retry_after(when, error)` to override the step's backoff with a specific span or timestamp. The retry still counts toward the step's `tries`:

```rust
use laravel::http::client;
use laravel::prelude::*;
use laravel::workflow;

#[derive(Debug, thiserror::Error)]
#[error("the CRM is busy")]
struct CrmBusy;

async fn sync_contacts(&self) -> laravel::Result<()> {
    let response = client::post("https://crm.example.com/contacts/sync").await?;

    if response.status() == StatusCode::TOO_MANY_REQUESTS {
        let seconds: i64 = response
            .header("retry-after")
            .and_then(|seconds| seconds.parse().ok())
            .unwrap_or(60);

        return Err(workflow::retry_after(seconds.seconds(), CrmBusy));
    }

    Ok(())
}
```

If a worker crashes after a step completes external work but before Laravel records its result, the step will run again, so design steps to be idempotent. Inside a step, `workflow::current_step()` returns the active step handle whose `key()` combines the run ID and step name deterministically across retries. Pass `step.key()` as an idempotency key to payment gateways or external APIs to prevent duplicate side effects:

```rust
use serde_json::json;

async fn charge_card(&self) -> laravel::Result<()> {
    let step = workflow::current_step();

    client::post("https://payments.example.com/charges")
        .header("Idempotency-Key", step.key())
        .json(json!({ "order_id": self.order_id }))
        .await?;

    Ok(())
}
```

You can also inspect `step.attempt()` to see the 1-based attempt number, such as when adjusting behavior on the final retry.

<a name="permanent-step-failures"></a>
### Permanent step failures

To fail a step immediately without retrying, such as when a card is declined by the bank, wrap the error with `workflow::fatal`:

```rust
use laravel::workflow;

async fn charge_card(&self) -> laravel::Result<Receipt> {
    self.gateway.charge(self.order_id).await.map_err(workflow::fatal)
}
```

When a step exhausts its retries or returns `fatal`, `run.step(..).await` resolves to a `workflow::StepFailed` error containing the step name and final error. Propagating it with `?` fails the run. On every subsequent replay, the step returns that recorded error so error handling and branching behave identically across replays.

You can express compensating transactions in plain Rust. For example, a travel booking workflow can cancel the flight if booking the hotel fails:

```rust
let flight = run.step("book flight", self.book_flight()).await?;

if let Err(error) = run.step("book hotel", self.book_hotel()).await {
    run.step("cancel flight", self.cancel_flight(&flight)).await?;

    return Err(error);
}
```

`"cancel flight"` is a normal workflow step, so Laravel retries and records it like `"book flight"` and `"book hotel"`.

<a name="parallel-steps"></a>
### Parallel steps

Use `task::try_join!` to run multiple steps concurrently on the current worker. If one step fails permanently, `task::try_join!` cancels the remaining steps and returns that error:

```rust
use laravel::task;

let (projects, teammates) = task::try_join!(
    run.step("count projects", self.count_projects()),
    run.step("count teammates", self.count_teammates()),
)?;
```

To fan work out across multiple queue workers and wait for all of it to finish, [claim](#early-resumes) the completion token when you start the workflow so a fast batch can't finish before `wait_for` runs, dispatch a [job batch](queues.md#job-batches) whose `finally` callback calls [`workflow::resume`](#waiting-and-resuming) with whether the batch succeeded, and pause the workflow with `run.wait_for`:

```rust
use laravel::queue::{self, Batch, callback};
use laravel::workflow::{self, Run};

#[callback]
async fn batch_finished(token: String, batch: &Batch) -> laravel::Result<()> {
    workflow::resume(token, batch.failed_jobs() == 0).await?;

    Ok(())
}

// Claim the token before starting so early completions are buffered:
// ImportContacts { import_id, chunks }
//     .start()
//     .claim(format!("imports.{import_id}.done"))
//     .await?;

async fn handle(self, run: &Run) -> laravel::Result<()> {
    let token = format!("imports.{}.done", self.import_id);

    run.step("dispatch batch", async {
        let jobs = self.chunks.iter().cloned().map(|rows| ImportCsv { rows });

        queue::batch(jobs).finally(batch_finished(token.clone())).await?;

        Ok(())
    })
    .await?;

    let succeeded = run.wait_for::<bool>(&token).await?;

    if !succeeded {
        return Err(laravel::Error::msg("one or more import jobs failed"));
    }

    run.step("mark import complete", self.mark_complete()).await?;

    Ok(())
}
```

<a name="rules-for-handle"></a>
## Rules for `handle`

Because `handle` replays from the top on every advance, it must follow deterministic control flow. Laravel enforces what it can and fails the run with a descriptive error if a rule is violated:

- **Perform all I/O inside steps.** A database query or HTTP call outside a step may return different results on replay. If `handle` awaits anything other than an operation on `&Run`, the run fails and reports the last step it passed.
- **Branch only on workflow inputs and recorded step, sleep, or wait results.** Read the current time and random values inside steps. `run.id()` and `run.started_at()` are deterministic across replays and safe to call anywhere.
- **Keep step names and wait tokens unique within a run.** Reusing a step name or wait token fails the run, as does reading from the same inbox token through two separate `Inbox` handles.
- **Avoid `task::select!` and spawning tasks around steps.** A cancelled branch stops mid-step and restarts on the next advance. To expire a wait after a duration, chain `.timeout(..)` on `wait_for` instead of combining it with `run.sleep` in `task::select!`.

<a name="changing-a-workflow-with-runs-in-flight"></a>
### Changing a workflow with runs in flight

Because workflows can sleep or wait for days, you will often deploy changes to a workflow while existing runs are still in flight. When a sleeping run wakes up, Laravel runs your newly deployed `handle` method and matches each `run.step` call against the step names already recorded for that run. That makes adding or removing steps safe in most cases, while renaming steps or changing stored return types requires extra care:

| Change | Effect on in-flight runs |
| --- | --- |
| Add a step | Runs the new step once reached |
| Remove a step | Ignores the previously recorded result |
| Rename a step | Executes it again under the new name, so avoid renaming steps with side effects |
| Change a step's output type | Fails naming the step unless stored JSON still deserializes; use `#[serde(default)]` and `#[serde(alias)]` |
| Rewrite the flow | Introduce a new workflow struct and retain the old one until existing runs finish |

<a name="sleeping"></a>
## Sleeping

Call `run.sleep` to suspend a run for a duration, or `run.sleep_until` to wait until a specific `Timestamp` or `ZonedDateTime`. Sequential sleeps are numbered automatically, appearing in `workflow:show` as `sleep 1`, `sleep 2`, and so on, though you may label any sleep with `named`:

```rust
use laravel::time::ToSpan;

run.sleep(3.days()).await?;

run.sleep(1.hours()).named("trial grace period").await?;

run.sleep_until(self.trial_ends_at).await?;
```

Because sleeps are implemented as delayed queue jobs, they require a queue connection that supports delays. SQS FIFO queues do not support delays, and the `sync` connection executes jobs immediately, pausing at the first sleep until a test or `workflow:recover` advances the run.

<a name="waiting-and-resuming"></a>
## Waiting and resuming

`run.wait_for::<T>(token)` suspends the run until another part of your application delivers a value via `workflow::resume(token, value)`. For example, this workflow pauses until a manager approves or rejects an expense:

```rust
use laravel::workflow::{Run, workflow};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub enum Decision {
    Approved,
    Rejected { reason: String },
}

#[workflow]
impl ApproveExpense {
    async fn handle(self, run: &Run) -> laravel::Result<()> {
        run.step("ask the manager", self.ask_manager()).await?;

        let decision = run
            .wait_for::<Decision>(format!("expenses.{}.decision", self.expense_id))
            .await?;

        match decision {
            Decision::Approved => run.step("pay out", self.pay_out()).await,
            Decision::Rejected { reason } => {
                run.step("notify the employee", self.reject(&reason)).await
            }
        }
    }
}
```

When the run reaches `wait_for`, it claims ownership of `expenses.42.decision` until the run completes, fails, or is cancelled. In this example, the approval email links to a route whose handler resumes the waiting run:

```rust
use laravel::prelude::*;
use laravel::workflow::{self, Resumed};

pub async fn approve(Params(expense_id): Params<i64>) -> laravel::Result<Redirect> {
    let resumed =
        workflow::resume(format!("expenses.{expense_id}.decision"), Decision::Approved).await?;

    if resumed == Resumed::NotFound {
        return Ok(
            Redirect::to("/expenses")
                .with("status", "This expense was already decided."),
        );
    }

    Ok(Redirect::to("/expenses"))
}
```

`workflow::resume` returns `Resumed::Delivered` when an active run owns the token and receives the value, or `Resumed::NotFound` when no active run owns it (storing nothing, so a duplicate click on an already-decided expense won't accidentally resume a future run). Inside `db::transaction`, `workflow::resume` defers delivery until commit and returns `Resumed::Pending`.

A wait token is an identifier, not a secret. Anyone who can reach the route can resume the run, so protect it with an authorization [policy](authorization.md) (for example, checking that the signed-in user manages the expense) or a [signed URL](urls.md#signed-urls).

Because a per-record token like `expenses.42.decision` always routes to whichever run for that expense is currently active, an approval page left open in an old tab could still decide a newer run. If a page should only resume the specific run that rendered it, include `run.id()` in the token and pass that token in the form or link (or use a [resume URL](#resume-urls), which embeds the token for you):

```rust
let token = format!("expenses.{}.decision.{}", self.expense_id, run.id());

let decision = run.wait_for::<Decision>(token).await?;
```

Only one active run may own a given token at a time; if a second run calls `wait_for` on a token already owned by another active run, the second run fails with an error naming the owner. Include the record's ID in your tokens, and use a [unique start](#starting-a-run-once) when a record should only have one active run at a time.

Chaining `.timeout(span)` changes the wait's return type to `Option<T>`, yielding `None` if the duration elapses before a resume arrives:

```rust
let decision = run
    .wait_for::<Decision>(format!("expenses.{}.decision", self.expense_id))
    .timeout(3.days())
    .await?;
```

To inspect the waiting run before resuming it (for example, to check its attributes), call `workflow::waiting_for(token)`. It returns `Some(RunInfo)` for the run currently suspended on that token, or `None` if no run is waiting (including a run that has [claimed](#early-resumes) the token but hasn't reached `wait_for` yet):

```rust
let waiting = workflow::waiting_for(format!("expenses.{expense_id}.decision")).await?;

if let Some(run) = waiting {
    // Check run.attributes() before resuming...
}
```

<a name="early-resumes"></a>
### Early resumes

Sometimes a resume arrives before the workflow reaches `wait_for`. For example, a step might ask a payment gateway to charge a card, and the gateway's webhook might hit your application before the step finishes and the workflow advances to `run.wait_for`. Because no run owns the token yet, `workflow::resume` returns `Resumed::NotFound`.

To buffer early resumes for a run, claim the token when you start it. The run owns the token immediately, and any values sent before it reaches `wait_for` are queued and delivered in order:

```rust
let run_id = ChargeOrder { order_id }
    .start()
    .claim(format!("orders.{order_id}.charged"))
    .await?;
```

Starting the run fails if another active run already owns the token. You may chain `claim` for each token the run will wait on.

If you don't know the token at start time, return a non-2xx status from your webhook handler when `workflow::resume` returns `Resumed::NotFound` so the provider retries once the run is waiting. [Webhook URLs](#webhook-urls) do this automatically by responding with `404 Not Found`. In a custom route handler, match on the result:

```rust
use laravel::prelude::*;
use laravel::workflow::{self, Resumed};

pub async fn charged(
    Params(order_id): Params<i64>,
    Json(charge): Json<Charge>,
) -> StatusCode {
    match workflow::resume(format!("orders.{order_id}.charged"), charge).await {
        Ok(Resumed::NotFound) => StatusCode::NOT_FOUND,
        Ok(_) => StatusCode::ACCEPTED,
        Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
    }
}
```

<a name="typed-tokens"></a>
### Typed tokens

With string tokens, the workflow and the handler that resumes it are decoupled, so nothing stops a handler from sending the wrong type and causing a deserialization failure at runtime. Define a helper returning `workflow::Token<T>` so both sides share the same token string and payload type at compile time:

```rust
use laravel::workflow::Token;

pub fn decision(expense_id: i64) -> Token<Decision> {
    Token::new(format!("expenses.{expense_id}.decision"))
}
```

The workflow can then wait without specifying a turbofish, and the handler is type-checked against `Decision`:

```rust
// In the workflow...
let decided = run.wait_for(decision(self.expense_id)).await?;

// In the route's handler...
workflow::resume(decision(expense_id), Decision::Approved).await?;
```

Plain strings remain supported wherever a token is accepted. `Token<T>` serializes as its underlying string, so you can store one on models or workflow structs.

<a name="resume-urls"></a>
### Resume URLs

When a route exists solely to resume a workflow, like the `approve` handler above, Laravel can generate signed URLs for you in two styles.

`workflow::resume_url(token, value)` returns a `ResumeUrl` representing a signed link that embeds a fixed payload, such as an "Approve" button in an email. `ResumeUrl` implements `Display` and `Serialize`, so you can call `.to_string()` or pass it directly into a mailable, template, or JSON payload:

```rust
use laravel::mail;
use laravel::time::ToSpan;
use laravel::workflow;

let token = format!("expenses.{}.decision", self.expense_id);

run.step("email the manager", async {
    let approval_url = workflow::resume_url(&token, Decision::Approved)?
        .expires(3.days())
        .to_string();

    mail::to(&self.manager_email)
        .send(ApproveExpenseMail { approval_url })
        .await
})
.await?;

let decision = run.wait_for::<Decision>(&token).await?;
```

<a name="webhook-urls"></a>
#### Webhook URLs

`workflow::webhook_url(token)` generates a signed callback URL that an external service can POST JSON to in order to resume your workflow. For example, in the step below, we send an uploaded receipt's URL along with a signed callback URL to an external receipt scanning service, then pause the workflow until the scanner POSTs back the scanned total in cents:

```rust
use laravel::http::client;
use serde::Deserialize;
use serde_json::json;

#[derive(Deserialize)]
pub struct Scan {
    pub total_cents: i64,
}

let token = format!("expenses.{}.scan", self.expense_id);

run.step("request receipt scan", async {
    let callback_url = workflow::webhook_url(&token)?.to_string();

    client::post("https://scanner.example.com/scans")
        .json(json!({ "receipt_url": self.receipt_url, "callback_url": callback_url }))
        .ensure_successful()
        .await?;

    Ok(())
})
.await?;

let scan = run.wait_for::<Scan>(&token).await?;
```

Webhook requests whose body is not valid JSON receive a `400` response while the run keeps waiting. By default, the workflow decodes the body as `T` during its next advance, failing the run if the schema does not match.

<a name="customizing-the-resume-response"></a>
#### Customizing the response

By default, Laravel serves these URLs automatically and responds with `202 Accepted` (or `404 Not Found` when no active run owns the token). To return a custom view, JSON payload, or redirect instead, chain `respond` with one of your route handlers and its parameters, and accept `workflow::Resume<T>` as the handler's final parameter:

```rust
use laravel::prelude::*;
use laravel::view::View;
use laravel::workflow::{self, Resume, Resumed};

pub async fn decided(
    Params(expense_id): Params<i64>,
    resume: Resume<Decision>,
) -> View {
    let approved = matches!(resume.value, Decision::Approved);
    let already_decided = resume.outcome == Resumed::NotFound;

    view(
        "expenses.decided",
        data! {
            expense_id => expense_id,
            approved => approved,
            already_decided => already_decided,
        },
    )
}
```

```rust
let approval_url = workflow::resume_url("expenses.42.decision", Decision::Approved)?
    .expires(3.days())
    .respond(expenses::decided, 42)?;
```

Extracting `Resume<T>` verifies the signature, resumes the workflow before your handler runs, and provides the decoded payload. Invalid or expired signatures return `403` without invoking the handler. `resume.outcome` is `Resumed::NotFound` if no unfinished run owns the token, such as when a user clicks the link again after the run has finished. Routes that do not extract `Resume<T>` fail to compile with `respond`. Route middleware runs beforehand, so attaching `Authenticate` ensures only signed-in users can resume the run.

Because the signature only proves that Laravel generated the URL and not who opened it, anyone with the link can trigger it, including automated email link scanners. For sensitive approvals, protect the route with `Authenticate` or link to a confirmation page that calls `workflow::resume` on form submission.

<a name="inboxes"></a>
### Inboxes

`run.wait_for` waits for a single value, whereas `run.inbox_for::<T>(token)` lets a workflow receive multiple messages over time. Each call to `next()` suspends the run until another message arrives on that token, delivering messages in arrival order.

For example, suppose a large expense requires sign-off from two different managers. The workflow below notifies the approvers and loops over incoming `Vote` messages, rejecting the expense immediately if anyone votes no, approving it once two distinct managers vote yes, or expiring if five days pass between votes:

```rust
use std::collections::HashSet;

use laravel::queue::Queueable;
use laravel::time::ToSpan;
use laravel::workflow::{Run, workflow};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub struct Vote {
    pub approver_id: i64,
    pub approve: bool,
}

#[derive(Serialize, Deserialize)]
pub enum Outcome {
    Approved,
    Rejected,
    Expired,
}

#[derive(Queueable)]
pub struct ApproveLargeExpense {
    pub expense_id: i64,
}

#[workflow]
impl ApproveLargeExpense {
    async fn handle(self, run: &Run) -> laravel::Result<Outcome> {
        let mut votes = run.inbox_for::<Vote>(format!("expenses.{}.votes", self.expense_id));

        run.step("ask the approvers", self.ask_approvers()).await?;

        let mut approvers = HashSet::new();

        while let Some(vote) = votes.next().timeout(5.days()).await? {
            if !vote.approve {
                return Ok(Outcome::Rejected);
            }

            approvers.insert(vote.approver_id);

            if approvers.len() == 2 {
                return Ok(Outcome::Approved);
            }
        }

        Ok(Outcome::Expired)
    }
}
```

Each approver's vote is delivered via `workflow::resume(format!("expenses.{expense_id}.votes"), vote)` in a route handler. The loop exits when your code returns or breaks, or when `.timeout(span)` elapses and `next()` returns `None`.

Once a read times out, Laravel records that timeout so execution continues normally with any steps after the loop, and replays exit the loop at the same point even if late messages arrive afterward. Because the timeout applies per read, calling `next()` again after a timeout continues listening and receives any messages that arrive later without skipping them.

You can also build [resume and webhook URLs](#resume-urls) for an inbox token. Because every request appends another message, clicking a link twice sends two votes, so deduplicate by approver ID as the `HashSet` above does rather than counting raw messages.

The first `next()` claims the token for the run, as `wait_for` does, and the inbox then delivers every message sent to the token, including messages that arrive while the run is busy with a step. To keep messages sent before the first read, [claim the token at the start](#early-resumes). Because messages replay on every advance, a run may read from a single inbox at most 1,000 times before failing.

<a name="inspecting-and-cancelling-runs"></a>
## Inspecting and cancelling runs

`workflow::find` loads a run by ID, returning its status, steps, and output or error. `RunInfo` implements `Serialize`, so a handler can return it directly as JSON for a progress page:

```rust
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))
}
```

`RunInfo` provides `status()`, `steps()` with attempt counts and timing, `output::<T>()`, `error()`, `attributes()`, and `waiting_for()`. On a wait record, `timed_out()` distinguishes timed-out waits from resumed ones.

Call `workflow::cancel(run_id)` to stop an active run and dispatch `RunCancelled`, matching the `workflow:cancel` command. Any currently executing step finishes, and no further steps start. You can optionally attach a reason that appears in `workflow:show`, `RunInfo::error()`, and the `RunCancelled` event:

```rust
workflow::cancel(run_id).reason("the customer closed their account").await?;
```

`RunId` is a UUID that binds and decodes directly as a `uuid` database column, so you can store it on a model to track or inspect a run later. Add a `table.uuid("onboarding_run_id").nullable()` column in your migration, then add a `RunId` field to your model:

```rust
use laravel::model::{model, update};
use laravel::workflow::{self, RunId};

#[model]
pub struct User {
    pub id: i64,
    pub onboarding_run_id: Option<RunId>,
}

// When starting the workflow...
let run_id = OnboardUser { user_id: user.id }.start().await?;

update!(user { onboarding_run_id: Some(run_id) }).await?;

// Later, when inspecting or cancelling the run...
if let Some(run_id) = user.onboarding_run_id {
    let run = workflow::find(run_id).await?;
}
```

<a name="commands"></a>
### Commands

| Command | Description |
| --- | --- |
| `workflow:list` | Lists runs, newest first. Filter with `--status=failed`, `--name=users.onboard`, and `--attribute tenant=acme` |
| `workflow:show {id}` | Displays a run's input, status, attributes, output or error, and each step's attempts, timing, and errors |
| `workflow:retry {id}` | Resumes a failed run from the failing step while keeping earlier recorded steps intact and resetting the step's retries |
| `workflow:cancel {id}` | Cancels active runs. Pass `--reason="..."` to record why |
| `workflow:recover` | Requeues runs whose sleep, timeout, retry, or resume is due without a pending wake-up job |
| `workflow:prune` | Removes runs finished more than 24 hours ago, with their steps and resume values. Customize retention with `--hours=72` |

Pass `--json` to `workflow:list` or `workflow:show {id}` for single-line JSON output suitable for scripts and dashboards.

When invoked without IDs, `workflow:cancel` targets unfinished runs matching `--status`, `--name`, and `--attribute`, capped at `--limit` which defaults to 50. It prompts for confirmation unless you pass `--force`:

```shell
laravel workflow:cancel --attribute tenant=acme --reason="the tenant closed their account"
```

Because wake-ups are scheduled as delayed queue jobs, a worker crash between persisting a run and enqueueing its wake-up, or a cleared queue, can leave a run stranded. [Schedule](scheduling.md) `workflow:recover` and `workflow:prune` in `src/console/mod.rs` to recover stranded runs and keep your workflow tables clean:

```rust
use laravel::schedule::{self, Schedule};

#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
    schedule.command("workflow:recover").every_five_minutes();
    schedule.command("workflow:prune").daily();
}
```

<a name="events"></a>
## Events

Laravel dispatches [events](events.md) from `laravel::workflow::events`: `RunCompleted` when a workflow finishes, `RunFailed` after a permanent failure and its `failed` hook, and `RunCancelled` with its `reason` when a run is cancelled. Failed runs are also reported to your error handler. Any [context values](context.md) captured when the run started, such as the active tenant, are restored before your [listeners](events.md#defining-listeners) execute so log entries include them automatically:

```rust
use laravel::event::{Event, listener};
use laravel::workflow::events::RunFailed;

#[listener]
pub async fn log_failed_workflow(event: Event<RunFailed>) {
    tracing::error!(run = %event.run_id, error = %event.error, "A workflow run failed");
}
```

Each time a run advances, Laravel creates a [tracing](tracing.md) span named after the workflow, such as `workflow users.onboard`. Each step attempt creates a child span, such as `step charge card`, recording the run ID, step name, and attempt number. Both spans are marked failed on error, and starting or resuming a run continues the caller's trace so the triggering HTTP request and the workflow's execution appear in the same trace.

<a name="writing-a-store"></a>
## Writing a store

To persist workflow runs in another backend, such as DynamoDB, implement `laravel::workflow::store::Store`. Laravel handles replay orchestration, step retries, serialization, and job dispatching, so a custom store only handles persistence and atomic coordination. Four operations must be atomic: claiming a run lease with a fresh `Lease` token, assigning token ownership to a single active run, numbering values appended to a token owner's queue, and matching a wait against a pending resume. Each write during an advance (`record`, `wait`, `stop_waiting`, `set_attributes`, `renew`, and `release`) receives that `Lease` and must reject the write without mutating state if the lease is no longer active. When no active run owns a token, `resume` must discard the value rather than storing it:

```rust
use std::collections::BTreeMap;
use std::time::Duration;

use laravel::time::Timestamp;
use laravel::workflow::RunId;
use laravel::workflow::store::{
    Claim, Created, Delivery, Entry, Filter, Lease, NewRun, Outcome, RunRecord, Store, Waited,
};

#[derive(Debug)]
pub struct DynamoSettings {
    pub table: String,
}

pub struct DynamoStore {
    table: String,
    // DynamoDB client...
}

impl DynamoStore {
    pub async fn connect(table: &str) -> laravel::Result<Self> {
        Ok(Self { table: table.to_owned() })
    }
}

impl Store for DynamoStore {
    async fn create(&self, run: NewRun) -> laravel::Result<Created> {
        // Save the run and claim `run.tokens` unless unique or token conflicts...
        Ok(Created::Saved)
    }

    async fn claim(&self, id: RunId, lease: Duration) -> laravel::Result<Claim> {
        // Acquire the lease with a fresh `Lease` token and return the run...
        Ok(Claim::Ended)
    }

    async fn record(
        &self,
        id: RunId,
        lease: &Lease,
        entry: Entry,
    ) -> laravel::Result<bool> {
        // Upsert the step, sleep, or wait entry while `lease` is active...
        Ok(true)
    }

    async fn wait(
        &self,
        id: RunId,
        lease: &Lease,
        token: &str,
        number: u32,
    ) -> laravel::Result<Waited> {
        // Claim `token`, register the wait, or return a value while `lease` is active...
        Ok(Waited::Waiting)
    }

    async fn stop_waiting(
        &self,
        id: RunId,
        lease: &Lease,
        token: &str,
    ) -> laravel::Result<bool> {
        // Clear the run's wait on `token` after a timeout while `lease` is active...
        Ok(true)
    }

    async fn resume(&self, token: &str, value: String) -> laravel::Result<Delivery> {
        // Append `value` to the token owner's queue, or discard if unowned...
        Ok(Delivery::NotFound)
    }

    async fn waiting(&self, token: &str) -> laravel::Result<Option<RunId>> {
        // Return the ID of the run currently waiting on `token`...
        Ok(None)
    }

    async fn set_attributes(
        &self,
        id: RunId,
        lease: &Lease,
        attributes: BTreeMap<String, String>,
    ) -> laravel::Result<bool> {
        // Replace the run's stored attributes while `lease` is active...
        Ok(true)
    }

    async fn renew(
        &self,
        id: RunId,
        lease: &Lease,
        duration: Duration,
    ) -> laravel::Result<bool> {
        // Extend the run's lease while `lease` is active...
        Ok(true)
    }

    async fn release(
        &self,
        id: RunId,
        lease: &Lease,
        outcome: Outcome,
        now: Timestamp,
    ) -> laravel::Result<bool> {
        // Apply `outcome`, clear the lease, and free tokens while `lease` is active...
        Ok(true)
    }

    async fn find(&self, id: RunId) -> laravel::Result<Option<RunRecord>> {
        // Load a run record by ID...
        Ok(None)
    }

    async fn entries(&self, id: RunId) -> laravel::Result<Vec<Entry>> {
        // Load all recorded entries for the run in order...
        Ok(Vec::new())
    }

    async fn list(&self, filter: Filter) -> laravel::Result<Vec<RunRecord>> {
        // Query runs matching `filter`, newest first...
        Ok(Vec::new())
    }

    async fn cancel(
        &self,
        id: RunId,
        reason: Option<String>,
        now: Timestamp,
    ) -> laravel::Result<bool> {
        // Cancel the run via `RunRecord::cancel` and release its keys...
        Ok(false)
    }

    async fn retry(&self, id: RunId, now: Timestamp) -> laravel::Result<bool> {
        // Reset a failed run to pending at `now` and clear failed entries...
        Ok(false)
    }

    async fn overdue(&self, now: Timestamp) -> laravel::Result<Vec<RunRecord>> {
        // Return runs with an expired `wake_at`, lease, or ready wait...
        Ok(Vec::new())
    }

    async fn prune(&self, before: Timestamp) -> laravel::Result<u64> {
        // Delete runs finished before `before` with their entries and values...
        Ok(0)
    }
}
```

Register the store driver by name in `src/app.rs` or a package service provider:

```rust
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;

impl ServiceProvider for DynamoWorkflowServiceProvider {
    fn register(&self, app: &mut Registrar) {
        app.workflow().extend("dynamodb", async |_app, definition| {
            let settings = definition.settings::<DynamoSettings>()?;

            DynamoStore::connect(&settings.table).await
        });
    }
}
```

Then configure a store using that driver and select it with `WORKFLOW_STORE=dynamodb`:

```rust
// src/config/workflow.rs
use laravel::config::workflow::{StoreConfig, Workflow};
use laravel::config::{self, Env};

#[config::section]
fn workflow(env: &Env) -> Workflow {
    let mut workflow = Workflow::from_env(env);

    workflow.add_store(
        "dynamodb",
        StoreConfig::custom("dynamodb").settings(DynamoSettings { table: "workflows".into() }),
    );

    workflow
}
```

<a name="testing"></a>
## Testing

In tests, Laravel uses the `memory` workflow store and the `sync` queue connection by default, so workflow tests require neither database tables nor a running worker.

<a name="faking-starts"></a>
### Faking starts

When testing a route handler that only needs to verify a workflow was started, call `workflow::fake()` to record starts without saving or executing them:

```rust
use laravel::testing::prelude::*;
use laravel::workflow;

#[laravel::test]
async fn registering_starts_onboarding(app: Application) {
    let workflows = workflow::fake();

    app.post("/register")
        .json(json!({ "email": "taylor@laravel.com" }))
        .await
        .assert_redirect();

    workflows.assert_started::<OnboardUser>();
    workflows.assert_started_where::<OnboardUser>(|run| run.user_id == 1);
}
```

The fake also provides `assert_started_times::<T>(count)` and `assert_nothing_started()`, remaining active until its handle is dropped.

<a name="running-a-workflow-in-a-test"></a>
### Running a workflow in a test

`app.workflow(..)` starts a run and advances it until it completes or suspends. You can then move the clock with `app.travel` and call `run.advance()` to simulate a worker waking the run:

```rust
use laravel::mail;
use laravel::testing::prelude::*;

#[laravel::test]
async fn onboarding_sends_tips_when_user_has_no_projects(
    app: Application,
) -> laravel::Result<()> {
    let mail = mail::fake();
    let user = User::factory().create().await?;

    let run = app.workflow(OnboardUser { user_id: user.id }).await;

    mail.assert_sent::<Welcome>();
    run.assert_sleeping();

    app.travel(3.days());
    run.advance().await;

    mail.assert_sent::<GettingStartedTips>();
    run.assert_completed();

    Ok(())
}
```

Additional assertions on the returned run include `assert_completed`, `assert_completed_with`, `assert_failed`, `assert_failed_with(message)`, `assert_retrying(name)`, `assert_step_ran(name)`, `assert_step_not_ran(name)`, and `assert_step_tries(name, count)`.

Because steps are named, you can stub a step's output directly in a test without faking the underlying service:

```rust
let run = app
    .workflow(Checkout { order_id: 1 })
    .with_step("charge card", Receipt { id: "re_1".into() })
    .await;
```

Stubbed steps record as completed with zero attempts, so `run.assert_step_tries("charge card", 0)` verifies the stub was used.

<a name="testing-waits-and-resumes"></a>
### Testing waits and resumes

When a workflow pauses at `run.wait_for` or `run.inbox_for`, assert the wait token with `run.assert_waiting_for(token)`, then call `run.resume(token, value)` to deliver a payload and advance the run immediately. Both methods accept either a plain string or a [typed `Token<T>`](#typed-tokens):

```rust
use laravel::testing::prelude::*;

use crate::workflows::approve_expense::{ApproveExpense, Decision, decision};

#[laravel::test]
async fn approved_expenses_are_paid_out(app: Application) -> laravel::Result<()> {
    let token = decision(42);

    let run = app.workflow(ApproveExpense { expense_id: 42 }).await;

    run.assert_waiting_for(&token);

    run.resume(token, Decision::Approved)
        .await
        .assert_step_ran("pay out")
        .assert_completed();

    Ok(())
}
```

For [inboxes](#inboxes), call `run.resume` once for each incoming message in order:

```rust
use crate::workflows::approve_large_expense::{ApproveLargeExpense, Outcome, Vote};

let token = "expenses.42.votes";
let run = app.workflow(ApproveLargeExpense { expense_id: 42 }).await;

run.assert_waiting_for(token);

run.resume(token, Vote { approver_id: 1, approve: true })
    .await
    .assert_waiting_for(token);

run.resume(token, Vote { approver_id: 2, approve: true })
    .await
    .assert_completed_with(Outcome::Approved);
```

To test an [early resume](#early-resumes) arriving before the run reaches `wait_for`, claim the token when starting the test run:

```rust
let run = app
    .workflow(ChargeOrder { order_id: 42 })
    .claim("orders.42.charged")
    .await;
```

To test a wait's `.timeout(..)` branch, travel past the timeout and call `run.advance()` without resuming:

```rust
let run = app.workflow(ApproveExpense { expense_id: 42 }).await;

app.travel(4.days());
run.advance().await.assert_completed();
```