"""Finite-state-machine helpers for workflows, nodes, and tasks.""" from __future__ import annotations from dataclasses import dataclass WORKFLOW_TRANSITIONS: dict[str, set[str]] = { "draft": {"active", "running", "completed", "failed", "cancelled", "archived"}, "active": {"running", "completed", "failed", "cancelled", "archived"}, "running": {"completed", "failed", "cancelled", "archived"}, "completed": {"archived"}, "failed": {"running", "archived"}, "cancelled": {"running", "archived"}, "archived": set(), } NODE_TRANSITIONS: dict[str, set[str]] = { "draft": {"queued", "running", "completed", "selected", "failed", "skipped", "discarded"}, "pending": {"queued", "running", "completed", "failed", "skipped"}, "queued": {"running", "completed", "selected", "failed", "cancelled", "discarded"}, "running": {"completed", "selected", "failed", "cancelled", "discarded"}, "completed": {"queued", "selected", "discarded"}, "selected": {"queued", "completed", "discarded"}, "failed": {"queued", "skipped", "discarded"}, "cancelled": {"queued", "discarded"}, "skipped": {"queued", "discarded"}, "discarded": set(), } TASK_TRANSITIONS: dict[str, set[str]] = { "created": {"queued", "running", "cancelled"}, "queued": {"running", "cancelled", "failed"}, "running": {"completed", "succeeded", "failed", "cancelled"}, "completed": set(), "succeeded": set(), "failed": {"queued", "cancelled", "dead_letter"}, "cancelled": {"queued"}, "dead_letter": {"queued"}, } @dataclass(frozen=True) class TransitionResult: allowed: bool current: str target: str reason: str = "" def can_transition(current: str, target: str, transitions: dict[str, set[str]]) -> bool: normalized_current = _normalize_state(current) normalized_target = _normalize_state(target) return normalized_target == normalized_current or normalized_target in transitions.get(normalized_current, set()) def check_transition(current: str, target: str, transitions: dict[str, set[str]]) -> TransitionResult: normalized_current = _normalize_state(current) normalized_target = _normalize_state(target) if normalized_current not in transitions: return TransitionResult(False, normalized_current, normalized_target, "unknown current state") if can_transition(normalized_current, normalized_target, transitions): return TransitionResult(True, normalized_current, normalized_target) return TransitionResult(False, normalized_current, normalized_target, "transition is not allowed") def workflow_transition(current: str, target: str) -> TransitionResult: return check_transition(current, target, WORKFLOW_TRANSITIONS) def node_transition(current: str, target: str) -> TransitionResult: return check_transition(current, target, NODE_TRANSITIONS) def task_transition(current: str, target: str) -> TransitionResult: return check_transition(current, target, TASK_TRANSITIONS) def _normalize_state(value: str) -> str: normalized = str(value or "").strip().lower() if not normalized: raise ValueError("state is required") return normalized