463 行
19 KiB
Python
463 行
19 KiB
Python
"""Atomic persistence for sealed character profile cards."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any
|
|
|
|
from backend.dto.common import ApiError, ErrorCode
|
|
from backend.dto.profile_card_dto import CharacterProfileCard, CharacterProfileCardAsset
|
|
from database.db_helper import Database
|
|
from engines.character_flow import canonical_gradual_node_key
|
|
|
|
|
|
CARD_COLUMNS = """
|
|
card_id, profile_id, workflow_id, branch_name, version, status,
|
|
persona_document, idempotency_key, metadata_json, created_at, updated_at
|
|
"""
|
|
|
|
ASSET_COLUMNS = """
|
|
asset_id, card_id, asset_role, image_id, image_uri, metadata_json, created_at
|
|
"""
|
|
|
|
PROFILE_CARD_ASSET_ROLES = ("avatar", "persona_image", "standing", "pv")
|
|
PROFILE_CARD_ROLE_STAGES: dict[str, frozenset[str]] = {
|
|
"avatar": frozenset({"headshot"}),
|
|
"persona_image": frozenset({"turnaround", "design_sheet"}),
|
|
"standing": frozenset({"full_body"}),
|
|
"pv": frozenset({"style_lock"}),
|
|
}
|
|
|
|
|
|
class ProfileCardRepository:
|
|
def __init__(self, database: Database):
|
|
self.database = database
|
|
|
|
@property
|
|
def placeholder(self) -> str:
|
|
return self.database._placeholder
|
|
|
|
def get(self, card_id: str) -> CharacterProfileCard | None:
|
|
conn = self.database.connect()
|
|
try:
|
|
row = conn.execute(
|
|
f"SELECT {CARD_COLUMNS} FROM character_profile_cards WHERE card_id = {self.placeholder}",
|
|
(card_id,),
|
|
).fetchone()
|
|
if row is None:
|
|
return None
|
|
assets = conn.execute(
|
|
f"SELECT {ASSET_COLUMNS} FROM character_profile_card_assets "
|
|
f"WHERE card_id = {self.placeholder} ORDER BY created_at, asset_role",
|
|
(card_id,),
|
|
).fetchall()
|
|
finally:
|
|
conn.close()
|
|
return _row_to_card(row, assets)
|
|
|
|
def get_by_idempotency_key(self, idempotency_key: str) -> CharacterProfileCard | None:
|
|
conn = self.database.connect()
|
|
try:
|
|
row = conn.execute(
|
|
f"SELECT card_id FROM character_profile_cards WHERE idempotency_key = {self.placeholder}",
|
|
(idempotency_key,),
|
|
).fetchone()
|
|
finally:
|
|
conn.close()
|
|
return self.get(str(row["card_id"])) if row else None
|
|
|
|
def list_by_profile(self, profile_id: str) -> list[CharacterProfileCard]:
|
|
conn = self.database.connect()
|
|
try:
|
|
rows = conn.execute(
|
|
f"SELECT card_id FROM character_profile_cards WHERE profile_id = {self.placeholder} "
|
|
"ORDER BY version DESC, created_at DESC",
|
|
(profile_id,),
|
|
).fetchall()
|
|
finally:
|
|
conn.close()
|
|
return [card for row in rows if (card := self.get(str(row["card_id"]))) is not None]
|
|
|
|
def finalize(self, payload: dict[str, Any]) -> CharacterProfileCard:
|
|
placeholder = self.placeholder
|
|
conn = self.database.connect()
|
|
result_card_id = str(payload["card_id"])
|
|
try:
|
|
if self.database.backend == "sqlite":
|
|
conn.execute("BEGIN IMMEDIATE")
|
|
else:
|
|
# Serialize per-profile version allocation and the workflow
|
|
# archive transition on PostgreSQL as one finalization unit.
|
|
conn.execute(
|
|
f"SELECT profile_id FROM character_profiles WHERE profile_id = {placeholder} FOR UPDATE",
|
|
(payload["profile_id"],),
|
|
).fetchone()
|
|
if payload.get("idempotency_key"):
|
|
existing = conn.execute(
|
|
f"SELECT card_id, workflow_id FROM character_profile_cards WHERE idempotency_key = {placeholder}",
|
|
(payload["idempotency_key"],),
|
|
).fetchone()
|
|
if existing:
|
|
if str(existing["workflow_id"]) != str(payload["workflow_id"]):
|
|
raise ApiError(
|
|
ErrorCode.VALIDATION_FAILED,
|
|
"profile-card idempotency key belongs to another workflow",
|
|
{
|
|
"idempotency_key": payload["idempotency_key"],
|
|
"workflow_id": payload["workflow_id"],
|
|
"existing_workflow_id": str(existing["workflow_id"]),
|
|
},
|
|
)
|
|
result_card_id = str(existing["card_id"])
|
|
else:
|
|
self._finalize_new(conn, payload)
|
|
else:
|
|
self._finalize_new(conn, payload)
|
|
conn.commit()
|
|
except Exception:
|
|
rollback = getattr(conn, "rollback", None)
|
|
if callable(rollback):
|
|
rollback()
|
|
raise
|
|
finally:
|
|
try:
|
|
conn.close()
|
|
except Exception:
|
|
pass
|
|
card = self.get(result_card_id)
|
|
if card is None:
|
|
raise RuntimeError("profile card was finalized but could not be read")
|
|
return card
|
|
|
|
def _finalize_new(self, conn, payload: dict[str, Any]) -> None:
|
|
placeholder = self.placeholder
|
|
validated = _validate_finalization_state(conn, placeholder, payload)
|
|
version_row = conn.execute(
|
|
f"SELECT MAX(version) AS latest FROM character_profile_cards WHERE profile_id = {placeholder}",
|
|
(payload["profile_id"],),
|
|
).fetchone()
|
|
version = int(version_row["latest"] or 0) + 1 if version_row else 1
|
|
assets = validated["assets"]
|
|
workflow_metadata = validated["workflow_metadata"]
|
|
profile_metadata = validated["profile_metadata"]
|
|
|
|
conn.execute(
|
|
f"""
|
|
INSERT INTO character_profile_cards (
|
|
card_id, profile_id, workflow_id, branch_name, version,
|
|
status, persona_document, idempotency_key, metadata_json
|
|
) VALUES (
|
|
{placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder},
|
|
{placeholder}, {placeholder}, {placeholder}, {placeholder}
|
|
)
|
|
""",
|
|
(
|
|
payload["card_id"],
|
|
payload["profile_id"],
|
|
payload["workflow_id"],
|
|
payload["branch_name"],
|
|
version,
|
|
payload.get("status", "sealed"),
|
|
payload["persona_document"],
|
|
payload.get("idempotency_key"),
|
|
_json(payload.get("metadata")),
|
|
),
|
|
)
|
|
for asset in assets:
|
|
conn.execute(
|
|
f"""
|
|
INSERT INTO character_profile_card_assets (
|
|
asset_id, card_id, asset_role, image_id, image_uri, metadata_json
|
|
) VALUES (
|
|
{placeholder}, {placeholder}, {placeholder},
|
|
{placeholder}, {placeholder}, {placeholder}
|
|
)
|
|
""",
|
|
(
|
|
asset["asset_id"],
|
|
payload["card_id"],
|
|
asset["asset_role"],
|
|
asset["image_id"],
|
|
asset["image_uri"],
|
|
_json(asset.get("metadata")),
|
|
),
|
|
)
|
|
|
|
conn.execute(
|
|
f"""
|
|
UPDATE character_profiles
|
|
SET avatar_image_uri = {placeholder}, metadata_json = {placeholder}, updated_at = CURRENT_TIMESTAMP
|
|
WHERE profile_id = {placeholder}
|
|
""",
|
|
(
|
|
validated["avatar_image_uri"],
|
|
_json(
|
|
{
|
|
**profile_metadata,
|
|
"profile_card_id": payload["card_id"],
|
|
"profile_card_version": version,
|
|
"profile_category": "profile_card",
|
|
}
|
|
),
|
|
payload["profile_id"],
|
|
),
|
|
)
|
|
conn.execute(
|
|
f"""
|
|
UPDATE profile_workflows
|
|
SET status = 'archived', current_node_id = {placeholder}, metadata_json = {placeholder},
|
|
updated_at = CURRENT_TIMESTAMP
|
|
WHERE workflow_id = {placeholder} AND current_branch = {placeholder}
|
|
""",
|
|
(
|
|
payload["profile_card_node_id"],
|
|
_json(
|
|
{
|
|
**workflow_metadata,
|
|
"profile_card_id": payload["card_id"],
|
|
"profile_card_version": version,
|
|
"profile_card_finalized": True,
|
|
"profile_card_asset_ids": [asset["asset_id"] for asset in assets],
|
|
}
|
|
),
|
|
payload["workflow_id"],
|
|
payload["branch_name"],
|
|
),
|
|
)
|
|
conn.execute(
|
|
f"""
|
|
UPDATE workflow_nodes
|
|
SET status = 'completed', updated_at = CURRENT_TIMESTAMP
|
|
WHERE node_id = {placeholder} AND workflow_id = {placeholder} AND branch_name = {placeholder}
|
|
""",
|
|
(payload["profile_card_node_id"], payload["workflow_id"], payload["branch_name"]),
|
|
)
|
|
conn.execute(
|
|
f"""
|
|
INSERT INTO workflow_history (
|
|
history_id, profile_id, workflow_id, node_id, image_id,
|
|
branch_name, action, title, prompt, metadata_json
|
|
) VALUES (
|
|
{placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder},
|
|
{placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}
|
|
)
|
|
""",
|
|
(
|
|
payload["history_id"],
|
|
payload["profile_id"],
|
|
payload["workflow_id"],
|
|
payload["profile_card_node_id"],
|
|
validated["avatar_image_id"],
|
|
payload["branch_name"],
|
|
"profile_card_finalized",
|
|
f"{payload['title_prefix']} v{version}",
|
|
payload["persona_document"],
|
|
_json(
|
|
{
|
|
"source": "profile_card_finalize",
|
|
"card_id": payload["card_id"],
|
|
"card_version": version,
|
|
"asset_roles": [asset["asset_role"] for asset in assets],
|
|
}
|
|
),
|
|
),
|
|
)
|
|
|
|
def next_version(self, profile_id: str) -> int:
|
|
conn = self.database.connect()
|
|
try:
|
|
row = conn.execute(
|
|
f"SELECT MAX(version) AS latest FROM character_profile_cards WHERE profile_id = {self.placeholder}",
|
|
(profile_id,),
|
|
).fetchone()
|
|
finally:
|
|
conn.close()
|
|
return int(row["latest"] or 0) + 1 if row else 1
|
|
|
|
|
|
def _validate_finalization_state(conn, placeholder: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
workflow = conn.execute(
|
|
f"""
|
|
SELECT profile_id, workflow_type, status, current_branch, metadata_json
|
|
FROM profile_workflows
|
|
WHERE workflow_id = {placeholder}
|
|
""",
|
|
(payload["workflow_id"],),
|
|
).fetchone()
|
|
if workflow is None:
|
|
raise _validation("workflow not found", workflow_id=payload["workflow_id"])
|
|
if str(workflow["profile_id"]) != str(payload["profile_id"]):
|
|
raise _validation("profile-card workflow/profile ownership changed", workflow_id=payload["workflow_id"])
|
|
if str(workflow["workflow_type"]) != "character_gradual":
|
|
raise _validation("only a detailed character workflow can create a profile card")
|
|
if str(workflow["status"]) in {"cancelled", "archived"}:
|
|
raise _validation("workflow cannot be finalized from its current status", status=str(workflow["status"]))
|
|
active_branch = str(workflow["current_branch"] or "main")
|
|
if active_branch != str(payload["branch_name"]):
|
|
raise _validation(
|
|
"workflow branch changed before profile-card finalization",
|
|
expected_branch=payload["branch_name"],
|
|
active_branch=active_branch,
|
|
)
|
|
|
|
card_node = conn.execute(
|
|
f"""
|
|
SELECT node_key, sort_order, status
|
|
FROM workflow_nodes
|
|
WHERE node_id = {placeholder} AND workflow_id = {placeholder} AND branch_name = {placeholder}
|
|
""",
|
|
(payload["profile_card_node_id"], payload["workflow_id"], active_branch),
|
|
).fetchone()
|
|
if card_node is None or canonical_gradual_node_key(str(card_node["node_key"])) != "profile_card":
|
|
raise _validation(
|
|
"workflow does not contain a valid profile-card node in the active branch",
|
|
node_id=payload["profile_card_node_id"],
|
|
active_branch=active_branch,
|
|
)
|
|
incomplete = conn.execute(
|
|
f"""
|
|
SELECT node_key
|
|
FROM workflow_nodes
|
|
WHERE workflow_id = {placeholder} AND branch_name = {placeholder}
|
|
AND sort_order < {placeholder}
|
|
AND status NOT IN ('selected', 'skipped', 'completed')
|
|
ORDER BY sort_order, node_id
|
|
""",
|
|
(payload["workflow_id"], active_branch, int(card_node["sort_order"] or 0)),
|
|
).fetchall()
|
|
if incomplete:
|
|
raise _validation(
|
|
"workflow stages must be completed before creating a profile card",
|
|
incomplete_node_keys=[str(row["node_key"]) for row in incomplete],
|
|
)
|
|
|
|
profile = conn.execute(
|
|
f"SELECT metadata_json FROM character_profiles WHERE profile_id = {placeholder}",
|
|
(payload["profile_id"],),
|
|
).fetchone()
|
|
if profile is None:
|
|
raise _validation("profile not found", profile_id=payload["profile_id"])
|
|
|
|
assets = payload.get("assets") if isinstance(payload.get("assets"), list) else []
|
|
by_role = {str(asset.get("asset_role")): dict(asset) for asset in assets if isinstance(asset, dict)}
|
|
missing_roles = [role for role in PROFILE_CARD_ASSET_ROLES if role not in by_role]
|
|
if missing_roles:
|
|
raise _validation(
|
|
"profile-card assets are incomplete",
|
|
required_roles=list(PROFILE_CARD_ASSET_ROLES),
|
|
missing_roles=missing_roles,
|
|
)
|
|
image_ids = [str(by_role[role].get("image_id") or "") for role in PROFILE_CARD_ASSET_ROLES]
|
|
if len(set(image_ids)) != len(image_ids):
|
|
raise _validation("each profile-card asset role must use a distinct confirmed image")
|
|
|
|
validated_assets: list[dict[str, Any]] = []
|
|
avatar_image_id = ""
|
|
avatar_image_uri = ""
|
|
for role in PROFILE_CARD_ASSET_ROLES:
|
|
asset = by_role[role]
|
|
image_id = str(asset.get("image_id") or "")
|
|
row = conn.execute(
|
|
f"""
|
|
SELECT image.profile_id, image.workflow_id, image.node_id, image.image_uri,
|
|
image.is_selected, image.is_archived, image.metadata_json,
|
|
node.node_key, node.branch_name, node.selected_image_id
|
|
FROM generation_images AS image
|
|
JOIN workflow_nodes AS node ON node.node_id = image.node_id
|
|
WHERE image.image_id = {placeholder}
|
|
""",
|
|
(image_id,),
|
|
).fetchone()
|
|
if row is None:
|
|
raise _validation("profile-card asset image not found", asset_role=role, image_id=image_id)
|
|
if str(row["profile_id"] or "") != str(payload["profile_id"]):
|
|
raise _validation("profile-card asset belongs to another profile", asset_role=role, image_id=image_id)
|
|
if str(row["workflow_id"] or "") != str(payload["workflow_id"]):
|
|
raise _validation("profile-card asset belongs to another workflow", asset_role=role, image_id=image_id)
|
|
if str(row["branch_name"] or "main") != active_branch:
|
|
raise _validation(
|
|
"profile-card asset belongs to another branch",
|
|
asset_role=role,
|
|
image_id=image_id,
|
|
active_branch=active_branch,
|
|
)
|
|
metadata = _json_load(row["metadata_json"])
|
|
if bool(row["is_archived"]) or metadata.get("quarantined") or metadata.get("gallery_visibility") == "restricted":
|
|
raise _validation("profile-card asset is archived or restricted", asset_role=role, image_id=image_id)
|
|
if not bool(row["is_selected"]) and str(row["selected_image_id"] or "") != image_id:
|
|
raise _validation("profile-card asset is not a confirmed candidate", asset_role=role, image_id=image_id)
|
|
source_stage = _profile_card_stage_key(str(row["node_key"] or ""))
|
|
if source_stage not in PROFILE_CARD_ROLE_STAGES[role]:
|
|
raise _validation(
|
|
"profile-card asset comes from an incompatible workflow stage",
|
|
asset_role=role,
|
|
image_id=image_id,
|
|
source_stage=source_stage,
|
|
allowed_stages=sorted(PROFILE_CARD_ROLE_STAGES[role]),
|
|
)
|
|
asset["image_uri"] = str(row["image_uri"])
|
|
asset_metadata = asset.get("metadata") if isinstance(asset.get("metadata"), dict) else {}
|
|
asset["metadata"] = {
|
|
**asset_metadata,
|
|
"source_node_id": str(row["node_id"]),
|
|
"source_node_key": str(row["node_key"]),
|
|
"source_stage": source_stage,
|
|
"source_branch": active_branch,
|
|
}
|
|
validated_assets.append(asset)
|
|
if role == "avatar":
|
|
avatar_image_id = image_id
|
|
avatar_image_uri = str(row["image_uri"])
|
|
|
|
return {
|
|
"assets": validated_assets,
|
|
"avatar_image_id": avatar_image_id,
|
|
"avatar_image_uri": avatar_image_uri,
|
|
"profile_metadata": _json_load(profile["metadata_json"]),
|
|
"workflow_metadata": _json_load(workflow["metadata_json"]),
|
|
}
|
|
|
|
|
|
def _profile_card_stage_key(node_key: str | None) -> str:
|
|
canonical = canonical_gradual_node_key(node_key)
|
|
return "style_lock" if canonical in {"style_lock", "hires_fix"} else canonical
|
|
|
|
|
|
def _validation(message: str, **details: Any) -> ApiError:
|
|
return ApiError(ErrorCode.VALIDATION_FAILED, message, details)
|
|
|
|
|
|
def _row_to_card(row, asset_rows) -> CharacterProfileCard:
|
|
return CharacterProfileCard(
|
|
card_id=str(row["card_id"]),
|
|
profile_id=str(row["profile_id"]),
|
|
workflow_id=str(row["workflow_id"]),
|
|
branch_name=str(row["branch_name"] or "main"),
|
|
version=int(row["version"] or 1),
|
|
status=str(row["status"]),
|
|
persona_document=str(row["persona_document"]),
|
|
idempotency_key=row["idempotency_key"],
|
|
metadata=_json_load(row["metadata_json"]),
|
|
created_at=str(row["created_at"]),
|
|
updated_at=str(row["updated_at"]),
|
|
assets=tuple(
|
|
CharacterProfileCardAsset(
|
|
asset_id=str(asset["asset_id"]),
|
|
card_id=str(asset["card_id"]),
|
|
asset_role=str(asset["asset_role"]),
|
|
image_id=str(asset["image_id"]),
|
|
image_uri=str(asset["image_uri"]),
|
|
metadata=_json_load(asset["metadata_json"]),
|
|
created_at=str(asset["created_at"]),
|
|
)
|
|
for asset in asset_rows
|
|
),
|
|
)
|
|
|
|
|
|
def _json(value: Any) -> str:
|
|
return json.dumps(value or {}, ensure_ascii=False, sort_keys=True)
|
|
|
|
|
|
def _json_load(value: str | None) -> dict[str, Any]:
|
|
return json.loads(value) if value else {}
|