79 行
2.7 KiB
Python
79 行
2.7 KiB
Python
"""Finite-state-machine helpers for workflows, nodes, and tasks."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
|
|
|
|
WORKFLOW_TRANSITIONS: dict[str, set[str]] = {
|
|
"draft": {"running", "archived"},
|
|
"running": {"completed", "failed", "cancelled", "archived"},
|
|
"completed": {"archived"},
|
|
"failed": {"running", "archived"},
|
|
"cancelled": {"running", "archived"},
|
|
"archived": set(),
|
|
}
|
|
|
|
NODE_TRANSITIONS: dict[str, set[str]] = {
|
|
"pending": {"queued", "running", "completed", "failed", "skipped"},
|
|
"queued": {"running", "completed", "failed", "cancelled"},
|
|
"running": {"completed", "failed", "cancelled"},
|
|
"completed": {"queued"},
|
|
"failed": {"queued", "skipped"},
|
|
"cancelled": {"queued"},
|
|
"skipped": {"queued"},
|
|
}
|
|
|
|
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", "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
|