use std::collections::HashSet;
use std::sync::atomic::{AtomicU32, Ordering};
use laravel::Application;
use laravel::container::Inject;
use laravel::event;
use laravel::prelude::{Json, Params, StatusCode};
use laravel::queue::Queueable;
use laravel::task;
use laravel::testing::{MakesConsoleRequests, MakesHttpRequests, RunsWorkflows};
use laravel::time::ToSpan;
use laravel::workflow::events::{RunCancelled, RunCompleted, RunFailed};
use laravel::workflow::{self, Resume, Run, StepFailed, workflow};
use serde::{Deserialize, Serialize};
use crate::queue::Records;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Subscribed {
plan: String,
}
#[derive(Queueable)]
struct Onboard {
user_id: i64,
}
#[workflow(name = "users.onboard", queue = "workflows")]
impl Onboard {
async fn handle(self, run: &Run, records: Inject<Records>) -> laravel::Result<String> {
let tenant = || laravel::context::get::<String>("tenant").unwrap_or_default();
run.step("send welcome", async {
records.push(format!("welcome {} for {:?}", self.user_id, tenant()));
Ok(())
})
.await?;
run.sleep(3.days()).await?;
let (projects, teammates) = task::try_join!(
run.step("count projects", async {
records.push("count projects");
Ok::<_, laravel::Error>(0)
}),
run.step("count teammates", async {
records.push("count teammates");
Ok::<_, laravel::Error>(0)
}),
)?;
if projects + teammates == 0 {
run.step("send tips", async {
records.push(format!("tips for {:?}", tenant()));
Ok(())
})
.await?;
}
let subscribed = run
.wait_for::<Subscribed>(format!("users.{}.subscribed", self.user_id))
.timeout(11.days())
.await?;
match subscribed {
Some(subscribed) => Ok(subscribed.plan),
None => {
run.step("end trial", async {
records.push("end trial");
Ok(())
})
.await?;
Ok("free".into())
}
}
}
}
fn app() -> Application {
Application::configure()
.for_testing(env!("CARGO_MANIFEST_DIR"))
.with_services(|services| {
services.instance(Records::default());
services.instance(Tries::default());
})
.with_routing(|routing, _| {
routing.routes(|route| {
route.get("/expenses/{expense}/decided", decided);
route.post("/scans", scanned);
});
})
.create()
}
async fn records(app: &Application) -> Vec<String> {
app.resolve::<Records>().await.all()
}
#[tokio::test]
async fn a_run_records_each_step_once_and_suspends_for_sleeps_and_waits() {
let app = app();
let run = app.workflow(Onboard { user_id: 7 }).await;
run.assert_step_ran("send welcome").assert_sleeping();
run.advance().await;
run.assert_sleeping();
app.travel(3.days());
run.advance().await;
run.assert_waiting_for("users.7.subscribed")
.assert_step_ran("count projects")
.assert_step_ran("send tips");
app.travel(10.days());
run.advance().await;
run.assert_waiting_for("users.7.subscribed");
app.travel(1.days());
run.advance().await;
run.assert_completed_with("free").assert_step_ran("end trial");
let info = run.info().unwrap();
let wait = info
.steps()
.iter()
.find(|step| step.name() == "users.7.subscribed")
.unwrap();
assert!(wait.timed_out());
assert_eq!(
records(&app).await,
[
"welcome 7 for \"\"",
"count projects",
"count teammates",
"tips for \"\"",
"end trial"
],
"each step ran once over five advances"
);
}
#[tokio::test]
async fn a_resume_gives_the_wait_its_value() {
let app = app();
let run = app.workflow(Onboard { user_id: 8 }).await;
app.travel(3.days());
run.advance().await;
run.resume("users.8.subscribed", Subscribed { plan: "pro".into() })
.await;
let resumed = app
.scope(async || workflow::resume("users.8.subscribed", Subscribed { plan: "late".into() }).await)
.await
.unwrap();
assert_eq!(
resumed,
workflow::Resumed::NotFound,
"a run that finished gives up its token"
);
run.assert_completed_with("pro").assert_step_not_ran("end trial");
}
#[tokio::test]
async fn a_started_run_advances_on_the_queue_and_keeps_its_context() {
let app = app();
let id = app
.scope(async || {
laravel::context::add("tenant", "acme");
Onboard { user_id: 9 }.start().await
})
.await
.unwrap();
let info = app.scope(async || workflow::find(id).await).await.unwrap().unwrap();
assert_eq!(
info.status(),
workflow::Status::Waiting,
"the sync connection advanced it"
);
assert_eq!(info.workflow(), "users.onboard");
app.command("workflow:recover")
.await
.assert_successful()
.assert_error_output_contains("No overdue workflow runs found.");
app.travel(3.days());
app.command("workflow:recover")
.await
.assert_successful()
.assert_error_output_contains("1 workflow run woken.");
app.scope(async || workflow::resume("users.9.subscribed", Subscribed { plan: "team".into() }).await)
.await
.unwrap();
let info = app.scope(async || workflow::find(id).await).await.unwrap().unwrap();
assert_eq!(info.status(), workflow::Status::Completed);
assert_eq!(info.output::<String>().unwrap().as_deref(), Some("team"));
let json = serde_json::to_value(&info).unwrap();
assert_eq!(
(&json["status"], &json["output"]),
(&"completed".into(), &"team".into())
);
assert_eq!(
info.steps().iter().map(|step| step.name()).collect::<Vec<_>>(),
[
"send welcome",
"sleep 1",
"count projects",
"count teammates",
"send tips",
"users.9.subscribed"
]
);
assert_eq!(
records(&app).await,
[
"welcome 9 for \"acme\"",
"count projects",
"count teammates",
"tips for \"acme\""
],
"every advance restores the context the run started with"
);
}
#[tokio::test]
async fn a_resume_before_the_wait_finds_no_run_unless_the_start_claims_the_token() {
let app = app();
let unclaimed = app.workflow(Onboard { user_id: 10 }).await;
let resumed = app
.scope(async || workflow::resume("users.10.subscribed", Subscribed { plan: "early".into() }).await)
.await
.unwrap();
assert_eq!(resumed, workflow::Resumed::NotFound);
app.scope(async || workflow::cancel(unclaimed.id()).await)
.await
.unwrap();
let run = app.workflow(Onboard { user_id: 10 }).claim("users.10.subscribed").await;
let resumed = app
.scope(async || workflow::resume("users.10.subscribed", Subscribed { plan: "early".into() }).await)
.await
.unwrap();
assert_eq!(resumed, workflow::Resumed::Delivered);
app.travel(25.hours());
app.command("workflow:prune").await.assert_successful();
app.travel(2.days());
run.advance().await;
run.assert_completed_with("early");
}
#[tokio::test]
async fn a_stale_decision_never_decides_a_later_run_of_the_same_record() {
let app = app();
let token = "expenses.5.decision";
let resume = |value: &'static str| app.scope(async move || workflow::resume(token, value).await);
let first = app.workflow(AwaitCallback { token: token.into() }).await;
let clicks = app
.scope(async || {
let _queue = laravel::queue::fake();
Ok::<_, laravel::Error>((
workflow::resume(token, "approved").await?,
workflow::resume(token, "approved twice").await?,
))
})
.await
.unwrap();
assert_eq!(clicks, (workflow::Resumed::Delivered, workflow::Resumed::Delivered));
first.advance().await.assert_completed_with("approved");
assert_eq!(resume("approved again").await.unwrap(), workflow::Resumed::NotFound);
let second = app.workflow(AwaitCallback { token: token.into() }).await;
second.assert_waiting_for(token);
second.resume(token, "rejected").await.assert_completed_with("rejected");
}
#[tokio::test]
async fn one_unfinished_run_owns_a_token() {
let app = app();
let token = "expenses.6.decision";
let owner = app.workflow(AwaitCallback { token: token.into() }).await;
let rival = app.workflow(AwaitCallback { token: token.into() }).await;
rival.assert_failed_with(&format!("which the unfinished run `{}` owns", owner.id()));
let started = app
.scope(async || AwaitCallback { token: token.into() }.start().claim(token).await)
.await;
let error = started.unwrap_err().to_string();
assert!(
error.contains(&format!("the unfinished run `{}` owns", owner.id())),
"{error}"
);
owner.resume(token, "approved").await.assert_completed_with("approved");
}
#[tokio::test]
async fn concurrent_resumes_all_reach_the_run() {
let app = app();
concurrent_resumes_reach_the_inbox(&app, "expenses.8.votes").await;
}
async fn concurrent_resumes_reach_the_inbox(app: &Application, token: &'static str) {
let run = app
.workflow(CollectAll {
token: token.into(),
count: 8,
})
.await;
run.assert_waiting_for(token);
let resumed = app
.scope(async || futures_util::future::try_join_all((1..=8).map(|vote| workflow::resume(token, vote))).await)
.await
.unwrap();
assert!(resumed.iter().all(|resumed| *resumed == workflow::Resumed::Delivered));
run.advance().await.assert_completed();
let mut votes: Vec<i64> = run.info().unwrap().output().unwrap().unwrap();
votes.sort_unstable();
assert_eq!(votes, (1..=8).collect::<Vec<_>>(), "no value is lost or read twice");
}
#[derive(Queueable)]
struct CollectAll {
token: String,
count: usize,
}
#[workflow(name = "votes.collect")]
impl CollectAll {
async fn handle(self, run: &Run) -> laravel::Result<Vec<i64>> {
let mut inbox = run.inbox_for::<i64>(self.token);
let mut values = Vec::new();
while values.len() < self.count {
values.push(inbox.next().await?);
}
Ok(values)
}
}
#[tokio::test]
async fn recover_wakes_a_resumed_run_whose_wake_up_was_lost() {
let app = app();
let run = app.workflow(Onboard { user_id: 13 }).await;
app.travel(3.days());
run.advance().await;
app.scope(async || {
let _queue = laravel::queue::fake();
workflow::resume("users.13.subscribed", Subscribed { plan: "pro".into() }).await
})
.await
.unwrap();
app.command("workflow:recover")
.await
.assert_error_output_contains("1 workflow run woken.");
let info = app
.scope(async || workflow::find(run.id()).await)
.await
.unwrap()
.unwrap();
assert_eq!(info.output::<String>().unwrap().as_deref(), Some("pro"));
app.command("workflow:recover")
.await
.assert_error_output_contains("No overdue workflow runs found.");
}
#[derive(Queueable)]
struct AwaitCallback {
token: String,
}
#[workflow(name = "callbacks.await")]
impl AwaitCallback {
async fn handle(self, run: &Run) -> laravel::Result<serde_json::Value> {
run.wait_for(self.token).await
}
}
async fn output(app: &Application, id: workflow::RunId) -> Option<serde_json::Value> {
let info = app.scope(async || workflow::find(id).await).await.unwrap().unwrap();
info.output().unwrap()
}
fn path(url: &str) -> &str {
url.strip_prefix("http://localhost").unwrap()
}
async fn decided(Params(expense): Params<i64>, resume: Resume<String>) -> String {
format!("expense {expense} {}: {:?}", resume.value, resume.outcome)
}
#[derive(Deserialize)]
struct Scan {
total: i64,
}
async fn scanned(resume: Resume<Scan>) -> (StatusCode, Json<serde_json::Value>) {
(
StatusCode::OK,
Json(serde_json::json!({ "received": resume.value.total })),
)
}
#[tokio::test]
async fn a_resume_url_resumes_the_wait_with_its_value_on_any_request() {
let app = app();
let token = "expenses/7 decision";
let run = app.workflow(AwaitCallback { token: token.into() }).await;
run.assert_waiting_for(token);
let (url, expiring) = app
.scope(async || {
(
workflow::resume_url(token, "approved").unwrap().to_string(),
workflow::resume_url(token, "approved")
.unwrap()
.expires(1.hours())
.to_string(),
)
})
.await;
app.get(path(&url).replace("approved", "rejected"))
.await
.assert_forbidden();
run.assert_waiting_for(token);
app.get(path(&url)).await.assert_status(202);
assert_eq!(output(&app, run.id()).await, Some("approved".into()));
app.post(path(&expiring)).await.assert_not_found();
app.travel(2.hours());
app.get(path(&expiring)).await.assert_forbidden();
}
#[tokio::test]
async fn a_resume_url_answers_with_the_response_of_the_handler_it_names() {
let app = app();
let run = app
.workflow(AwaitCallback {
token: "expenses.7.decision".into(),
})
.await;
let url = app
.scope(async || {
workflow::resume_url("expenses.7.decision", "approved")
.unwrap()
.respond(decided, 7)
.unwrap()
.to_string()
})
.await;
assert!(
url.starts_with("http://localhost/expenses/7/decided?workflow_token="),
"{url}"
);
app.get(path(&url).replace("approved", "rejected"))
.await
.assert_forbidden();
app.get(path(&url).replace("/7/", "/8/")).await.assert_forbidden();
run.assert_waiting_for("expenses.7.decision");
app.get(path(&url))
.await
.assert_ok()
.assert_see("expense 7 approved: Delivered");
assert_eq!(output(&app, run.id()).await, Some("approved".into()));
app.get(path(&url))
.await
.assert_ok()
.assert_see("expense 7 approved: NotFound");
}
#[tokio::test]
async fn a_webhook_url_resumes_the_wait_with_the_request_body() {
let app = app();
let run = app
.workflow(AwaitCallback {
token: "scans.1".into(),
})
.await;
let (plain, typed) = app
.scope(async || {
(
workflow::webhook_url("scans.1").unwrap().to_string(),
workflow::webhook_url("scans.1")
.unwrap()
.respond(scanned, ())
.unwrap()
.to_string(),
)
})
.await;
app.post(path(&plain)).body("not json").await.assert_status(400);
app.post(path(&typed))
.json(serde_json::json!({ "total": "unknown" }))
.await
.assert_status(400);
run.assert_waiting_for("scans.1");
app.post(path(&typed))
.json(serde_json::json!({ "total": 4200 }))
.await
.assert_ok()
.assert_json(serde_json::json!({ "received": 4200 }));
assert_eq!(output(&app, run.id()).await, Some(serde_json::json!({ "total": 4200 })));
}
#[derive(Queueable)]
struct AskManager {
overlap: bool,
}
#[workflow(name = "approvals.ask")]
impl AskManager {
async fn handle(self, run: &Run, records: Inject<Records>) -> laravel::Result<String> {
if self.overlap {
task::try_join!(run.sleep(1.hours()).named("cooling off"), async {
run.wait::<String>().await
})?;
}
let decision = run.wait::<String>();
let approve = decision.resume_url("approved")?.to_string();
run.step("email the manager", async {
records.push(approve);
Ok(())
})
.await?;
Ok(decision.timeout(3.days()).await?.unwrap_or_else(|| "expired".into()))
}
}
#[tokio::test]
async fn a_wait_without_a_token_gets_the_same_generated_token_on_every_advance() {
let app = app();
let run = app.workflow(AskManager { overlap: false }).await;
let other = app.workflow(AskManager { overlap: false }).await;
let token = format!("{}.1", run.id());
run.assert_waiting_for(&token);
other.assert_waiting_for(format!("{}.1", other.id()));
app.travel(1.days());
run.advance().await;
run.assert_waiting_for(&token).assert_step_tries("email the manager", 1);
let emailed = records(&app).await.remove(0);
app.get(path(&emailed)).await.assert_status(202);
assert_eq!(output(&app, run.id()).await, Some("approved".into()));
other.assert_waiting_for(format!("{}.1", other.id()));
app.workflow(AskManager { overlap: true })
.await
.assert_failed_with("makes a wait without a token while another operation is running");
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Vote {
approver: i64,
approve: bool,
}
#[derive(Queueable)]
struct CollectVotes {
token: Option<String>,
}
#[workflow(name = "expenses.votes")]
impl CollectVotes {
async fn handle(self, run: &Run, records: Inject<Records>) -> laravel::Result<String> {
let mut votes = match self.token {
Some(token) => run.inbox_for::<Vote>(token),
None => run.inbox::<Vote>(),
};
let approve = votes
.resume_url(Vote {
approver: 1,
approve: true,
})?
.to_string();
run.step("email the approvers", async {
records.push(approve);
Ok(())
})
.await?;
let mut approvers = HashSet::new();
while let Some(vote) = votes.next().timeout(5.days()).await? {
if !vote.approve {
return Ok("rejected".into());
}
approvers.insert(vote.approver);
if approvers.len() == 2 {
return Ok("approved".into());
}
}
Ok("expired".into())
}
}
fn vote(approver: i64) -> Vote {
Vote {
approver,
approve: true,
}
}
#[tokio::test]
async fn an_inbox_reads_every_value_in_the_order_it_arrived() {
let app = app();
let token = "expenses.7.votes";
let early = app
.scope(async || workflow::resume(token, vote(2)).await)
.await
.unwrap();
assert_eq!(early, workflow::Resumed::NotFound);
let run = app
.workflow(CollectVotes {
token: Some(token.into()),
})
.await;
run.assert_waiting_for(token);
let emailed = records(&app).await.remove(0);
app.get(path(&emailed)).await.assert_status(202);
app.get(path(&emailed)).await.assert_status(202);
run.advance().await.assert_waiting_for(token);
let resumed = app
.scope(async || workflow::resume(token, vote(2)).await)
.await
.unwrap();
assert_eq!(resumed, workflow::Resumed::Delivered);
run.advance().await.assert_completed_with("approved");
let info = app
.scope(async || workflow::find(run.id()).await)
.await
.unwrap()
.unwrap();
let reads: Vec<&str> = info.steps().iter().skip(1).map(|step| step.name()).collect();
assert_eq!(
reads,
["expenses.7.votes #1", "expenses.7.votes #2", "expenses.7.votes #3"]
);
}
#[tokio::test]
async fn an_inbox_with_a_generated_token_ends_when_no_value_arrives_in_time() {
let app = app();
let run = app.workflow(CollectVotes { token: None }).await;
let token = format!("{}.1", run.id());
run.assert_waiting_for(&token);
let emailed = records(&app).await.remove(0);
app.post(path(&emailed)).await.assert_status(202);
run.advance().await.assert_waiting_for(&token);
app.travel(121.hours());
run.advance().await;
run.assert_completed_with("expired");
assert_eq!(
records(&app).await.len(),
1,
"the approvers are emailed once over every advance"
);
}
#[derive(Queueable)]
struct ReadsForever;
#[workflow]
impl ReadsForever {
async fn handle(self, run: &Run) -> laravel::Result<()> {
let mut messages = run.inbox_for::<String>("chat");
loop {
messages.next().timeout(0.seconds()).await?;
}
}
}
#[tokio::test]
async fn reading_an_inbox_more_than_a_thousand_times_fails_the_run() {
let app = app();
app.workflow(ReadsForever)
.await
.assert_failed_with("reads the inbox `chat` more than 1000 times");
}
#[derive(Default)]
struct Tries(AtomicU32);
#[derive(Queueable)]
struct Flaky {
succeed_on: u32,
}
#[workflow]
impl Flaky {
async fn handle(self, run: &Run, tries: Inject<Tries>) -> laravel::Result<u32> {
run.step("call the api", async {
let attempt = tries.0.fetch_add(1, Ordering::SeqCst) + 1;
match attempt {
1 => Err(laravel::abort_with(503, "the api is down")),
2 => panic!("the client crashed"),
attempt if attempt < self.succeed_on => Err(laravel::abort_with(503, "still down")),
attempt => Ok(attempt),
}
})
.backoff([1.minutes(), 5.minutes()])
.await
}
}
#[tokio::test]
async fn a_failed_step_is_tried_again_after_its_backoff() {
let app = app();
let run = app.workflow(Flaky { succeed_on: 3 }).await;
run.assert_step_tries("call the api", 1).assert_retrying("call the api");
run.advance().await;
run.assert_step_tries("call the api", 1);
app.travel(1.minutes());
run.advance().await;
run.assert_step_tries("call the api", 2);
app.travel(4.minutes());
run.advance().await;
run.assert_step_tries("call the api", 2);
app.travel(1.minutes());
run.advance().await;
run.assert_completed_with(3).assert_step_tries("call the api", 3);
}
#[tokio::test]
async fn a_step_out_of_tries_fails_the_run() {
let app = app();
let run = app.workflow(Flaky { succeed_on: 10 }).await;
for _ in 0..2 {
app.travel(5.minutes());
run.advance().await;
}
run.assert_failed_with("the step `call the api` failed: still down")
.assert_step_tries("call the api", 3);
}
#[derive(Queueable)]
struct RateLimited;
#[workflow]
impl RateLimited {
async fn handle(self, run: &Run, tries: Inject<Tries>) -> laravel::Result<u32> {
run.step("sync contacts", async {
match tries.0.fetch_add(1, Ordering::SeqCst) + 1 {
1 => Err(workflow::retry_after(2.hours(), laravel::abort_with(429, "slow down"))),
attempt => Ok(attempt),
}
})
.await
}
}
#[tokio::test]
async fn a_step_may_choose_when_it_is_tried_again() {
let app = app();
let run = app.workflow(RateLimited).await;
run.assert_retrying("sync contacts");
app.travel(1.hours());
run.advance().await;
run.assert_step_tries("sync contacts", 1);
app.travel(1.hours());
run.advance().await;
run.assert_completed_with(2).assert_step_tries("sync contacts", 2);
}
#[derive(Queueable)]
struct BookTrip {
trip_id: i64,
}
#[workflow]
impl BookTrip {
async fn handle(self, run: &Run, records: Inject<Records>) -> laravel::Result<()> {
let flight = run
.step("book flight", async {
records.push("book flight");
Ok(format!("flight {}", self.trip_id))
})
.await?;
if let Err(error) = run
.step("book hotel", async {
records.push("book hotel");
if records.all().iter().any(|record| record == "rooms available") {
return Ok(());
}
Err(workflow::fatal(laravel::abort_with(409, "no rooms")))
})
.await
{
assert!(error.is::<StepFailed>());
run.step("cancel flight", async {
records.push(format!("cancel {flight}"));
Ok(())
})
.await?;
return Err(error);
}
Ok(())
}
async fn failed(self, error: &laravel::Error, records: Inject<Records>) {
records.push(format!("failed {}: {error}", self.trip_id));
}
}
#[tokio::test]
async fn a_fatal_step_fails_without_another_try_and_compensation_is_an_err_arm() {
let app = app();
let events = app.scope(async || event::fake()).await;
let run = app.workflow(BookTrip { trip_id: 1 }).await;
run.assert_failed_with("the step `book hotel` failed: no rooms")
.assert_step_tries("book hotel", 1)
.assert_step_ran("cancel flight");
assert_eq!(
records(&app).await,
[
"book flight",
"book hotel",
"cancel flight 1",
"failed 1: the step `book hotel` failed: no rooms"
]
);
events
.assert_dispatched_where::<RunFailed>(|event| event.run_id == run.id() && event.error.is::<StepFailed>())
.assert_dispatched_times::<RunCompleted>(0);
}
#[tokio::test]
async fn a_test_may_replace_a_step_with_its_output() {
let app = app();
let run = app.workflow(BookTrip { trip_id: 2 }).with_step("book hotel", ()).await;
run.assert_completed().assert_step_tries("book hotel", 0);
assert_eq!(records(&app).await, ["book flight"]);
}
#[tokio::test]
async fn commands_list_show_retry_and_prune_runs() {
let app = app();
let run = app.workflow(BookTrip { trip_id: 3 }).await;
run.assert_failed();
let id = run.id();
app.command("workflow:list --status=failed")
.await
.assert_successful()
.assert_output_contains(&id.to_string());
app.command("workflow:list --status=completed")
.await
.assert_error_output_contains("No workflow runs found.");
app.command(&format!("workflow:show {id}"))
.await
.assert_successful()
.assert_output_contains("book hotel")
.assert_output_contains("no rooms");
app.command("workflow:show nope")
.await
.assert_exit_code(1)
.assert_error_output_contains("no workflow run has the ID `nope`");
app.resolve::<Records>().await.push("rooms available");
app.command(&format!("workflow:retry nope {id}"))
.await
.assert_exit_code(1)
.assert_error_output_contains("no workflow run has the ID `nope`")
.assert_error_output_contains(&format!("Workflow run `{id}` retried."));
let info = app.scope(async || workflow::find(id).await).await.unwrap().unwrap();
assert_eq!(info.status(), workflow::Status::Completed);
assert_eq!(
records(&app)
.await
.iter()
.filter(|record| *record == "book flight")
.count(),
1,
"the recorded step didn't run again"
);
app.command(&format!("workflow:retry {id}"))
.await
.assert_exit_code(1)
.assert_error_output_contains(&format!("workflow run `{id}` hasn't failed"));
app.command("workflow:prune")
.await
.assert_error_output_contains("No finished workflow runs found.");
app.travel(25.hours());
app.command("workflow:prune")
.await
.assert_error_output_contains("1 workflow run deleted.");
let stale = app
.scope(async || workflow::resume("trips.3.stale", true).await)
.await
.unwrap();
assert_eq!(stale, workflow::Resumed::NotFound);
assert!(app.scope(async || workflow::find(id).await).await.unwrap().is_none());
}
#[tokio::test]
async fn a_cancelled_run_doesnt_advance_again() {
let app = app();
let run = app.workflow(Onboard { user_id: 11 }).await;
let events = app.scope(async || event::fake()).await;
app.command(&format!("workflow:cancel {}", run.id()))
.await
.assert_successful();
events
.assert_dispatched_where::<RunCancelled>(|event| event.run_id == run.id() && event.workflow == "users.onboard");
app.travel(3.days());
run.advance().await;
let info = run.info().unwrap();
assert_eq!(info.status(), workflow::Status::Cancelled);
assert!(!app.scope(async || workflow::cancel(run.id()).await).await.unwrap());
}
#[derive(Queueable)]
struct PanicsAfterStep;
#[workflow]
impl PanicsAfterStep {
async fn handle(self, run: &Run) -> laravel::Result<()> {
run.step("first", async { Ok(()) }).await?;
panic!("unexpected workflow state");
}
}
#[tokio::test]
async fn a_panic_between_steps_fails_the_run() {
app()
.workflow(PanicsAfterStep)
.await
.assert_failed_with("unexpected workflow state");
}
#[derive(Queueable)]
struct ReadsOutsideAStep;
#[workflow]
impl ReadsOutsideAStep {
async fn handle(self, run: &Run) -> laravel::Result<()> {
run.step("first", async { Ok(()) }).await?;
task::sleep(1.milliseconds()).await;
run.step("second", async { Ok(()) }).await
}
}
#[derive(Queueable)]
struct ReusesAName;
#[workflow]
impl ReusesAName {
async fn handle(self, run: &Run) -> laravel::Result<()> {
run.step("send", async { Ok(()) }).await?;
run.step("send", async { Ok(()) }).await
}
}
#[derive(Queueable)]
struct SleepsTogether {
named: bool,
}
#[workflow]
impl SleepsTogether {
async fn handle(self, run: &Run) -> laravel::Result<()> {
if self.named {
task::try_join!(
run.sleep(1.hours()).named("cooling off"),
run.sleep(2.hours()).named("settling")
)?;
} else {
task::try_join!(run.sleep(1.hours()), run.sleep(2.hours()))?;
}
Ok(())
}
}
#[tokio::test]
async fn the_runtime_checks_the_determinism_rules() {
let app = app();
app.workflow(ReadsOutsideAStep)
.await
.assert_failed_with("awaited something outside a step after the step `first`");
app.workflow(ReusesAName)
.await
.assert_failed_with("the step `send` runs twice: give each step its own name");
app.workflow(SleepsTogether { named: false })
.await
.assert_failed_with("has a sleep that overlaps another operation: name it");
let run = app.workflow(SleepsTogether { named: true }).await;
run.assert_sleeping();
app.travel(1.hours());
run.advance().await;
run.assert_sleeping();
app.travel(1.hours());
run.advance().await;
run.assert_completed();
}
#[tokio::test]
async fn fakes_record_starts() {
let app = app();
app.scope(async || {
let workflows = workflow::fake();
Onboard { user_id: 12 }.start().await?;
workflows
.assert_started::<Onboard>()
.assert_started_times::<Onboard>(1)
.assert_started_where::<Onboard>(|run| run.user_id == 12)
.assert_started_times::<BookTrip>(0);
Ok::<_, laravel::Error>(())
})
.await
.unwrap();
assert!(records(&app).await.is_empty(), "the fake didn't run the workflow");
}
#[derive(Queueable)]
struct Charge {
order_id: i64,
}
#[workflow(name = "orders.charge")]
impl Charge {
async fn handle(self, run: &Run, records: Inject<Records>) -> laravel::Result<String> {
run.set_attribute("phase", "charging");
let receipt = run
.step("charge card", async {
let step = workflow::current_step();
records.push(format!("{} try {}", step.key(), step.attempt()));
Ok(format!("receipt {}", self.order_id))
})
.await?;
run.set_attribute("phase", "shipping");
let shipped = run.wait_for(shipped(self.order_id)).await?;
Ok(format!("{receipt} via {}", shipped.carrier))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Shipped {
carrier: String,
}
fn shipped(order_id: i64) -> workflow::Token<Shipped> {
workflow::Token::new(format!("orders.{order_id}.shipped"))
}
async fn start_charge(app: &Application, order_id: i64) -> workflow::Started {
app.scope(async move || {
Charge { order_id }
.start()
.attribute("tenant", "acme")
.unique(format!("orders.{order_id}"))
.await
})
.await
.unwrap()
}
#[tokio::test]
async fn a_unique_start_starts_one_run_per_key_until_it_finishes() {
let app = app();
let workflow::Started::New(first) = start_charge(&app, 1).await else {
panic!("the first start saves a run");
};
assert_eq!(start_charge(&app, 1).await, workflow::Started::Existing(first));
assert!(matches!(start_charge(&app, 2).await, workflow::Started::New(_)));
let waiting = app
.scope(async || workflow::waiting_for(shipped(1)).await)
.await
.unwrap()
.unwrap();
assert_eq!(waiting.id(), first);
assert_eq!(
waiting.attributes().iter().collect::<Vec<_>>(),
[
(&"phase".to_owned(), &"shipping".to_owned()),
(&"tenant".to_owned(), &"acme".to_owned())
]
);
assert_eq!(records(&app).await[0], format!("{first}:charge card try 1"));
app.scope(async || workflow::resume(shipped(1), Shipped { carrier: "ups".into() }).await)
.await
.unwrap();
let info = app.scope(async || workflow::find(first).await).await.unwrap().unwrap();
assert_eq!(info.output::<String>().unwrap().as_deref(), Some("receipt 1 via ups"));
assert!(
app.scope(async || workflow::waiting_for(shipped(1)).await)
.await
.unwrap()
.is_none()
);
assert!(
matches!(start_charge(&app, 1).await, workflow::Started::New(id) if id != first),
"a finished run gives up its key"
);
}
#[tokio::test]
async fn commands_filter_by_attribute_print_json_and_cancel_in_bulk_with_a_reason() {
let app = app();
let workflow::Started::New(acme) = start_charge(&app, 3).await else {
panic!("the start saves a run");
};
let other = app
.scope(async || Charge { order_id: 4 }.start().attribute("tenant", "globex").await)
.await
.unwrap();
let listed = app.command("workflow:list --attribute tenant=acme --json").await;
listed.assert_successful();
let runs: serde_json::Value = serde_json::from_str(listed.output().trim()).unwrap();
assert_eq!(runs.as_array().unwrap().len(), 1);
assert_eq!(runs[0]["id"], acme.to_string());
assert_eq!(runs[0]["status"], "waiting");
assert_eq!(runs[0]["attributes"]["phase"], "shipping");
let shown = app.command(&format!("workflow:show {acme} --json")).await;
let run: serde_json::Value = serde_json::from_str(shown.output().trim()).unwrap();
assert_eq!(run["steps"][0]["name"], "charge card");
assert_eq!(run["attributes"]["tenant"], "acme");
app.command("workflow:cancel")
.await
.assert_exit_code(2)
.assert_error_output_contains("give the IDs of the runs to cancel")
.assert_error_output_contains("Usage: ")
.assert_error_output_contains("workflow:cancel [OPTIONS] [IDS]...");
app.command("workflow:cancel --status=completed")
.await
.assert_exit_code(2)
.assert_error_output_contains("can't be cancelled");
app.command(&format!("workflow:cancel {acme} --name=orders"))
.await
.assert_exit_code(2)
.assert_error_output_contains("give either the IDs of the runs to cancel or filters, not both");
app.command("workflow:cancel --attribute tenant=acme")
.expects_confirmation("Cancel 1 workflow run?", false)
.await
.assert_exit_code(1)
.assert_error_output_contains("Command cancelled.");
let events = app.scope(async || event::fake()).await;
app.command("workflow:cancel --attribute tenant=acme --reason=refunded")
.expects_confirmation("Cancel 1 workflow run?", true)
.await
.assert_successful()
.assert_error_output_contains(&format!("Workflow run `{acme}` cancelled."));
events.assert_dispatched_where::<RunCancelled>(|event| {
event.run_id == acme && event.reason.as_deref() == Some("refunded")
});
app.command(&format!("workflow:show {acme}"))
.await
.assert_output_contains("Reason refunded");
app.command(&format!("workflow:cancel {acme}"))
.await
.assert_exit_code(1)
.assert_error_output_contains(&format!("workflow run `{acme}` has already ended"));
let info = app.scope(async || workflow::find(other).await).await.unwrap().unwrap();
assert_eq!(
info.status(),
workflow::Status::Waiting,
"the filter left the other tenant's run"
);
app.scope(async || workflow::cancel(other).reason("duplicate").await)
.await
.unwrap();
let info = app.scope(async || workflow::find(other).await).await.unwrap().unwrap();
assert_eq!(
(info.status(), info.error()),
(workflow::Status::Cancelled, Some("duplicate"))
);
}
#[derive(Queueable)]
struct ReadBankDetails;
#[workflow]
impl ReadBankDetails {
async fn handle(self, run: &Run) -> laravel::Result<String> {
run.step("read iban", async { Ok("DE89 3704".to_owned()) }).await
}
}
#[tokio::test]
async fn a_purged_run_keeps_its_outline_and_loses_its_data() {
let app = app();
let id = app
.scope(async || ReadBankDetails.start().purge_when_finished().await)
.await
.unwrap();
let info = app.scope(async || workflow::find(id).await).await.unwrap().unwrap();
assert_eq!(info.status(), workflow::Status::Completed);
assert!(info.purged());
assert_eq!(info.output::<String>().unwrap(), None);
assert_eq!(info.steps()[0].name(), "read iban");
let shown = app.command(&format!("workflow:show {id}")).await;
shown.assert_output_contains("<data deleted>");
assert!(!shown.output().contains("DE89"), "{}", shown.output());
}
#[cfg(feature = "database-sqlite")]
mod database {
use laravel::Application;
use laravel::config::database::ConnectionConfig as DatabaseConnection;
use laravel::config::queue::DatabaseQueue;
use laravel::db::{self, AnyConnection};
use laravel::testing::{MakesConsoleRequests, RunsWorkflows};
use laravel::time::ToSpan;
use laravel::workflow;
use super::{AwaitCallback, BookTrip, CollectVotes, Onboard, ReadBankDetails, Subscribed, Vote, start_charge};
use crate::queue::Records;
use crate::queue::database::{create_failed_table, create_table};
mod schema {
laravel::workflow::tables!();
}
pub(crate) async fn migrate(connection: &AnyConnection) -> laravel::Result<()> {
for table in [
"workflow_attributes",
"workflow_resumes",
"workflow_waits",
"workflow_steps",
"workflow_runs",
] {
connection.schema().drop_if_exists(table).await?;
}
connection.transaction(schema::migrate).await
}
async fn application(url: String) -> Application {
let app = Application::configure()
.for_testing(env!("CARGO_MANIFEST_DIR"))
.with_env("WORKFLOW_STORE", "database")
.with_config(move |config, _| {
config.database.default = "primary".into();
config
.database
.connections
.insert("primary".into(), DatabaseConnection::new(url));
})
.with_services(|services| {
services.instance(Records::default());
})
.create();
app.scope(async || migrate(&db::default_connection()?).await)
.await
.unwrap();
app
}
#[tokio::test]
async fn the_worker_shows_each_advance_as_its_workflow_and_a_failed_run_as_failed() {
let directory = crate::support::TempDir::new("workflows-worker");
let url = format!("sqlite://{}?mode=rwc", directory.join("workflows.sqlite").display());
let app = Application::configure()
.for_testing(env!("CARGO_MANIFEST_DIR"))
.with_env("WORKFLOW_STORE", "database")
.with_config(move |config, _| {
config.database.default = "primary".into();
config
.database
.connections
.insert("primary".into(), DatabaseConnection::new(url));
config.queue.add_connection("database", DatabaseQueue::new());
config.queue.default = "database".into();
})
.with_services(|services| {
services.instance(Records::default());
})
.create();
app.scope(async || {
let connection = db::default_connection()?;
migrate(&connection).await?;
connection.query(create_table(connection.driver())).statement().await?;
connection
.query(create_failed_table(connection.driver()))
.statement()
.await?;
Onboard { user_id: 3 }.start().await?;
BookTrip { trip_id: 4 }.start().await
})
.await
.unwrap();
let worked = app
.command("queue:work --queue=workflows,default --stop-when-empty")
.await;
worked
.assert_successful()
.assert_error_output_contains("workflow users.onboard ")
.assert_error_output_contains("BookTrip failed ")
.assert_error_output_contains("the step `book hotel` failed: no rooms");
assert!(!worked.error_output().contains("laravel.workflow.advance.v1"));
app.command("queue:failed")
.await
.assert_error_output_contains("No failed jobs found.");
let records = app.resolve::<Records>().await.all();
assert_eq!(records.iter().filter(|record| *record == "book hotel").count(), 1);
assert_eq!(
records.iter().filter(|record| record.starts_with("failed 4:")).count(),
1
);
let failed = app.command("workflow:list --status=failed --json").await;
let runs: serde_json::Value = serde_json::from_str(failed.output().trim()).unwrap();
assert_eq!(runs.as_array().unwrap().len(), 1);
}
async fn the_database_store_keeps_runs(app: Application) {
let run = app.workflow(Onboard { user_id: 1 }).await;
run.assert_sleeping();
app.travel(3.days());
run.advance().await;
run.assert_waiting_for("users.1.subscribed");
run.resume("users.1.subscribed", Subscribed { plan: "pro".into() })
.await;
run.assert_completed_with("pro");
let early = app.workflow(Onboard { user_id: 2 }).claim("users.2.subscribed").await;
app.scope(async || {
let rolled_back: laravel::Result<()> = db::transaction(async |_| {
workflow::resume(
"users.2.subscribed",
Subscribed {
plan: "rolled back".into(),
},
)
.await?;
Err(laravel::abort_with(409, "Roll back"))
})
.await;
assert!(rolled_back.is_err());
db::transaction(async |_| {
workflow::resume(
"users.2.subscribed",
Subscribed {
plan: "committed".into(),
},
)
.await
})
.await
})
.await
.unwrap();
app.travel(3.days());
early.advance().await;
early.assert_completed_with("committed");
let token = "expenses.2.decision";
let resume = |value: &'static str| app.scope(async move || workflow::resume(token, value).await);
let first = app.workflow(AwaitCallback { token: token.into() }).await;
let clicks = app
.scope(async || {
let _queue = laravel::queue::fake();
Ok::<_, laravel::Error>((
workflow::resume(token, "approved").await?,
workflow::resume(token, "approved twice").await?,
))
})
.await
.unwrap();
assert_eq!(clicks, (workflow::Resumed::Delivered, workflow::Resumed::Delivered));
first.advance().await.assert_completed_with("approved");
assert_eq!(resume("approved again").await.unwrap(), workflow::Resumed::NotFound);
let second = app.workflow(AwaitCallback { token: token.into() }).await;
second.assert_waiting_for(token);
let rival = app.workflow(AwaitCallback { token: token.into() }).await;
rival.assert_failed_with(&format!("which the unfinished run `{}` owns", second.id()));
second.resume(token, "rejected").await.assert_completed_with("rejected");
super::concurrent_resumes_reach_the_inbox(&app, "expenses.3.votes").await;
let listed = app
.scope(async || laravel::workflow::find(run.id()).await)
.await
.unwrap()
.unwrap();
assert_eq!(listed.steps().len(), 6);
let votes = app
.workflow(CollectVotes {
token: Some("expenses.1.votes".into()),
})
.await;
for approver in [1, 1, 2] {
votes
.resume(
"expenses.1.votes",
Vote {
approver,
approve: true,
},
)
.await;
}
votes.assert_completed_with("approved");
let workflow::Started::New(first) = start_charge(&app, 1).await else {
panic!("the first start saves a run");
};
assert_eq!(start_charge(&app, 1).await, workflow::Started::Existing(first));
let listed = app
.command("workflow:list --attribute tenant=acme --attribute phase=shipping --json")
.await;
let runs: serde_json::Value = serde_json::from_str(listed.output().trim()).unwrap();
assert_eq!(runs[0]["id"], first.to_string());
assert_eq!(runs.as_array().unwrap().len(), 1);
app.scope(async || workflow::cancel(first).reason("refunded").await)
.await
.unwrap();
let cancelled = app.scope(async || workflow::find(first).await).await.unwrap().unwrap();
assert_eq!(cancelled.error(), Some("refunded"));
assert!(matches!(start_charge(&app, 1).await, workflow::Started::New(id) if id != first));
let id = app
.scope(async || ReadBankDetails.start().purge_when_finished().await)
.await
.unwrap();
let info = app.scope(async || workflow::find(id).await).await.unwrap().unwrap();
assert!(info.purged() && info.status() == workflow::Status::Completed);
let shown = app.command(&format!("workflow:show {id} --json")).await;
assert!(!shown.output().contains("DE89"), "{}", shown.output());
}
#[tokio::test]
async fn a_workflow_fake_records_only_committed_starts() {
let app = application("sqlite::memory:".into()).await;
app.scope(async || {
let fake = workflow::fake();
let rolled_back: laravel::Result<()> = db::transaction(async |_| {
Onboard { user_id: 1 }.start().await?;
Err(laravel::abort_with(409, "Roll back"))
})
.await;
assert!(rolled_back.is_err());
fake.assert_nothing_started();
db::transaction(async |_| {
let started = Onboard { user_id: 2 }.start().unique("onboard.2").await?;
assert_eq!(started, workflow::Started::Pending(started.id()));
fake.assert_nothing_started();
Ok(())
})
.await
.unwrap();
fake.assert_started_times::<Onboard>(1)
.assert_started_where::<Onboard>(|run| run.user_id == 2);
})
.await;
}
#[tokio::test]
async fn sqlite_keeps_runs() {
let directory = crate::support::TempDir::new("workflows");
let url = format!("sqlite://{}?mode=rwc", directory.join("workflows.sqlite").display());
the_database_store_keeps_runs(application(url).await).await;
}
#[derive(Default)]
struct TakeoverGate {
attempts: std::sync::atomic::AtomicU32,
first_entered: tokio::sync::Notify,
first_continue: tokio::sync::Notify,
second_entered: tokio::sync::Notify,
second_continue: tokio::sync::Notify,
}
#[derive(laravel::queue::Queueable)]
struct FencedRun;
#[laravel::workflow::workflow(name = "fenced.run")]
impl FencedRun {
async fn handle(
self,
run: &laravel::workflow::Run,
gate: laravel::container::Inject<TakeoverGate>,
) -> laravel::Result<String> {
let label = run
.step("work", async {
let attempt = gate.attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
if attempt == 1 {
gate.first_entered.notify_one();
gate.first_continue.notified().await;
Ok("stale".to_owned())
} else {
gate.second_entered.notify_one();
gate.second_continue.notified().await;
Ok("current".to_owned())
}
})
.await?;
run.set_attribute("writer", label.clone());
Ok(label)
}
}
#[tokio::test]
async fn a_stale_advance_whose_lease_was_taken_over_cannot_overwrite_the_run() {
let directory = crate::support::TempDir::new("workflows-fenced");
let url = format!("sqlite://{}?mode=rwc", directory.join("workflows.sqlite").display());
let app = Application::configure()
.for_testing(env!("CARGO_MANIFEST_DIR"))
.with_env("WORKFLOW_STORE", "database")
.with_config(move |config, _| {
config.database.default = "primary".into();
config
.database
.connections
.insert("primary".into(), DatabaseConnection::new(url));
config.queue.add_connection("database", DatabaseQueue::new());
config.queue.default = "database".into();
})
.with_services(|services| {
services.instance(TakeoverGate::default());
})
.create();
let gate = app.resolve::<TakeoverGate>().await;
let id = app
.scope(async || {
let connection = db::default_connection()?;
migrate(&connection).await?;
connection.query(create_table(connection.driver())).statement().await?;
connection
.query(create_failed_table(connection.driver()))
.statement()
.await?;
FencedRun.start().await
})
.await
.unwrap();
let events = app.scope(async || laravel::event::fake()).await;
let first_worker = {
let app = app.clone();
tokio::spawn(async move {
app.command("queue:work --max-jobs=1 --stop-when-empty")
.await
.assert_successful();
})
};
gate.first_entered.notified().await;
app.scope(async || {
let expired = laravel::time::Timestamp::from_second(1_000_000_000).unwrap();
db::table("workflow_runs")
.filter(db::col("id").eq(id.to_string()))
.update(db::values! { leased_until: expired })
.await
})
.await
.unwrap();
app.command("workflow:recover").await.assert_successful();
let second_worker = {
let app = app.clone();
tokio::spawn(async move {
app.command("queue:work --max-jobs=1 --stop-when-empty")
.await
.assert_successful();
})
};
gate.second_entered.notified().await;
gate.first_continue.notify_one();
first_worker.await.unwrap();
let during = app.scope(async || workflow::find(id).await).await.unwrap().unwrap();
assert_eq!(during.status(), workflow::Status::Running);
assert!(during.steps().is_empty(), "the stale worker must not record a step");
assert!(
during.attributes().is_empty(),
"the stale worker must not write attributes"
);
gate.second_continue.notify_one();
second_worker.await.unwrap();
let finished = app.scope(async || workflow::find(id).await).await.unwrap().unwrap();
assert_eq!(finished.status(), workflow::Status::Completed);
assert_eq!(finished.output::<String>().unwrap().as_deref(), Some("current"));
assert_eq!(finished.attributes().get("writer").map(String::as_str), Some("current"));
assert_eq!(finished.steps().len(), 1);
let step_output: Option<String> = app
.scope(async || {
db::table("workflow_steps")
.filter(db::col("run_id").eq(id.to_string()) & db::col("name").eq("work"))
.value("output")
.await
})
.await
.unwrap();
assert_eq!(step_output.as_deref(), Some("\"current\""));
events.assert_dispatched_times::<super::RunCompleted>(1);
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
async fn postgres_keeps_runs() {
let url = std::env::var("LARAVEL_TEST_POSTGRES_URL").unwrap();
the_database_store_keeps_runs(application(url).await).await;
}
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable database"]
async fn mysql_keeps_runs() {
let url = std::env::var("LARAVEL_TEST_MYSQL_URL").unwrap();
the_database_store_keeps_runs(application(url).await).await;
}
}