astrbot_plugin_imagestudio/backend/services/workflow_service.py

297 行
11 KiB
Python

"""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, WorkflowDetail, WorkflowNode
from core.audit_service import AuditService
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"}
NODE_STATUSES = {
"draft",
"queued",
"running",
"completed",
"selected",
"failed",
"skipped",
"discarded",
}
class WorkflowService:
def __init__(
self,
workflow_repository: WorkflowRepository,
profile_repository: ProfileRepository,
audit_service: AuditService,
):
self.workflow_repository = workflow_repository
self.profile_repository = profile_repository
self.audit_service = audit_service
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(),
)
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 and payload["status"] not in WORKFLOW_STATUSES:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"unsupported workflow status",
{"field": "status", "allowed": sorted(WORKFLOW_STATUSES)},
)
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(),
)
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(),
)
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 and payload["status"] not in NODE_STATUSES:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"unsupported node status",
{"field": "status", "allowed": sorted(NODE_STATUSES)},
)
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(),
)
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 _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 new_workflow_id() -> str:
return f"workflow_{uuid4().hex}"
def new_node_id() -> str:
return f"node_{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 []