Workflows
- Introduction
- Setup
- Defining workflows
- Starting runs
- Steps
- Rules for
handle - Sleeping
- Waiting and resuming
- Inspecting and cancelling runs
- Events
- Writing a store
- Testing
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 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:
1// src/workflows/onboard_user.rs2use laravel::queue::Queueable;3use laravel::time::ToSpan;4use laravel::workflow::{Run, workflow};56#[derive(Queueable)]7pub struct OnboardUser {8 pub user_id: i64,9}1011#[workflow]12impl OnboardUser {13 async fn handle(self, run: &Run) -> laravel::Result<()> {14 run.step("send welcome email", self.send_welcome_email()).await?;1516 run.sleep(3.days()).await?;1718 if run.step("count projects", self.count_projects()).await? == 0 {19 run.step("send tips", self.send_tips()).await?;20 }2122 Ok(())23 }24}1// src/workflows/onboard_user.rs2use laravel::queue::Queueable;3use laravel::time::ToSpan;4use laravel::workflow::{Run, workflow};56#[derive(Queueable)]7pub struct OnboardUser {8 pub user_id: i64,9}1011#[workflow]12impl OnboardUser {13 async fn handle(self, run: &Run) -> laravel::Result<()> {14 run.step("send welcome email", self.send_welcome_email()).await?;1516 run.sleep(3.days()).await?;1718 if run.step("count projects", self.count_projects()).await? == 0 {19 run.step("send tips", self.send_tips()).await?;20 }2122 Ok(())23 }24}
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.
Setup
Workflows require a queue worker backed by a connection that supports delayed jobs, such as database, redis, or sqs.
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 that holds only the workflow::tables! macro before starting a workflow. The macro creates all five tables:
1// database/migrations/2026_01_01_000000_create_workflow_tables.rs2laravel::workflow::tables!();1// database/migrations/2026_01_01_000000_create_workflow_tables.rs2laravel::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:
1// database/migrations/2026_01_01_000000_create_workflow_tables.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .create("workflow_runs", |table| {7 table.string("id").length(36).primary();8 table.string("workflow");9 table.long_text("input");10 table.long_text("context");11 table.string("connection");12 table.string("queue");13 table.string("status").length(16);14 table.long_text("output").nullable();15 table.text("error").nullable();16 table.timestamp("wake_at").nullable();17 table.timestamp("leased_until").nullable();18 table.string("lease_token").length(36).nullable();19 table.timestamp("created_at");20 table.timestamp("finished_at").nullable();21 table.string("unique_key").nullable().unique();22 table.boolean("purge_data").default(false);2324 table.index(["workflow", "id"]);25 table.index(["status", "wake_at"]);26 table.index("finished_at");27 })28 .await?;2930 tx.schema()31 .create("workflow_steps", |table| {32 table.id();33 table.string("run_id").length(36);34 table.string("kind").length(8);35 table.string("name");36 table.string("status").length(16);37 table.integer("tries");38 table.long_text("output").nullable();39 table.text("error").nullable();40 table.timestamp("wake_at").nullable();41 table.timestamp("started_at");42 table.timestamp("finished_at").nullable();4344 table.unique(["run_id", "kind", "name"]);45 })46 .await?;4748 tx.schema()49 .create("workflow_waits", |table| {50 table.string("token").primary();51 table.string("run_id").length(36);52 table.integer("number").nullable();53 table.timestamp("resumed_at").nullable();5455 table.index("run_id");56 })57 .await?;5859 tx.schema()60 .create("workflow_resumes", |table| {61 table.string("run_id").length(36);62 table.string("token");63 table.big_integer("number");64 table.long_text("value");65 table.timestamp("created_at");6667 table.primary(["run_id", "token", "number"]);68 })69 .await?;7071 tx.schema()72 .create("workflow_attributes", |table| {73 table.string("run_id").length(36);74 table.string("name");75 table.string("value");7677 table.primary(["run_id", "name"]);78 table.index(["name", "value"]);79 })80 .await81}1// database/migrations/2026_01_01_000000_create_workflow_tables.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .create("workflow_runs", |table| {7 table.string("id").length(36).primary();8 table.string("workflow");9 table.long_text("input");10 table.long_text("context");11 table.string("connection");12 table.string("queue");13 table.string("status").length(16);14 table.long_text("output").nullable();15 table.text("error").nullable();16 table.timestamp("wake_at").nullable();17 table.timestamp("leased_until").nullable();18 table.string("lease_token").length(36).nullable();19 table.timestamp("created_at");20 table.timestamp("finished_at").nullable();21 table.string("unique_key").nullable().unique();22 table.boolean("purge_data").default(false);2324 table.index(["workflow", "id"]);25 table.index(["status", "wake_at"]);26 table.index("finished_at");27 })28 .await?;2930 tx.schema()31 .create("workflow_steps", |table| {32 table.id();33 table.string("run_id").length(36);34 table.string("kind").length(8);35 table.string("name");36 table.string("status").length(16);37 table.integer("tries");38 table.long_text("output").nullable();39 table.text("error").nullable();40 table.timestamp("wake_at").nullable();41 table.timestamp("started_at");42 table.timestamp("finished_at").nullable();4344 table.unique(["run_id", "kind", "name"]);45 })46 .await?;4748 tx.schema()49 .create("workflow_waits", |table| {50 table.string("token").primary();51 table.string("run_id").length(36);52 table.integer("number").nullable();53 table.timestamp("resumed_at").nullable();5455 table.index("run_id");56 })57 .await?;5859 tx.schema()60 .create("workflow_resumes", |table| {61 table.string("run_id").length(36);62 table.string("token");63 table.big_integer("number");64 table.long_text("value");65 table.timestamp("created_at");6667 table.primary(["run_id", "token", "number"]);68 })69 .await?;7071 tx.schema()72 .create("workflow_attributes", |table| {73 table.string("run_id").length(36);74 table.string("name");75 table.string("value");7677 table.primary(["run_id", "name"]);78 table.index(["name", "value"]);79 })80 .await81}
To store these tables on a separate database connection, set DB_WORKFLOW_CONNECTION.
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:
1// src/config/workflow.rs2use laravel::config::workflow::{DatabaseStore, Workflow};3use laravel::config::{self, Env};45#[config::section]6fn workflow(env: &Env) -> Workflow {7 let mut workflow = Workflow::from_env(env);89 workflow.add_store("database", DatabaseStore::new().connection("workflows"));1011 workflow12}1// src/config/workflow.rs2use laravel::config::workflow::{DatabaseStore, Workflow};3use laravel::config::{self, Env};45#[config::section]6fn workflow(env: &Env) -> Workflow {7 let mut workflow = Workflow::from_env(env);89 workflow.add_store("database", DatabaseStore::new().connection("workflows"));1011 workflow12}
Defining workflows
Like a job, 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 to observe every failure:
1use laravel::container::Inject;2use laravel::workflow::{Run, workflow};34#[workflow(name = "orders.checkout")]5impl Checkout {6 async fn handle(self, run: &Run, payments: Inject<Payments>) -> laravel::Result<()> {7 run.step("charge card", payments.charge(self.order_id)).await?;89 Ok(())10 }1112 async fn failed(self, error: &laravel::Error, slack: Inject<Slack>) {13 slack.alert(format!("checkout {} failed: {error}", self.order_id)).await;14 }15}1use laravel::container::Inject;2use laravel::workflow::{Run, workflow};34#[workflow(name = "orders.checkout")]5impl Checkout {6 async fn handle(self, run: &Run, payments: Inject<Payments>) -> laravel::Result<()> {7 run.step("charge card", payments.charge(self.order_id)).await?;89 Ok(())10 }1112 async fn failed(self, error: &laravel::Error, slack: Inject<Slack>) {13 slack.alert(format!("checkout {} failed: {error}", self.order_id)).await;14 }15}
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:
1use laravel::prelude::*;23use crate::workflows::OnboardUser;45pub async fn store(user: User) -> laravel::Result<Redirect> {6 OnboardUser { user_id: user.id }.start().await?;78 Ok(Redirect::to("/dashboard"))9}1use laravel::prelude::*;23use crate::workflows::OnboardUser;45pub async fn store(user: User) -> laravel::Result<Redirect> {6 OnboardUser { user_id: user.id }.start().await?;78 Ok(Redirect::to("/dashboard"))9}
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:
1use laravel::time::ToSpan;23let run_id = OnboardUser { user_id: user.id }4 .start()5 .on_connection("redis")6 .on_queue("workflows")7 .delay(1.hours())8 .await?;1use laravel::time::ToSpan;23let run_id = OnboardUser { user_id: user.id }4 .start()5 .on_connection("redis")6 .on_queue("workflows")7 .delay(1.hours())8 .await?;
Starting a workflow inside db::transaction waits until the transaction commits and is discarded on rollback, as dispatching a job does. Laravel captures the current context values, such as the active tenant, and restores them on every advance.
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:
1use laravel::prelude::*;2use laravel::workflow::Started;34pub async fn submit(Params(expense_id): Params<i64>) -> laravel::Result<Redirect> {5 let started = ApproveExpense { expense_id }6 .start()7 .unique(format!("expenses.{expense_id}"))8 .await?;910 if let Started::Existing(run_id) = started {11 tracing::info!(%run_id, "the expense is already waiting for approval");12 }1314 Ok(Redirect::to("/expenses"))15}1use laravel::prelude::*;2use laravel::workflow::Started;34pub async fn submit(Params(expense_id): Params<i64>) -> laravel::Result<Redirect> {5 let started = ApproveExpense { expense_id }6 .start()7 .unique(format!("expenses.{expense_id}"))8 .await?;910 if let Started::Existing(run_id) = started {11 tracing::info!(%run_id, "the expense is already waiting for approval");12 }1314 Ok(Redirect::to("/expenses"))15}
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.
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:
1let run_id = OnboardUser { user_id: user.id }2 .start()3 .attribute("tenant", "acme")4 .attribute("plan", "pro")5 .await?;1let run_id = OnboardUser { user_id: user.id }2 .start()3 .attribute("tenant", "acme")4 .attribute("plan", "pro")5 .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:
1run.step("charge card", self.charge_card()).await?;2run.set_attribute("phase", "shipping");1run.step("charge card", self.charge_card()).await?;2run.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.
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:
1let run_id = VerifyBankAccount { account_id }2 .start()3 .purge_when_finished()4 .await?;1let run_id = VerifyBankAccount { account_id }2 .start()3 .purge_when_finished()4 .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.
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:
1let receipt = run.step("charge card", self.charge_card()).await?;23let total = run4 .step("total the order", async {5 let order = Order::find_or_fail(self.order_id).await?;67 order.total().await8 })9 .await?;1let receipt = run.step("charge card", self.charge_card()).await?;23let total = run4 .step("total the order", async {5 let order = Order::find_or_fail(self.order_id).await?;67 order.total().await8 })9 .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:
1for day in [1, 3, 7] {2 run.sleep(day.days()).await?;3 run.step(format!("send reminder {day}"), self.send_reminder(day)).await?;4}1for day in [1, 3, 7] {2 run.sleep(day.days()).await?;3 run.step(format!("send reminder {day}"), self.send_reminder(day)).await?;4}
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:
1let receipt = run2 .step("charge card", self.charge_card())3 .tries(5)4 .backoff([10.seconds(), 1.minutes(), 10.minutes()])5 .timeout(30.seconds())6 .await?;1let receipt = run2 .step("charge card", self.charge_card())3 .tries(5)4 .backoff([10.seconds(), 1.minutes(), 10.minutes()])5 .timeout(30.seconds())6 .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:
1use laravel::http::client;2use laravel::prelude::*;3use laravel::workflow;45#[derive(Debug, thiserror::Error)]6#[error("the CRM is busy")]7struct CrmBusy;89async fn sync_contacts(&self) -> laravel::Result<()> {10 let response = client::post("https://crm.example.com/contacts/sync").await?;1112 if response.status() == StatusCode::TOO_MANY_REQUESTS {13 let seconds: i64 = response14 .header("retry-after")15 .and_then(|seconds| seconds.parse().ok())16 .unwrap_or(60);1718 return Err(workflow::retry_after(seconds.seconds(), CrmBusy));19 }2021 Ok(())22}1use laravel::http::client;2use laravel::prelude::*;3use laravel::workflow;45#[derive(Debug, thiserror::Error)]6#[error("the CRM is busy")]7struct CrmBusy;89async fn sync_contacts(&self) -> laravel::Result<()> {10 let response = client::post("https://crm.example.com/contacts/sync").await?;1112 if response.status() == StatusCode::TOO_MANY_REQUESTS {13 let seconds: i64 = response14 .header("retry-after")15 .and_then(|seconds| seconds.parse().ok())16 .unwrap_or(60);1718 return Err(workflow::retry_after(seconds.seconds(), CrmBusy));19 }2021 Ok(())22}
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:
1use serde_json::json;23async fn charge_card(&self) -> laravel::Result<()> {4 let step = workflow::current_step();56 client::post("https://payments.example.com/charges")7 .header("Idempotency-Key", step.key())8 .json(json!({ "order_id": self.order_id }))9 .await?;1011 Ok(())12}1use serde_json::json;23async fn charge_card(&self) -> laravel::Result<()> {4 let step = workflow::current_step();56 client::post("https://payments.example.com/charges")7 .header("Idempotency-Key", step.key())8 .json(json!({ "order_id": self.order_id }))9 .await?;1011 Ok(())12}
You can also inspect step.attempt() to see the 1-based attempt number, such as when adjusting behavior on the final retry.
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:
1use laravel::workflow;23async fn charge_card(&self) -> laravel::Result<Receipt> {4 self.gateway.charge(self.order_id).await.map_err(workflow::fatal)5}1use laravel::workflow;23async fn charge_card(&self) -> laravel::Result<Receipt> {4 self.gateway.charge(self.order_id).await.map_err(workflow::fatal)5}
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:
1let flight = run.step("book flight", self.book_flight()).await?;23if let Err(error) = run.step("book hotel", self.book_hotel()).await {4 run.step("cancel flight", self.cancel_flight(&flight)).await?;56 return Err(error);7}1let flight = run.step("book flight", self.book_flight()).await?;23if let Err(error) = run.step("book hotel", self.book_hotel()).await {4 run.step("cancel flight", self.cancel_flight(&flight)).await?;56 return Err(error);7}
"cancel flight" is a normal workflow step, so Laravel retries and records it like "book flight" and "book hotel".
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:
1use laravel::task;23let (projects, teammates) = task::try_join!(4 run.step("count projects", self.count_projects()),5 run.step("count teammates", self.count_teammates()),6)?;1use laravel::task;23let (projects, teammates) = task::try_join!(4 run.step("count projects", self.count_projects()),5 run.step("count teammates", self.count_teammates()),6)?;
To fan work out across multiple queue workers and wait for all of it to finish, claim the completion token when you start the workflow so a fast batch can't finish before wait_for runs, dispatch a job batch whose finally callback calls workflow::resume with whether the batch succeeded, and pause the workflow with run.wait_for:
1use laravel::queue::{self, Batch, callback};2use laravel::workflow::{self, Run};34#[callback]5async fn batch_finished(token: String, batch: &Batch) -> laravel::Result<()> {6 workflow::resume(token, batch.failed_jobs() == 0).await?;78 Ok(())9}1011// Claim the token before starting so early completions are buffered:12// ImportContacts { import_id, chunks }13// .start()14// .claim(format!("imports.{import_id}.done"))15// .await?;1617async fn handle(self, run: &Run) -> laravel::Result<()> {18 let token = format!("imports.{}.done", self.import_id);1920 run.step("dispatch batch", async {21 let jobs = self.chunks.iter().cloned().map(|rows| ImportCsv { rows });2223 queue::batch(jobs).finally(batch_finished(token.clone())).await?;2425 Ok(())26 })27 .await?;2829 let succeeded = run.wait_for::<bool>(&token).await?;3031 if !succeeded {32 return Err(laravel::Error::msg("one or more import jobs failed"));33 }3435 run.step("mark import complete", self.mark_complete()).await?;3637 Ok(())38}1use laravel::queue::{self, Batch, callback};2use laravel::workflow::{self, Run};34#[callback]5async fn batch_finished(token: String, batch: &Batch) -> laravel::Result<()> {6 workflow::resume(token, batch.failed_jobs() == 0).await?;78 Ok(())9}1011// Claim the token before starting so early completions are buffered:12// ImportContacts { import_id, chunks }13// .start()14// .claim(format!("imports.{import_id}.done"))15// .await?;1617async fn handle(self, run: &Run) -> laravel::Result<()> {18 let token = format!("imports.{}.done", self.import_id);1920 run.step("dispatch batch", async {21 let jobs = self.chunks.iter().cloned().map(|rows| ImportCsv { rows });2223 queue::batch(jobs).finally(batch_finished(token.clone())).await?;2425 Ok(())26 })27 .await?;2829 let succeeded = run.wait_for::<bool>(&token).await?;3031 if !succeeded {32 return Err(laravel::Error::msg("one or more import jobs failed"));33 }3435 run.step("mark import complete", self.mark_complete()).await?;3637 Ok(())38}
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
handleawaits 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()andrun.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
Inboxhandles. - 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(..)onwait_forinstead of combining it withrun.sleepintask::select!.
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 |
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:
1use laravel::time::ToSpan;23run.sleep(3.days()).await?;45run.sleep(1.hours()).named("trial grace period").await?;67run.sleep_until(self.trial_ends_at).await?;1use laravel::time::ToSpan;23run.sleep(3.days()).await?;45run.sleep(1.hours()).named("trial grace period").await?;67run.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.
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:
1use laravel::workflow::{Run, workflow};2use serde::{Deserialize, Serialize};34#[derive(Serialize, Deserialize)]5pub enum Decision {6 Approved,7 Rejected { reason: String },8}910#[workflow]11impl ApproveExpense {12 async fn handle(self, run: &Run) -> laravel::Result<()> {13 run.step("ask the manager", self.ask_manager()).await?;1415 let decision = run16 .wait_for::<Decision>(format!("expenses.{}.decision", self.expense_id))17 .await?;1819 match decision {20 Decision::Approved => run.step("pay out", self.pay_out()).await,21 Decision::Rejected { reason } => {22 run.step("notify the employee", self.reject(&reason)).await23 }24 }25 }26}1use laravel::workflow::{Run, workflow};2use serde::{Deserialize, Serialize};34#[derive(Serialize, Deserialize)]5pub enum Decision {6 Approved,7 Rejected { reason: String },8}910#[workflow]11impl ApproveExpense {12 async fn handle(self, run: &Run) -> laravel::Result<()> {13 run.step("ask the manager", self.ask_manager()).await?;1415 let decision = run16 .wait_for::<Decision>(format!("expenses.{}.decision", self.expense_id))17 .await?;1819 match decision {20 Decision::Approved => run.step("pay out", self.pay_out()).await,21 Decision::Rejected { reason } => {22 run.step("notify the employee", self.reject(&reason)).await23 }24 }25 }26}
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:
1use laravel::prelude::*;2use laravel::workflow::{self, Resumed};34pub async fn approve(Params(expense_id): Params<i64>) -> laravel::Result<Redirect> {5 let resumed =6 workflow::resume(format!("expenses.{expense_id}.decision"), Decision::Approved).await?;78 if resumed == Resumed::NotFound {9 return Ok(10 Redirect::to("/expenses")11 .with("status", "This expense was already decided."),12 );13 }1415 Ok(Redirect::to("/expenses"))16}1use laravel::prelude::*;2use laravel::workflow::{self, Resumed};34pub async fn approve(Params(expense_id): Params<i64>) -> laravel::Result<Redirect> {5 let resumed =6 workflow::resume(format!("expenses.{expense_id}.decision"), Decision::Approved).await?;78 if resumed == Resumed::NotFound {9 return Ok(10 Redirect::to("/expenses")11 .with("status", "This expense was already decided."),12 );13 }1415 Ok(Redirect::to("/expenses"))16}
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 (for example, checking that the signed-in user manages the expense) or a signed URL.
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, which embeds the token for you):
1let token = format!("expenses.{}.decision.{}", self.expense_id, run.id());23let decision = run.wait_for::<Decision>(token).await?;1let token = format!("expenses.{}.decision.{}", self.expense_id, run.id());23let 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 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:
1let decision = run2 .wait_for::<Decision>(format!("expenses.{}.decision", self.expense_id))3 .timeout(3.days())4 .await?;1let decision = run2 .wait_for::<Decision>(format!("expenses.{}.decision", self.expense_id))3 .timeout(3.days())4 .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 the token but hasn't reached wait_for yet):
1let waiting = workflow::waiting_for(format!("expenses.{expense_id}.decision")).await?;23if let Some(run) = waiting {4 // Check run.attributes() before resuming...5}1let waiting = workflow::waiting_for(format!("expenses.{expense_id}.decision")).await?;23if let Some(run) = waiting {4 // Check run.attributes() before resuming...5}
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:
1let run_id = ChargeOrder { order_id }2 .start()3 .claim(format!("orders.{order_id}.charged"))4 .await?;1let run_id = ChargeOrder { order_id }2 .start()3 .claim(format!("orders.{order_id}.charged"))4 .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 do this automatically by responding with 404 Not Found. In a custom route handler, match on the result:
1use laravel::prelude::*;2use laravel::workflow::{self, Resumed};34pub async fn charged(5 Params(order_id): Params<i64>,6 Json(charge): Json<Charge>,7) -> StatusCode {8 match workflow::resume(format!("orders.{order_id}.charged"), charge).await {9 Ok(Resumed::NotFound) => StatusCode::NOT_FOUND,10 Ok(_) => StatusCode::ACCEPTED,11 Err(_) => StatusCode::INTERNAL_SERVER_ERROR,12 }13}1use laravel::prelude::*;2use laravel::workflow::{self, Resumed};34pub async fn charged(5 Params(order_id): Params<i64>,6 Json(charge): Json<Charge>,7) -> StatusCode {8 match workflow::resume(format!("orders.{order_id}.charged"), charge).await {9 Ok(Resumed::NotFound) => StatusCode::NOT_FOUND,10 Ok(_) => StatusCode::ACCEPTED,11 Err(_) => StatusCode::INTERNAL_SERVER_ERROR,12 }13}
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:
1use laravel::workflow::Token;23pub fn decision(expense_id: i64) -> Token<Decision> {4 Token::new(format!("expenses.{expense_id}.decision"))5}1use laravel::workflow::Token;23pub fn decision(expense_id: i64) -> Token<Decision> {4 Token::new(format!("expenses.{expense_id}.decision"))5}
The workflow can then wait without specifying a turbofish, and the handler is type-checked against Decision:
1// In the workflow...2let decided = run.wait_for(decision(self.expense_id)).await?;34// In the route's handler...5workflow::resume(decision(expense_id), Decision::Approved).await?;1// In the workflow...2let decided = run.wait_for(decision(self.expense_id)).await?;34// In the route's handler...5workflow::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.
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:
1use laravel::mail;2use laravel::time::ToSpan;3use laravel::workflow;45let token = format!("expenses.{}.decision", self.expense_id);67run.step("email the manager", async {8 let approval_url = workflow::resume_url(&token, Decision::Approved)?9 .expires(3.days())10 .to_string();1112 mail::to(&self.manager_email)13 .send(ApproveExpenseMail { approval_url })14 .await15})16.await?;1718let decision = run.wait_for::<Decision>(&token).await?;1use laravel::mail;2use laravel::time::ToSpan;3use laravel::workflow;45let token = format!("expenses.{}.decision", self.expense_id);67run.step("email the manager", async {8 let approval_url = workflow::resume_url(&token, Decision::Approved)?9 .expires(3.days())10 .to_string();1112 mail::to(&self.manager_email)13 .send(ApproveExpenseMail { approval_url })14 .await15})16.await?;1718let decision = run.wait_for::<Decision>(&token).await?;
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:
1use laravel::http::client;2use serde::Deserialize;3use serde_json::json;45#[derive(Deserialize)]6pub struct Scan {7 pub total_cents: i64,8}910let token = format!("expenses.{}.scan", self.expense_id);1112run.step("request receipt scan", async {13 let callback_url = workflow::webhook_url(&token)?.to_string();1415 client::post("https://scanner.example.com/scans")16 .json(json!({ "receipt_url": self.receipt_url, "callback_url": callback_url }))17 .ensure_successful()18 .await?;1920 Ok(())21})22.await?;2324let scan = run.wait_for::<Scan>(&token).await?;1use laravel::http::client;2use serde::Deserialize;3use serde_json::json;45#[derive(Deserialize)]6pub struct Scan {7 pub total_cents: i64,8}910let token = format!("expenses.{}.scan", self.expense_id);1112run.step("request receipt scan", async {13 let callback_url = workflow::webhook_url(&token)?.to_string();1415 client::post("https://scanner.example.com/scans")16 .json(json!({ "receipt_url": self.receipt_url, "callback_url": callback_url }))17 .ensure_successful()18 .await?;1920 Ok(())21})22.await?;2324let 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.
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:
1use laravel::prelude::*;2use laravel::view::View;3use laravel::workflow::{self, Resume, Resumed};45pub async fn decided(6 Params(expense_id): Params<i64>,7 resume: Resume<Decision>,8) -> View {9 let approved = matches!(resume.value, Decision::Approved);10 let already_decided = resume.outcome == Resumed::NotFound;1112 view(13 "expenses.decided",14 data! {15 expense_id => expense_id,16 approved => approved,17 already_decided => already_decided,18 },19 )20}1use laravel::prelude::*;2use laravel::view::View;3use laravel::workflow::{self, Resume, Resumed};45pub async fn decided(6 Params(expense_id): Params<i64>,7 resume: Resume<Decision>,8) -> View {9 let approved = matches!(resume.value, Decision::Approved);10 let already_decided = resume.outcome == Resumed::NotFound;1112 view(13 "expenses.decided",14 data! {15 expense_id => expense_id,16 approved => approved,17 already_decided => already_decided,18 },19 )20}
1let approval_url = workflow::resume_url("expenses.42.decision", Decision::Approved)?2 .expires(3.days())3 .respond(expenses::decided, 42)?;1let approval_url = workflow::resume_url("expenses.42.decision", Decision::Approved)?2 .expires(3.days())3 .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.
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:
1use std::collections::HashSet;23use laravel::queue::Queueable;4use laravel::time::ToSpan;5use laravel::workflow::{Run, workflow};6use serde::{Deserialize, Serialize};78#[derive(Serialize, Deserialize)]9pub struct Vote {10 pub approver_id: i64,11 pub approve: bool,12}1314#[derive(Serialize, Deserialize)]15pub enum Outcome {16 Approved,17 Rejected,18 Expired,19}2021#[derive(Queueable)]22pub struct ApproveLargeExpense {23 pub expense_id: i64,24}2526#[workflow]27impl ApproveLargeExpense {28 async fn handle(self, run: &Run) -> laravel::Result<Outcome> {29 let mut votes = run.inbox_for::<Vote>(format!("expenses.{}.votes", self.expense_id));3031 run.step("ask the approvers", self.ask_approvers()).await?;3233 let mut approvers = HashSet::new();3435 while let Some(vote) = votes.next().timeout(5.days()).await? {36 if !vote.approve {37 return Ok(Outcome::Rejected);38 }3940 approvers.insert(vote.approver_id);4142 if approvers.len() == 2 {43 return Ok(Outcome::Approved);44 }45 }4647 Ok(Outcome::Expired)48 }49}1use std::collections::HashSet;23use laravel::queue::Queueable;4use laravel::time::ToSpan;5use laravel::workflow::{Run, workflow};6use serde::{Deserialize, Serialize};78#[derive(Serialize, Deserialize)]9pub struct Vote {10 pub approver_id: i64,11 pub approve: bool,12}1314#[derive(Serialize, Deserialize)]15pub enum Outcome {16 Approved,17 Rejected,18 Expired,19}2021#[derive(Queueable)]22pub struct ApproveLargeExpense {23 pub expense_id: i64,24}2526#[workflow]27impl ApproveLargeExpense {28 async fn handle(self, run: &Run) -> laravel::Result<Outcome> {29 let mut votes = run.inbox_for::<Vote>(format!("expenses.{}.votes", self.expense_id));3031 run.step("ask the approvers", self.ask_approvers()).await?;3233 let mut approvers = HashSet::new();3435 while let Some(vote) = votes.next().timeout(5.days()).await? {36 if !vote.approve {37 return Ok(Outcome::Rejected);38 }3940 approvers.insert(vote.approver_id);4142 if approvers.len() == 2 {43 return Ok(Outcome::Approved);44 }45 }4647 Ok(Outcome::Expired)48 }49}
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 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. Because messages replay on every advance, a run may read from a single inbox at most 1,000 times before failing.
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:
1use laravel::prelude::*;2use laravel::workflow::{self, RunId, RunInfo};34pub async fn show(Params(run_id): Params<RunId>) -> laravel::Result<Json<RunInfo>> {5 let run = workflow::find(run_id).await?.or_abort(404)?;67 Ok(Json(run))8}1use laravel::prelude::*;2use laravel::workflow::{self, RunId, RunInfo};34pub async fn show(Params(run_id): Params<RunId>) -> laravel::Result<Json<RunInfo>> {5 let run = workflow::find(run_id).await?.or_abort(404)?;67 Ok(Json(run))8}
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:
1workflow::cancel(run_id).reason("the customer closed their account").await?;1workflow::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:
1use laravel::model::{model, update};2use laravel::workflow::{self, RunId};34#[model]5pub struct User {6 pub id: i64,7 pub onboarding_run_id: Option<RunId>,8}910// When starting the workflow...11let run_id = OnboardUser { user_id: user.id }.start().await?;1213update!(user { onboarding_run_id: Some(run_id) }).await?;1415// Later, when inspecting or cancelling the run...16if let Some(run_id) = user.onboarding_run_id {17 let run = workflow::find(run_id).await?;18}1use laravel::model::{model, update};2use laravel::workflow::{self, RunId};34#[model]5pub struct User {6 pub id: i64,7 pub onboarding_run_id: Option<RunId>,8}910// When starting the workflow...11let run_id = OnboardUser { user_id: user.id }.start().await?;1213update!(user { onboarding_run_id: Some(run_id) }).await?;1415// Later, when inspecting or cancelling the run...16if let Some(run_id) = user.onboarding_run_id {17 let run = workflow::find(run_id).await?;18}
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:
1laravel workflow:cancel --attribute tenant=acme --reason="the tenant closed their account"1laravel 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 workflow:recover and workflow:prune in src/console/mod.rs to recover stranded runs and keep your workflow tables clean:
1use laravel::schedule::{self, Schedule};23#[schedule::tasks]4fn schedule(schedule: &mut Schedule) {5 schedule.command("workflow:recover").every_five_minutes();6 schedule.command("workflow:prune").daily();7}1use laravel::schedule::{self, Schedule};23#[schedule::tasks]4fn schedule(schedule: &mut Schedule) {5 schedule.command("workflow:recover").every_five_minutes();6 schedule.command("workflow:prune").daily();7}
Events
Laravel dispatches events 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 captured when the run started, such as the active tenant, are restored before your listeners execute so log entries include them automatically:
1use laravel::event::{Event, listener};2use laravel::workflow::events::RunFailed;34#[listener]5pub async fn log_failed_workflow(event: Event<RunFailed>) {6 tracing::error!(run = %event.run_id, error = %event.error, "A workflow run failed");7}1use laravel::event::{Event, listener};2use laravel::workflow::events::RunFailed;34#[listener]5pub async fn log_failed_workflow(event: Event<RunFailed>) {6 tracing::error!(run = %event.run_id, error = %event.error, "A workflow run failed");7}
Each time a run advances, Laravel creates a tracing 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.
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:
1use std::collections::BTreeMap;2use std::time::Duration;34use laravel::time::Timestamp;5use laravel::workflow::RunId;6use laravel::workflow::store::{7 Claim, Created, Delivery, Entry, Filter, Lease, NewRun, Outcome, RunRecord, Store, Waited,8};910#[derive(Debug)]11pub struct DynamoSettings {12 pub table: String,13}1415pub struct DynamoStore {16 table: String,17 // DynamoDB client...18}1920impl DynamoStore {21 pub async fn connect(table: &str) -> laravel::Result<Self> {22 Ok(Self { table: table.to_owned() })23 }24}2526impl Store for DynamoStore {27 async fn create(&self, run: NewRun) -> laravel::Result<Created> {28 // Save the run and claim `run.tokens` unless unique or token conflicts...29 Ok(Created::Saved)30 }3132 async fn claim(&self, id: RunId, lease: Duration) -> laravel::Result<Claim> {33 // Acquire the lease with a fresh `Lease` token and return the run...34 Ok(Claim::Ended)35 }3637 async fn record(38 &self,39 id: RunId,40 lease: &Lease,41 entry: Entry,42 ) -> laravel::Result<bool> {43 // Upsert the step, sleep, or wait entry while `lease` is active...44 Ok(true)45 }4647 async fn wait(48 &self,49 id: RunId,50 lease: &Lease,51 token: &str,52 number: u32,53 ) -> laravel::Result<Waited> {54 // Claim `token`, register the wait, or return a value while `lease` is active...55 Ok(Waited::Waiting)56 }5758 async fn stop_waiting(59 &self,60 id: RunId,61 lease: &Lease,62 token: &str,63 ) -> laravel::Result<bool> {64 // Clear the run's wait on `token` after a timeout while `lease` is active...65 Ok(true)66 }6768 async fn resume(&self, token: &str, value: String) -> laravel::Result<Delivery> {69 // Append `value` to the token owner's queue, or discard if unowned...70 Ok(Delivery::NotFound)71 }7273 async fn waiting(&self, token: &str) -> laravel::Result<Option<RunId>> {74 // Return the ID of the run currently waiting on `token`...75 Ok(None)76 }7778 async fn set_attributes(79 &self,80 id: RunId,81 lease: &Lease,82 attributes: BTreeMap<String, String>,83 ) -> laravel::Result<bool> {84 // Replace the run's stored attributes while `lease` is active...85 Ok(true)86 }8788 async fn renew(89 &self,90 id: RunId,91 lease: &Lease,92 duration: Duration,93 ) -> laravel::Result<bool> {94 // Extend the run's lease while `lease` is active...95 Ok(true)96 }9798 async fn release(99 &self,100 id: RunId,101 lease: &Lease,102 outcome: Outcome,103 now: Timestamp,104 ) -> laravel::Result<bool> {105 // Apply `outcome`, clear the lease, and free tokens while `lease` is active...106 Ok(true)107 }108109 async fn find(&self, id: RunId) -> laravel::Result<Option<RunRecord>> {110 // Load a run record by ID...111 Ok(None)112 }113114 async fn entries(&self, id: RunId) -> laravel::Result<Vec<Entry>> {115 // Load all recorded entries for the run in order...116 Ok(Vec::new())117 }118119 async fn list(&self, filter: Filter) -> laravel::Result<Vec<RunRecord>> {120 // Query runs matching `filter`, newest first...121 Ok(Vec::new())122 }123124 async fn cancel(125 &self,126 id: RunId,127 reason: Option<String>,128 now: Timestamp,129 ) -> laravel::Result<bool> {130 // Cancel the run via `RunRecord::cancel` and release its keys...131 Ok(false)132 }133134 async fn retry(&self, id: RunId, now: Timestamp) -> laravel::Result<bool> {135 // Reset a failed run to pending at `now` and clear failed entries...136 Ok(false)137 }138139 async fn overdue(&self, now: Timestamp) -> laravel::Result<Vec<RunRecord>> {140 // Return runs with an expired `wake_at`, lease, or ready wait...141 Ok(Vec::new())142 }143144 async fn prune(&self, before: Timestamp) -> laravel::Result<u64> {145 // Delete runs finished before `before` with their entries and values...146 Ok(0)147 }148}1use std::collections::BTreeMap;2use std::time::Duration;34use laravel::time::Timestamp;5use laravel::workflow::RunId;6use laravel::workflow::store::{7 Claim, Created, Delivery, Entry, Filter, Lease, NewRun, Outcome, RunRecord, Store, Waited,8};910#[derive(Debug)]11pub struct DynamoSettings {12 pub table: String,13}1415pub struct DynamoStore {16 table: String,17 // DynamoDB client...18}1920impl DynamoStore {21 pub async fn connect(table: &str) -> laravel::Result<Self> {22 Ok(Self { table: table.to_owned() })23 }24}2526impl Store for DynamoStore {27 async fn create(&self, run: NewRun) -> laravel::Result<Created> {28 // Save the run and claim `run.tokens` unless unique or token conflicts...29 Ok(Created::Saved)30 }3132 async fn claim(&self, id: RunId, lease: Duration) -> laravel::Result<Claim> {33 // Acquire the lease with a fresh `Lease` token and return the run...34 Ok(Claim::Ended)35 }3637 async fn record(38 &self,39 id: RunId,40 lease: &Lease,41 entry: Entry,42 ) -> laravel::Result<bool> {43 // Upsert the step, sleep, or wait entry while `lease` is active...44 Ok(true)45 }4647 async fn wait(48 &self,49 id: RunId,50 lease: &Lease,51 token: &str,52 number: u32,53 ) -> laravel::Result<Waited> {54 // Claim `token`, register the wait, or return a value while `lease` is active...55 Ok(Waited::Waiting)56 }5758 async fn stop_waiting(59 &self,60 id: RunId,61 lease: &Lease,62 token: &str,63 ) -> laravel::Result<bool> {64 // Clear the run's wait on `token` after a timeout while `lease` is active...65 Ok(true)66 }6768 async fn resume(&self, token: &str, value: String) -> laravel::Result<Delivery> {69 // Append `value` to the token owner's queue, or discard if unowned...70 Ok(Delivery::NotFound)71 }7273 async fn waiting(&self, token: &str) -> laravel::Result<Option<RunId>> {74 // Return the ID of the run currently waiting on `token`...75 Ok(None)76 }7778 async fn set_attributes(79 &self,80 id: RunId,81 lease: &Lease,82 attributes: BTreeMap<String, String>,83 ) -> laravel::Result<bool> {84 // Replace the run's stored attributes while `lease` is active...85 Ok(true)86 }8788 async fn renew(89 &self,90 id: RunId,91 lease: &Lease,92 duration: Duration,93 ) -> laravel::Result<bool> {94 // Extend the run's lease while `lease` is active...95 Ok(true)96 }9798 async fn release(99 &self,100 id: RunId,101 lease: &Lease,102 outcome: Outcome,103 now: Timestamp,104 ) -> laravel::Result<bool> {105 // Apply `outcome`, clear the lease, and free tokens while `lease` is active...106 Ok(true)107 }108109 async fn find(&self, id: RunId) -> laravel::Result<Option<RunRecord>> {110 // Load a run record by ID...111 Ok(None)112 }113114 async fn entries(&self, id: RunId) -> laravel::Result<Vec<Entry>> {115 // Load all recorded entries for the run in order...116 Ok(Vec::new())117 }118119 async fn list(&self, filter: Filter) -> laravel::Result<Vec<RunRecord>> {120 // Query runs matching `filter`, newest first...121 Ok(Vec::new())122 }123124 async fn cancel(125 &self,126 id: RunId,127 reason: Option<String>,128 now: Timestamp,129 ) -> laravel::Result<bool> {130 // Cancel the run via `RunRecord::cancel` and release its keys...131 Ok(false)132 }133134 async fn retry(&self, id: RunId, now: Timestamp) -> laravel::Result<bool> {135 // Reset a failed run to pending at `now` and clear failed entries...136 Ok(false)137 }138139 async fn overdue(&self, now: Timestamp) -> laravel::Result<Vec<RunRecord>> {140 // Return runs with an expired `wake_at`, lease, or ready wait...141 Ok(Vec::new())142 }143144 async fn prune(&self, before: Timestamp) -> laravel::Result<u64> {145 // Delete runs finished before `before` with their entries and values...146 Ok(0)147 }148}
Register the store driver by name in src/app.rs or a package service provider:
1use laravel::container::Registrar;2use laravel::foundation::ServiceProvider;34impl ServiceProvider for DynamoWorkflowServiceProvider {5 fn register(&self, app: &mut Registrar) {6 app.workflow().extend("dynamodb", async |_app, definition| {7 let settings = definition.settings::<DynamoSettings>()?;89 DynamoStore::connect(&settings.table).await10 });11 }12}1use laravel::container::Registrar;2use laravel::foundation::ServiceProvider;34impl ServiceProvider for DynamoWorkflowServiceProvider {5 fn register(&self, app: &mut Registrar) {6 app.workflow().extend("dynamodb", async |_app, definition| {7 let settings = definition.settings::<DynamoSettings>()?;89 DynamoStore::connect(&settings.table).await10 });11 }12}
Then configure a store using that driver and select it with WORKFLOW_STORE=dynamodb:
1// src/config/workflow.rs2use laravel::config::workflow::{StoreConfig, Workflow};3use laravel::config::{self, Env};45#[config::section]6fn workflow(env: &Env) -> Workflow {7 let mut workflow = Workflow::from_env(env);89 workflow.add_store(10 "dynamodb",11 StoreConfig::custom("dynamodb").settings(DynamoSettings { table: "workflows".into() }),12 );1314 workflow15}1// src/config/workflow.rs2use laravel::config::workflow::{StoreConfig, Workflow};3use laravel::config::{self, Env};45#[config::section]6fn workflow(env: &Env) -> Workflow {7 let mut workflow = Workflow::from_env(env);89 workflow.add_store(10 "dynamodb",11 StoreConfig::custom("dynamodb").settings(DynamoSettings { table: "workflows".into() }),12 );1314 workflow15}
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.
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:
1use laravel::testing::prelude::*;2use laravel::workflow;34#[laravel::test]5async fn registering_starts_onboarding(app: Application) {6 let workflows = workflow::fake();78 app.post("/register")10 .await11 .assert_redirect();1213 workflows.assert_started::<OnboardUser>();14 workflows.assert_started_where::<OnboardUser>(|run| run.user_id == 1);15}1use laravel::testing::prelude::*;2use laravel::workflow;34#[laravel::test]5async fn registering_starts_onboarding(app: Application) {6 let workflows = workflow::fake();78 app.post("/register")10 .await11 .assert_redirect();1213 workflows.assert_started::<OnboardUser>();14 workflows.assert_started_where::<OnboardUser>(|run| run.user_id == 1);15}
The fake also provides assert_started_times::<T>(count) and assert_nothing_started(), remaining active until its handle is dropped.
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:
1use laravel::mail;2use laravel::testing::prelude::*;34#[laravel::test]5async fn onboarding_sends_tips_when_user_has_no_projects(6 app: Application,7) -> laravel::Result<()> {8 let mail = mail::fake();9 let user = User::factory().create().await?;1011 let run = app.workflow(OnboardUser { user_id: user.id }).await;1213 mail.assert_sent::<Welcome>();14 run.assert_sleeping();1516 app.travel(3.days());17 run.advance().await;1819 mail.assert_sent::<GettingStartedTips>();20 run.assert_completed();2122 Ok(())23}1use laravel::mail;2use laravel::testing::prelude::*;34#[laravel::test]5async fn onboarding_sends_tips_when_user_has_no_projects(6 app: Application,7) -> laravel::Result<()> {8 let mail = mail::fake();9 let user = User::factory().create().await?;1011 let run = app.workflow(OnboardUser { user_id: user.id }).await;1213 mail.assert_sent::<Welcome>();14 run.assert_sleeping();1516 app.travel(3.days());17 run.advance().await;1819 mail.assert_sent::<GettingStartedTips>();20 run.assert_completed();2122 Ok(())23}
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:
1let run = app2 .workflow(Checkout { order_id: 1 })3 .with_step("charge card", Receipt { id: "re_1".into() })4 .await;1let run = app2 .workflow(Checkout { order_id: 1 })3 .with_step("charge card", Receipt { id: "re_1".into() })4 .await;
Stubbed steps record as completed with zero attempts, so run.assert_step_tries("charge card", 0) verifies the stub was used.
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>:
1use laravel::testing::prelude::*;23use crate::workflows::approve_expense::{ApproveExpense, Decision, decision};45#[laravel::test]6async fn approved_expenses_are_paid_out(app: Application) -> laravel::Result<()> {7 let token = decision(42);89 let run = app.workflow(ApproveExpense { expense_id: 42 }).await;1011 run.assert_waiting_for(&token);1213 run.resume(token, Decision::Approved)14 .await15 .assert_step_ran("pay out")16 .assert_completed();1718 Ok(())19}1use laravel::testing::prelude::*;23use crate::workflows::approve_expense::{ApproveExpense, Decision, decision};45#[laravel::test]6async fn approved_expenses_are_paid_out(app: Application) -> laravel::Result<()> {7 let token = decision(42);89 let run = app.workflow(ApproveExpense { expense_id: 42 }).await;1011 run.assert_waiting_for(&token);1213 run.resume(token, Decision::Approved)14 .await15 .assert_step_ran("pay out")16 .assert_completed();1718 Ok(())19}
For inboxes, call run.resume once for each incoming message in order:
1use crate::workflows::approve_large_expense::{ApproveLargeExpense, Outcome, Vote};23let token = "expenses.42.votes";4let run = app.workflow(ApproveLargeExpense { expense_id: 42 }).await;56run.assert_waiting_for(token);78run.resume(token, Vote { approver_id: 1, approve: true })9 .await10 .assert_waiting_for(token);1112run.resume(token, Vote { approver_id: 2, approve: true })13 .await14 .assert_completed_with(Outcome::Approved);1use crate::workflows::approve_large_expense::{ApproveLargeExpense, Outcome, Vote};23let token = "expenses.42.votes";4let run = app.workflow(ApproveLargeExpense { expense_id: 42 }).await;56run.assert_waiting_for(token);78run.resume(token, Vote { approver_id: 1, approve: true })9 .await10 .assert_waiting_for(token);1112run.resume(token, Vote { approver_id: 2, approve: true })13 .await14 .assert_completed_with(Outcome::Approved);
To test an early resume arriving before the run reaches wait_for, claim the token when starting the test run:
1let run = app2 .workflow(ChargeOrder { order_id: 42 })3 .claim("orders.42.charged")4 .await;1let run = app2 .workflow(ChargeOrder { order_id: 42 })3 .claim("orders.42.charged")4 .await;
To test a wait's .timeout(..) branch, travel past the timeout and call run.advance() without resuming:
1let run = app.workflow(ApproveExpense { expense_id: 42 }).await;23app.travel(4.days());4run.advance().await.assert_completed();1let run = app.workflow(ApproveExpense { expense_id: 42 }).await;23app.travel(4.days());4run.advance().await.assert_completed();