orcher-sdk 0.18.3

Rust SDK for Orcher, a durable workflow engine: workflows, tasks, actors, workers and a client
Documentation
//! A step that has to wait returns nothing to the workflow's code.
//!
//! A waiting step used to return `Err(Suspended)`. Code that used `?` passed
//! it on, but code that matched on a step's error took a wait for a failure:
//! its error arm ran, and what it scheduled there went out with the
//! activation; code that swallowed the error and returned `Ok` completed the
//! run over the step's scheduled task (sdk-rust#129). The step now never
//! resolves, and [`drive`] ends the activation once the code has stopped.

use super::command::WorkflowCommand;
use super::WorkflowExecution;
use super::{drive, WorkflowContext};
use crate::error::{Error, Result};

fn context() -> WorkflowContext {
    WorkflowContext::new(
        WorkflowExecution {
            workflow_id: "order-7".to_string(),
            run_id: "run-1".to_string(),
            workflow_type: "checkout".to_string(),
            attempt: 1,
            namespace: "default".to_string(),
            task_queue: "orders".to_string(),
        },
        false,
        "1.0.0".to_string(),
    )
}

/// The task types the activation scheduled, in order.
fn scheduled(ctx: &WorkflowContext) -> Vec<String> {
    ctx.take_commands()
        .into_iter()
        .filter_map(|command| match command {
            WorkflowCommand::ScheduleTask(task) => Some(task.task_type),
            _ => None,
        })
        .collect()
}

fn waits(outcome: &Result<String>) -> bool {
    matches!(outcome, Err(e) if e.is_suspend())
}

#[tokio::test]
async fn the_error_arm_around_a_waiting_step_does_not_run() {
    let ctx = context();
    let code = ctx.clone();
    let outcome = drive(&ctx, async move {
        match code.execute_task::<_, _, String>("charge", 1).await {
            Ok(charged) => code.execute_task::<_, _, String>("ship", charged).await,
            Err(failed) => {
                // What a workflow does when a step really fails.
                let _: String = code.execute_task("refund", 1).await?;
                Err(failed)
            }
        }
    })
    .await;

    assert!(waits(&outcome), "{outcome:?}");
    assert_eq!(scheduled(&ctx), ["charge"]);
}

#[tokio::test]
async fn code_that_ignores_a_waiting_steps_outcome_does_not_complete() {
    let ctx = context();
    let code = ctx.clone();
    let outcome = drive(&ctx, async move {
        let _ = code.execute_task::<_, _, String>("charge", 1).await;
        Ok("done".to_string())
    })
    .await;

    assert!(waits(&outcome), "{outcome:?}");
    assert_eq!(scheduled(&ctx), ["charge"]);
}

#[tokio::test]
async fn every_joined_branch_is_scheduled_in_one_activation() {
    let ctx = context();
    let (left, right) = (ctx.clone(), ctx.clone());
    let outcome = drive(&ctx, async move {
        let (a, b) = tokio::join!(
            left.execute_task::<_, _, String>("left", 1),
            right.execute_task::<_, _, String>("right", 2),
        );
        Ok(format!("{}{}", a?, b?))
    })
    .await;

    assert!(waits(&outcome), "{outcome:?}");
    assert_eq!(scheduled(&ctx), ["left", "right"]);
}

#[tokio::test]
async fn a_closure_running_beside_a_waiting_step_is_waited_for() {
    let ctx = context();
    let (step, side) = (ctx.clone(), ctx.clone());
    let outcome = drive(&ctx, async move {
        let (a, noted) = tokio::join!(step.execute_task::<_, _, String>("charge", 1), async {
            side.execute("note", || async {
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
                Ok::<_, Error>(7)
            })
            .await
        },);
        Ok(format!("{}{}", a?, noted?))
    })
    .await;

    assert!(waits(&outcome), "{outcome:?}");
    // The closure finished, and its result is recorded with this activation.
    let recorded = super::closure_commands::extract_closure_commands(&ctx).unwrap();
    assert_eq!(recorded.len(), 1);
}

#[tokio::test]
async fn code_that_waits_for_nothing_runs_to_its_end() {
    let ctx = context();
    let outcome = drive(&ctx, async move { Ok("done".to_string()) }).await;
    assert_eq!(outcome.ok().as_deref(), Some("done"));

    let ctx = context();
    let outcome: Result<String> =
        drive(&ctx, async move { Err(Error::Other("broke".to_string())) }).await;
    assert!(matches!(outcome, Err(e) if !e.is_suspend()));
}

/// Code run by hand, outside `drive`, is told the step is waiting, as it
/// always was: nothing would end the wait, so it must not wait for good
/// (sdk-rust#132).
#[tokio::test]
async fn a_step_awaited_outside_drive_says_it_is_waiting() {
    let ctx = context();
    let outcome = tokio::time::timeout(
        std::time::Duration::from_secs(5),
        ctx.execute_task::<_, _, String>("charge", 1),
    )
    .await
    .expect("a step awaited outside drive must not wait for good");
    assert!(waits(&outcome), "{outcome:?}");
    assert_eq!(scheduled(&ctx), ["charge"]);

    // Under drive again afterwards, the same context waits as the worker's do.
    let code = ctx.clone();
    let outcome = drive(&ctx, async move {
        match code.execute_task::<_, _, String>("ship", 1).await {
            Ok(shipped) => Ok(shipped),
            Err(_) => Ok("the error arm ran".to_string()),
        }
    })
    .await;
    assert!(waits(&outcome), "{outcome:?}");
}