"""Profile workflow and workflow node service.""" from __future__ import annotations from typing import Any from uuid import uuid4 from backend.dto.common import ApiError, ErrorCode from backend.dto.workflow_dto import ProfileWorkflow, WorkflowBranch, WorkflowDetail, WorkflowNode from core.audit_service import AuditService from core.event_bus import EventBus from core.fsm import node_transition, workflow_transition from core.identity import RequestContext from database.repositories.profile_repository import ProfileRepository from database.repositories.workflow_repository import WorkflowRepository from engines.character_flow import gradual_node_templates from engines.fast_character_flow import fast_character_node_templates from engines.quick_profile_flow import quick_profile_node_templates WORKFLOW_TYPES = {"single_image", "character_gradual", "character_fast", "quick_profile"} WORKFLOW_STATUSES = {"draft", "active", "running", "completed", "failed", "archived", "cancelled"} BRANCH_STATUSES = {"active", "archived"} NODE_STATUSES = { "draft", "queued", "running", "completed", "selected", "failed", "skipped", "discarded", } class WorkflowService: def __init__( self, workflow_repository: WorkflowRepository, profile_repository: ProfileRepository, audit_service: AuditService, event_bus: EventBus | None = None, ): self.workflow_repository = workflow_repository self.profile_repository = profile_repository self.audit_service = audit_service self.event_bus = event_bus def create_workflow( self, profile_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> WorkflowDetail: self._ensure_profile_exists(profile_id) workflow_type = str(payload.get("workflow_type") or "").strip() if workflow_type not in WORKFLOW_TYPES: raise ApiError( ErrorCode.VALIDATION_FAILED, "unsupported workflow type", {"field": "workflow_type", "allowed": sorted(WORKFLOW_TYPES)}, ) display_name = str(payload.get("display_name") or "").strip() if not display_name: raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow display_name is required", {"field": "display_name"}, ) workflow = self.workflow_repository.create_workflow( { "workflow_id": payload.get("workflow_id") or new_workflow_id(), "profile_id": profile_id, "workflow_type": workflow_type, "display_name": display_name, "mode": payload.get("mode"), "status": payload.get("status", "draft"), "current_branch": payload.get("current_branch", "main"), "session_key": payload.get("session_key") or ctx.session_key, "metadata": payload.get("metadata") or {}, } ) nodes = self._create_initial_nodes(workflow, payload, ctx) if nodes: self.workflow_repository.update_workflow( workflow.workflow_id, {"current_node_id": nodes[0].node_id}, ) workflow = self.workflow_repository.get_workflow(workflow.workflow_id) or workflow self.audit_service.record( ctx=ctx, action="create_workflow", target_type="profile_workflow", target_id=workflow.workflow_id, after_snapshot=workflow.to_dict(), ) self._publish( "workflow.created", { "workflow_id": workflow.workflow_id, "profile_id": workflow.profile_id, "workflow_type": workflow.workflow_type, "node_ids": [node.node_id for node in nodes], }, ) return WorkflowDetail(workflow=workflow, nodes=nodes) def list_workflows(self, profile_id: str) -> list[ProfileWorkflow]: self._ensure_profile_exists(profile_id) return self.workflow_repository.list_workflows(profile_id) def get_workflow(self, workflow_id: str) -> WorkflowDetail: workflow = self.workflow_repository.get_workflow(workflow_id) if workflow is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "workflow not found", {"workflow_id": workflow_id}, ) return WorkflowDetail( workflow=workflow, nodes=self.workflow_repository.list_nodes(workflow_id), ) def update_workflow( self, workflow_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> ProfileWorkflow: before = self.get_workflow(workflow_id).workflow if "status" in payload: self._validate_workflow_status_transition(before.status, str(payload["status"])) if "display_name" in payload and not str(payload["display_name"]).strip(): raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow display_name is required", {"field": "display_name"}, ) update_payload = dict(payload) if "display_name" in update_payload: update_payload["display_name"] = str(update_payload["display_name"]).strip() after = self.workflow_repository.update_workflow(workflow_id, update_payload) if after is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "workflow not found", {"workflow_id": workflow_id}) self.audit_service.record( ctx=ctx, action="update_workflow", target_type="profile_workflow", target_id=workflow_id, before_snapshot=before.to_dict(), after_snapshot=after.to_dict(), ) if before.status != after.status: self._publish( "workflow.status_changed", { "workflow_id": workflow_id, "profile_id": after.profile_id, "before_status": before.status, "after_status": after.status, }, ) self._publish("workflow.updated", {"workflow_id": workflow_id, "profile_id": after.profile_id}) return after def create_branch( self, workflow_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> WorkflowBranch: workflow = self._ensure_workflow_exists(workflow_id) branch_name = str(payload.get("branch_name") or "").strip() if not branch_name: raise ApiError(ErrorCode.VALIDATION_FAILED, "branch_name is required", {"field": "branch_name"}) if self.workflow_repository.get_branch(workflow_id, branch_name): raise ApiError( ErrorCode.VALIDATION_FAILED, "branch already exists", {"workflow_id": workflow_id, "branch_name": branch_name}, ) base_branch_name = str(payload.get("base_branch_name") or workflow.current_branch or "main") base_node_id = payload.get("base_node_id") or workflow.current_node_id branch = self.workflow_repository.create_branch( { "branch_id": payload.get("branch_id") or new_branch_id(), "workflow_id": workflow_id, "branch_name": branch_name, "base_branch_name": base_branch_name, "base_node_id": base_node_id, "status": payload.get("status", "active"), "metadata": payload.get("metadata") or {}, } ) copied_nodes = [] if payload.get("copy_nodes", True): copied_nodes = self._copy_branch_nodes(workflow_id, base_branch_name, branch_name, ctx) self.audit_service.record( ctx=ctx, action="create_branch", target_type="workflow_branch", target_id=branch.branch_id, after_snapshot={**branch.to_dict(), "copied_node_ids": [node.node_id for node in copied_nodes]}, ) self._publish( "workflow.branch_created", { "workflow_id": workflow_id, "branch_name": branch.branch_name, "copied_node_ids": [node.node_id for node in copied_nodes], }, ) return branch def list_branches(self, workflow_id: str) -> list[WorkflowBranch]: self._ensure_workflow_exists(workflow_id) branches = self.workflow_repository.list_branches(workflow_id) if branches: return branches return [ WorkflowBranch( branch_id="branch_virtual_main", workflow_id=workflow_id, branch_name="main", base_branch_name=None, base_node_id=None, status="active", metadata={"virtual": True}, created_at="", updated_at="", ) ] def switch_branch(self, workflow_id: str, branch_name: str, ctx: RequestContext) -> ProfileWorkflow: before = self._ensure_workflow_exists(workflow_id) if branch_name != "main" and self.workflow_repository.get_branch(workflow_id, branch_name) is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "branch not found", {"workflow_id": workflow_id, "branch_name": branch_name}, ) branch_nodes = self.workflow_repository.list_nodes(workflow_id, branch_name=branch_name) after = self.update_workflow( workflow_id, { "current_branch": branch_name, "current_node_id": branch_nodes[0].node_id if branch_nodes else before.current_node_id, }, ctx, ) self.audit_service.record( ctx=ctx, action="switch_branch", target_type="profile_workflow", target_id=workflow_id, before_snapshot=before.to_dict(), after_snapshot=after.to_dict(), ) return after def create_node( self, workflow_id: str, payload: dict[str, Any], ctx: RequestContext, *, audit: bool = True, ) -> WorkflowNode: self._ensure_workflow_exists(workflow_id) node_key = str(payload.get("node_key") or "").strip() title = str(payload.get("title") or "").strip() if not node_key: raise ApiError(ErrorCode.VALIDATION_FAILED, "node_key is required", {"field": "node_key"}) if not title: raise ApiError(ErrorCode.VALIDATION_FAILED, "node title is required", {"field": "title"}) status = payload.get("status", "draft") if status not in NODE_STATUSES: raise ApiError( ErrorCode.VALIDATION_FAILED, "unsupported node status", {"field": "status", "allowed": sorted(NODE_STATUSES)}, ) node = self.workflow_repository.create_node( { "node_id": payload.get("node_id") or new_node_id(), "workflow_id": workflow_id, "node_key": node_key, "title": title, "description": payload.get("description"), "step_name": payload.get("step_name"), "node_type": payload.get("node_type", "generation"), "status": status, "branch_name": payload.get("branch_name", "main"), "prompt": payload.get("prompt"), "negative_prompt": payload.get("negative_prompt"), "model_route": payload.get("model_route"), "selected_image_id": payload.get("selected_image_id"), "sort_order": payload.get("sort_order", 0), "metadata": payload.get("metadata") or {}, } ) if audit: self.audit_service.record( ctx=ctx, action="create_node", target_type="workflow_node", target_id=node.node_id, after_snapshot=node.to_dict(), ) self._publish( "workflow.node_created", {"workflow_id": workflow_id, "node_id": node.node_id, "node_key": node.node_key}, ) return node def list_nodes(self, workflow_id: str) -> list[WorkflowNode]: self._ensure_workflow_exists(workflow_id) return self.workflow_repository.list_nodes(workflow_id) def get_node(self, node_id: str) -> WorkflowNode: node = self.workflow_repository.get_node(node_id) if node is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "node not found", {"node_id": node_id}) return node def update_node(self, node_id: str, payload: dict[str, Any], ctx: RequestContext) -> WorkflowNode: before = self.get_node(node_id) if "status" in payload: self._validate_node_status_transition(before.status, str(payload["status"])) if "title" in payload and not str(payload["title"]).strip(): raise ApiError(ErrorCode.VALIDATION_FAILED, "node title is required", {"field": "title"}) update_payload = dict(payload) if "title" in update_payload: update_payload["title"] = str(update_payload["title"]).strip() after = self.workflow_repository.update_node(node_id, update_payload) if after is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "node not found", {"node_id": node_id}) self.audit_service.record( ctx=ctx, action="update_node", target_type="workflow_node", target_id=node_id, before_snapshot=before.to_dict(), after_snapshot=after.to_dict(), ) if before.status != after.status: self._publish( "workflow.node_status_changed", { "workflow_id": after.workflow_id, "node_id": node_id, "before_status": before.status, "after_status": after.status, }, ) self._publish("workflow.node_updated", {"workflow_id": after.workflow_id, "node_id": node_id}) return after def _create_initial_nodes( self, workflow: ProfileWorkflow, payload: dict[str, Any], ctx: RequestContext, ) -> list[WorkflowNode]: if payload.get("auto_create_nodes", True) is False: return [] return [ self.create_node( workflow.workflow_id, template, ctx, audit=False, ) for template in _initial_node_templates(workflow.workflow_type) ] def _copy_branch_nodes( self, workflow_id: str, from_branch: str, to_branch: str, ctx: RequestContext, ) -> list[WorkflowNode]: source_nodes = self.workflow_repository.list_nodes(workflow_id, branch_name=from_branch) if not source_nodes and from_branch != "main": source_nodes = self.workflow_repository.list_nodes(workflow_id, branch_name="main") return [ self.create_node( workflow_id, { "node_key": node.node_key, "title": node.title, "description": node.description, "step_name": node.step_name, "node_type": node.node_type, "status": "draft", "branch_name": to_branch, "prompt": node.prompt, "negative_prompt": node.negative_prompt, "model_route": node.model_route, "sort_order": node.sort_order, "metadata": {**node.metadata, "copied_from_node_id": node.node_id}, }, ctx, audit=False, ) for node in source_nodes ] def _ensure_profile_exists(self, profile_id: str) -> None: profile = self.profile_repository.get(profile_id) if profile is None or profile.status == "deleted": raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "profile not found", {"profile_id": profile_id}, ) def _ensure_workflow_exists(self, workflow_id: str) -> ProfileWorkflow: workflow = self.workflow_repository.get_workflow(workflow_id) if workflow is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "workflow not found", {"workflow_id": workflow_id}, ) return workflow def _validate_workflow_status_transition(self, current: str, target: str) -> None: if target not in WORKFLOW_STATUSES: raise ApiError( ErrorCode.VALIDATION_FAILED, "unsupported workflow status", {"field": "status", "allowed": sorted(WORKFLOW_STATUSES)}, ) transition = workflow_transition(current, target) if not transition.allowed: raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow status transition is not allowed", {"current": current, "target": target, "reason": transition.reason}, ) def _validate_node_status_transition(self, current: str, target: str) -> None: if target not in NODE_STATUSES: raise ApiError( ErrorCode.VALIDATION_FAILED, "unsupported node status", {"field": "status", "allowed": sorted(NODE_STATUSES)}, ) transition = node_transition(current, target) if not transition.allowed: raise ApiError( ErrorCode.VALIDATION_FAILED, "node status transition is not allowed", {"current": current, "target": target, "reason": transition.reason}, ) def _publish(self, event_type: str, payload: dict[str, Any]) -> None: if self.event_bus: self.event_bus.publish(event_type, payload) def new_workflow_id() -> str: return f"workflow_{uuid4().hex}" def new_node_id() -> str: return f"node_{uuid4().hex}" def new_branch_id() -> str: return f"branch_{uuid4().hex}" def _initial_node_templates(workflow_type: str) -> list[dict[str, Any]]: if workflow_type == "single_image": return [ { "node_key": "virtual_single_image", "title": "Single image", "description": "Backend virtual node for the single image flow.", "node_type": "virtual_single_image", "sort_order": 0, "metadata": {"virtual": True, "template": "single_image_v1"}, } ] if workflow_type == "character_gradual": return gradual_node_templates() if workflow_type == "character_fast": return fast_character_node_templates() if workflow_type == "quick_profile": return quick_profile_node_templates() return []