durable-workflow 4.28.0

Rust client and worker SDK for Durable Workflow Cloud and self-hosted Server
Documentation
use super::{invalid_recorded_history, recorded_parallel_group_entry, Error, HistoryEvent, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;

pub(super) const CAPABILITY: &str = "parallel_group_policies";
pub(super) const FIELD: &str = "parallel_group_policy";
const CAUSE: &str = "parallel_group_cancellation";

/// Failure behavior for an explicitly qualified durable parallel group.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ParallelFailurePolicy {
    /// Raise the first failure in recorded event order.
    Propagate,
    /// Raise the first recorded failure after Server cancels eligible siblings.
    CancelRemaining,
    /// Return each member's durable result or failure after all members settle.
    Settle,
}

impl ParallelFailurePolicy {
    const ALL: [Self; 3] = [Self::Propagate, Self::CancelRemaining, Self::Settle];

    pub(super) fn as_str(self) -> &'static str {
        match self {
            Self::Propagate => "propagate",
            Self::CancelRemaining => "cancel_remaining",
            Self::Settle => "settle",
        }
    }

    fn bit(self) -> u8 {
        match self {
            Self::Propagate => 1,
            Self::CancelRemaining => 2,
            Self::Settle => 4,
        }
    }

    pub(super) fn parse(value: &Value) -> Option<Self> {
        let name = value.as_str()?;
        Self::ALL.into_iter().find(|policy| policy.as_str() == name)
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct Policies(pub(super) u8);

impl Policies {
    pub(super) fn requested(values: impl IntoIterator<Item = ParallelFailurePolicy>) -> Self {
        Self(
            values
                .into_iter()
                .fold(0, |bits, policy| bits | policy.bit()),
        )
    }

    pub(super) fn contains(self, policy: ParallelFailurePolicy) -> bool {
        self.0 & policy.bit() != 0
    }

    pub(super) fn is_empty(self) -> bool {
        self.0 == 0
    }

    pub(super) fn intersect(self, other: Self) -> Self {
        Self(self.0 & other.0)
    }

    pub(super) fn descriptor(self) -> Value {
        json!({
            "supported": true, "version": 1,
            "policies": ParallelFailurePolicy::ALL.into_iter()
                .filter(|policy| self.contains(*policy)).map(ParallelFailurePolicy::as_str)
                .collect::<Vec<_>>(),
        })
    }

    pub(super) fn read_descriptor(value: &Value) -> Result<Self> {
        let invalid =
            || Error::WorkerLoop("invalid parallel_group_policies version 1 descriptor".into());
        if !value.as_object().is_some_and(|fields| fields.len() == 3)
            || value["supported"] != true
            || value["version"].as_u64() != Some(1)
        {
            return Err(invalid());
        }
        let names = value["policies"]
            .as_array()
            .filter(|names| !names.is_empty())
            .ok_or_else(invalid)?;
        let mut policies = Self::default();
        for name in names {
            let policy = ParallelFailurePolicy::parse(name).ok_or_else(invalid)?;
            if policies.contains(policy) {
                return Err(invalid());
            }
            policies.0 |= policy.bit();
        }
        Ok(policies)
    }
}

#[derive(Clone, Copy, Debug)]
pub(super) struct FailureOrder {
    pub(super) ordinal: u64,
    pub(super) sibling_cancellation: bool,
}

#[derive(Debug, Default)]
pub(super) struct Recorded {
    groups: HashMap<String, Option<ParallelFailurePolicy>>,
    failures: HashMap<u64, FailureOrder>,
    completions: HashMap<u64, u64>,
}

impl Recorded {
    pub(super) fn read(history: &[HistoryEvent]) -> Result<Self> {
        let mut recorded = Self::default();
        let mut initiating = HashMap::new();
        for event in history {
            let payload = &event.payload;
            let path = payload.get("parallel_group_path").and_then(Value::as_array);
            let explicit = payload.get(FIELD).is_some()
                || path.is_some_and(|frames| frames.iter().any(|frame| frame.get(FIELD).is_some()));
            let cause = payload.get(CAUSE);
            if !explicit && cause.is_none() {
                for frame in path
                    .map(Vec::as_slice)
                    .unwrap_or(std::slice::from_ref(payload))
                {
                    if let Some(group) = frame["parallel_group_id"].as_str() {
                        recorded.insert(
                            group,
                            None,
                            super::durable_event_sequence(event).unwrap_or(0),
                        )?;
                    }
                }
                continue;
            }

            let slot = payload["parallel_group_base_sequence"]
                .as_u64()
                .zip(payload["parallel_group_index"].as_u64())
                .and_then(|(base, index)| base.checked_add(index))
                .ok_or_else(|| malformed(0))?;
            let ordinal = event
                .raw
                .get("sequence")
                .and_then(Value::as_u64)
                .filter(|ordinal| *ordinal > 0)
                .ok_or_else(|| malformed(slot))?;
            let frames = path
                .filter(|frames| !frames.is_empty())
                .ok_or_else(|| malformed(slot))?;
            let policy =
                ParallelFailurePolicy::parse(&payload[FIELD]).ok_or_else(|| malformed(slot))?;
            let root = recorded_parallel_group_entry(&frames[0], slot)?;
            let inner = recorded_parallel_group_entry(frames.last().expect("nonempty path"), slot)?;
            if recorded_parallel_group_entry(payload, slot)? != inner {
                return Err(malformed(slot));
            }
            for frame in frames {
                let metadata = recorded_parallel_group_entry(frame, slot)?;
                if metadata.parallel_group_mode.is_some()
                    || ParallelFailurePolicy::parse(&frame[FIELD]) != Some(policy)
                {
                    return Err(malformed(slot));
                }
                recorded.insert(&metadata.parallel_group_id, Some(policy), slot)?;
            }

            if let Some(cause) = cause {
                let failure = cause["failure_event_sequence"]
                    .as_u64()
                    .zip(cause["failed_member_index"].as_u64());
                if policy != ParallelFailurePolicy::CancelRemaining
                    || !matches!(
                        event.event_type.as_str(),
                        "ActivityCancelled"
                            | "TimerCancelled"
                            | "ConditionWaitCancelled"
                            | "SignalWaitCancelled"
                            | "ChildCancellationRequested"
                    )
                    || !cause.as_object().is_some_and(|fields| fields.len() == 4)
                    || cause["schema"] != "durable-workflow.parallel-group-cancellation/v1"
                    || cause["policy"] != policy.as_str()
                    || !failure.is_some_and(|(source, index)| {
                        source < ordinal && index != root.parallel_group_index as u64
                    })
                    || initiating.get(&root.parallel_group_id).copied() != failure
                {
                    return Err(invalid_recorded_history(
                        "parallel_group_cancellation_history_invalid",
                        slot,
                        "sibling cancellation linked to the first member failure",
                        "invalid cause",
                        "recorded parallel sibling cancellation lacks its initiating failure",
                    ));
                }
            }
            let initiates = matches!(
                event.event_type.as_str(),
                "ActivityFailed"
                    | "ActivityTimedOut"
                    | "ChildRunFailed"
                    | "ChildRunCancelled"
                    | "ChildRunTerminated"
            );
            if initiates && policy == ParallelFailurePolicy::CancelRemaining {
                initiating
                    .entry(root.parallel_group_id)
                    .or_insert((ordinal, root.parallel_group_index as u64));
            }
            if matches!(
                event.event_type.as_str(),
                "ActivityCompleted"
                    | "ChildRunCompleted"
                    | "TimerFired"
                    | "ConditionWaitSatisfied"
                    | "ConditionWaitTimedOut"
            ) && payload["timer_kind"].as_str() != Some("condition_timeout")
            {
                recorded.completions.entry(slot).or_insert(ordinal);
            }
            if initiates
                || matches!(
                    event.event_type.as_str(),
                    "ActivityCancelled"
                        | "TimerCancelled"
                        | "ConditionWaitCancelled"
                        | "SignalWaitCancelled"
                )
            {
                recorded.failures.entry(slot).or_insert(FailureOrder {
                    ordinal,
                    sibling_cancellation: cause.is_some(),
                });
            }
        }
        Ok(recorded)
    }

    fn insert(
        &mut self,
        group: &str,
        policy: Option<ParallelFailurePolicy>,
        slot: u64,
    ) -> Result<()> {
        if self
            .groups
            .insert(group.to_owned(), policy)
            .is_some_and(|prior| prior != policy)
        {
            return Err(invalid_recorded_history(
                "parallel_group_history_conflict",
                slot,
                "one failure policy for the group",
                "inconsistent policy",
                "parallel-group history changes its recorded failure policy",
            ));
        }
        Ok(())
    }

    pub(super) fn check_supported(&self, policies: Policies) -> Result<()> {
        if let Some(policy) = ParallelFailurePolicy::ALL.into_iter().find(|policy| {
            !policies.contains(*policy) && self.groups.values().any(|value| *value == Some(*policy))
        }) {
            return Err(Error::ParallelGroupPolicyUnavailable(policy));
        }
        Ok(())
    }

    pub(super) fn match_group(
        &self,
        group: &str,
        slot: u64,
        authored: Option<ParallelFailurePolicy>,
    ) -> Result<()> {
        if self
            .groups
            .get(group)
            .is_some_and(|recorded| *recorded != authored)
        {
            return Err(invalid_recorded_history(
                "parallel_group_policy_changed",
                slot,
                "the original group failure policy",
                "changed policy",
                "the authored failure policy differs from the recorded group policy",
            ));
        }
        Ok(())
    }

    pub(super) fn failure(&self, sequence: u64) -> Option<FailureOrder> {
        self.failures.get(&sequence).copied()
    }

    pub(super) fn completed_before(&self, sequence: u64, failure_ordinal: u64) -> bool {
        self.completions
            .get(&sequence)
            .is_some_and(|ordinal| *ordinal < failure_ordinal)
    }
}

fn malformed(sequence: u64) -> Error {
    invalid_recorded_history(
        "parallel_group_metadata_invalid",
        sequence,
        "canonical explicit parallel-group path",
        "invalid policy metadata",
        "explicit group policy requires canonical metadata and an event ordinal",
    )
}

pub(super) fn completion_refused(error: &Error, worker_id: &str, sent: Policies) -> bool {
    if sent.is_empty() {
        return false;
    }
    let Error::Http { status, body } = error else {
        return false;
    };
    if *status != reqwest::StatusCode::CONFLICT {
        return false;
    }
    let Ok(body) = serde_json::from_str::<Value>(body) else {
        return false;
    };
    body["reason"] == "parallel_group_policy_not_supported"
        && body["recorded"] == false
        && body["worker_id"] == worker_id
        && body["required_capability"] == CAPABILITY
        && ParallelFailurePolicy::parse(&body[FIELD]).is_some_and(|policy| sent.contains(policy))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn explicit_parallel_refusal_must_match_submitted_policy_and_current_lease() {
        let error = |worker, policy, recorded| Error::Http {
            status: reqwest::StatusCode::CONFLICT,
            body: json!({
                "reason": "parallel_group_policy_not_supported",
                "worker_id": worker,
                "required_capability": CAPABILITY,
                "parallel_group_policy": policy,
                "recorded": recorded,
            })
            .to_string(),
        };
        let sent = Policies::requested([ParallelFailurePolicy::Settle]);
        assert!(completion_refused(
            &error("worker", "settle", false),
            "worker",
            sent
        ));
        assert!(!completion_refused(
            &error("other", "settle", false),
            "worker",
            sent
        ));
        assert!(!completion_refused(
            &error("worker", "settle", true),
            "worker",
            sent
        ));
        assert!(!completion_refused(
            &error("worker", "cancel_remaining", false),
            "worker",
            sent
        ));
    }
}