Files
plba_v2/src/plba/workflow/engine.py
T
2026-10-10 19:36:32 +03:00

132 lines
4.8 KiB
Python

from collections.abc import Callable, Mapping
import logging
from uuid import UUID, uuid4
from plba.workflow.models import (
StepResult,
WorkflowContext,
WorkflowDefinition,
WorkflowRunResult,
WorkflowTransitionError,
)
from plba.workflow.persistence import WorkflowPersistence
from plba.workflow.failure_recorder import WorkflowFailureRecorder
class WorkflowEngine:
def __init__(
self,
persistence: WorkflowPersistence,
id_factory: Callable[[], UUID] = uuid4,
logger: logging.Logger | None = None,
) -> None:
self._persistence = persistence
self._id_factory = id_factory
self._logger = logger or logging.getLogger(__name__)
self._failure_recorder = WorkflowFailureRecorder(
persistence, self._logger
)
async def run(
self, definition: WorkflowDefinition, context: WorkflowContext
) -> WorkflowRunResult:
definition.validate()
run_id = str(self._id_factory())
current_name = definition.initial_step
current_context = context
await self._persistence.record_run_started(
run_id, definition.name, self._snapshot(current_context)
)
self._logger.info(
"workflow run started",
extra={
"attributes": {"workflow": definition.name, "run_id": run_id}
},
)
try:
while current_name is not None:
node = definition.nodes[current_name]
self._logger.debug(
"workflow step started",
extra={
"attributes": {
"workflow": definition.name,
"run_id": run_id,
"step": current_name,
}
},
)
await self._persistence.record_step_started(
run_id, current_name, self._snapshot(current_context)
)
try:
result = await node.step(current_context)
next_name = self._next_node(node.transitions, result)
except Exception as error:
await self._failure_recorder.record_step_failure(
run_id, current_name, current_context, error
)
raise
next_context = current_context.with_updates(result.updates)
await self._persistence.record_step_completed(
run_id, current_name, self._snapshot(next_context), result
)
self._logger.debug(
"workflow step completed",
extra={
"attributes": {
"workflow": definition.name,
"run_id": run_id,
"step": current_name,
"status": result.status,
}
},
)
current_name = next_name
current_context = next_context
await self._persistence.record_run_completed(
run_id, definition.name, self._snapshot(current_context), "completed"
)
self._logger.info(
"workflow run completed",
extra={
"attributes": {
"workflow": definition.name,
"run_id": run_id,
"status": "completed",
}
},
)
return WorkflowRunResult(run_id, current_context, "completed")
except Exception as error:
await self._failure_recorder.record_run_failure(
run_id, definition.name, self._snapshot(current_context), error
)
raise
@staticmethod
def _next_node(
transitions: Mapping[str, str], result: StepResult
) -> str | None:
if not isinstance(result, StepResult):
raise TypeError("workflow step must return StepResult")
if not isinstance(result.updates, Mapping) or not isinstance(result.status, str):
raise TypeError("workflow step returned an invalid StepResult")
if result.transition is None:
if transitions:
raise WorkflowTransitionError(
"step must select one of its declared transitions"
)
return None
if result.transition not in transitions:
raise WorkflowTransitionError(
f"transition is not declared: {result.transition}"
)
return transitions[result.transition]
@staticmethod
def _snapshot(context: WorkflowContext) -> WorkflowContext:
return WorkflowContext(context.state)