astrbot_plugin_imagestudio/core/branch_state.py

94 行
3.2 KiB
Python

"""Branch-scoped workflow metadata shaping.
These helpers are pure dictionary transforms over a workflow's ``metadata``
column -- no repository, no service, no I/O. They live in ``core`` because both
the service layer and the repositories legitimately need them: the round and
cross-review repositories must read and merge branch state while writing rows,
and importing ``backend.services.branch_lineage_service`` to do that inverted
the dependency direction (data layer -> service layer) and dragged
``WorkflowRepository`` into its own callers' import graph.
"""
from __future__ import annotations
from copy import deepcopy
from typing import Any
BRANCH_STATE_FIELDS = frozenset(
{
"character_execution",
"material_binding_schema_version",
"material_binding_source_node_id",
"material_binding_updated_at",
"material_bindings",
"prompt_plan_schema_version",
"prompt_plan_source_node_id",
"prompt_plan_updated_at",
"prompt_plan",
"prompt_matrix",
"stage_input_schema_version",
"stage_inputs",
"restoration_input_schema_version",
"restoration_inputs",
"stage_review_handoffs",
"last_stage_review_confirmed_at",
"last_stage_review_node_id",
"last_stage_review_image_id",
"current_stage_input_image_id",
"final_archive_schema_version",
"final_archive_history_id",
"final_archive_image_ids",
"final_archive_node_id",
"final_archive_source_node_id",
"final_archive_completed_at",
}
)
def branch_state_for(metadata: dict[str, Any] | None, branch_name: str) -> dict[str, Any]:
"""Read branch state with a root-metadata fallback for pre-1.0.16 data."""
source = metadata if isinstance(metadata, dict) else {}
branch_states = source.get("branch_state")
if isinstance(branch_states, dict) and isinstance(branch_states.get(branch_name), dict):
return deepcopy(branch_states[branch_name])
return {
key: deepcopy(source[key])
for key in BRANCH_STATE_FIELDS
if key in source
}
def workflow_metadata_for_branch(metadata: dict[str, Any] | None, branch_name: str) -> dict[str, Any]:
"""Return the legacy root projection overlaid with one branch's state."""
result = deepcopy(metadata) if isinstance(metadata, dict) else {}
state = branch_state_for(result, branch_name)
for key in BRANCH_STATE_FIELDS:
result.pop(key, None)
result.update(state)
return result
def with_branch_state(
metadata: dict[str, Any] | None,
branch_name: str,
patch: dict[str, Any],
*,
activate: bool,
) -> dict[str, Any]:
"""Merge one branch state while preserving every sibling branch."""
result = deepcopy(metadata) if isinstance(metadata, dict) else {}
states = deepcopy(result.get("branch_state")) if isinstance(result.get("branch_state"), dict) else {}
state = branch_state_for(result, branch_name)
state.update({key: deepcopy(value) for key, value in patch.items() if key in BRANCH_STATE_FIELDS})
states[branch_name] = state
result["branch_state"] = states
if activate:
for key in BRANCH_STATE_FIELDS:
result.pop(key, None)
result.update(deepcopy(state))
return result