476 lines
19 KiB
Python
476 lines
19 KiB
Python
"""编辑命令:真实会话复核、CAS、资源引用与幂等回执在同一事务提交。"""
|
||
|
||
from copy import deepcopy
|
||
from math import ceil
|
||
from types import SimpleNamespace
|
||
from sqlalchemy import select, delete
|
||
from app.models import WorkflowDraft, WorkflowRun, WorkflowStep, Asset, AssetReference, User, utcnow
|
||
from app.core.errors import fail
|
||
from app.core.maintenance import require_writable
|
||
from app.domain.editors import (
|
||
validate_manifest,
|
||
manifest_from_draft,
|
||
editor_issues,
|
||
collect_manifest_asset_ids,
|
||
editing_mode,
|
||
MODE_CAPABILITIES,
|
||
invalidate_join_anchors,
|
||
)
|
||
from app.services.auth import require_session_user
|
||
from app.services.snapshots import owned, asset_dto, snapshot_run
|
||
from app.services.submissions import accept_submission, request_payload
|
||
|
||
|
||
async def sync_editor_refs(session, draft, manifest):
|
||
assets = {}
|
||
for id in sorted(collect_manifest_asset_ids(manifest)):
|
||
asset = await session.scalar(
|
||
select(Asset)
|
||
.where(
|
||
Asset.id == id,
|
||
Asset.owner_id == draft.owner_id,
|
||
Asset.library_scope == "private",
|
||
Asset.ready.is_(True),
|
||
Asset.deleted_at.is_(None),
|
||
)
|
||
.with_for_update()
|
||
)
|
||
if not asset:
|
||
fail(404, "asset_not_found", "素材不存在或不可访问")
|
||
assets[id] = asset
|
||
for key, b in manifest["bindings"].items():
|
||
a = assets[b["asset_id"]]
|
||
if a.kind != b["kind"]:
|
||
fail(422, "wrong_asset_kind", "绑定素材类型不正确")
|
||
b["sha256"] = a.sha256
|
||
if a.duration_seconds is not None:
|
||
b["duration_seconds"] = a.duration_seconds
|
||
b["duration_frames"] = (
|
||
ceil(a.duration_seconds * 24)
|
||
if a.kind == "audio"
|
||
else round(a.duration_seconds * 24)
|
||
)
|
||
|
||
def image_refs(value):
|
||
if isinstance(value, dict):
|
||
for key, item in value.items():
|
||
if key == "image_asset_id" and item:
|
||
yield item
|
||
elif key == "reference_asset_ids":
|
||
yield from item
|
||
else:
|
||
yield from image_refs(item)
|
||
elif isinstance(value, list):
|
||
for item in value:
|
||
yield from image_refs(item)
|
||
|
||
if any(assets[id].kind != "image" for id in image_refs(manifest["spec"])):
|
||
fail(422, "wrong_asset_kind", "视觉参考必须为图片素材")
|
||
track = manifest["audio"].get("track")
|
||
if track and assets[track["asset_id"]].kind != "audio":
|
||
fail(422, "wrong_asset_kind", "音轨需要音频素材")
|
||
for layer in manifest["audio"].get("layers", []):
|
||
if assets[layer["asset_id"]].kind != "audio":
|
||
fail(422, "wrong_asset_kind", "背景音乐和音效需要音频素材")
|
||
# 独立草稿引用不能依赖旧 Run 的存活。
|
||
await session.execute(
|
||
delete(AssetReference).where(
|
||
AssetReference.owner_id == draft.owner_id,
|
||
AssetReference.ref_kind == "draft",
|
||
AssetReference.ref_id == draft.id,
|
||
)
|
||
)
|
||
for id in assets:
|
||
session.add(
|
||
AssetReference(owner_id=draft.owner_id, asset_id=id, ref_kind="draft", ref_id=draft.id)
|
||
)
|
||
return assets
|
||
|
||
|
||
async def load_manifest(session, draft):
|
||
m = manifest_from_draft(draft)
|
||
if draft.editor_manifest or draft.kind != "story_v3":
|
||
return m
|
||
from app.services.stories.common import selections, current_hash, selection_source_kind
|
||
|
||
latest = await selections(session, draft)
|
||
for row in latest.values():
|
||
if not row.asset_id or row.shot_id not in m["shot_ids"]:
|
||
continue
|
||
a = await session.get(Asset, row.asset_id)
|
||
if (
|
||
not a
|
||
or a.owner_id != draft.owner_id
|
||
or a.deleted_at is not None
|
||
or not a.ready
|
||
or a.library_scope != "private"
|
||
):
|
||
continue
|
||
source_kind = await selection_source_kind(session, row)
|
||
if row.context_hash != await current_hash(
|
||
session,
|
||
draft,
|
||
row.shot_id,
|
||
row.kind,
|
||
latest=latest,
|
||
source_kind=source_kind,
|
||
source_sha256=a.sha256,
|
||
):
|
||
continue
|
||
expected = "image" if row.kind in {"frame", "end_frame", "join_anchor"} else "video"
|
||
if a.kind != expected or row.decision_json.get("asset_sha256") != a.sha256:
|
||
continue
|
||
m["bindings"][row.kind + ":" + row.shot_id] = dict(
|
||
asset_id=a.id, sha256=a.sha256, kind=a.kind, source="manual", locked=True
|
||
)
|
||
return m
|
||
|
||
|
||
async def dto(session, draft, manifest=None):
|
||
m = manifest if manifest is not None else await load_manifest(session, draft)
|
||
ids = collect_manifest_asset_ids(m)
|
||
assets = (
|
||
(
|
||
await session.scalars(
|
||
select(Asset).where(
|
||
Asset.id.in_(ids), Asset.owner_id == draft.owner_id, Asset.deleted_at.is_(None)
|
||
)
|
||
)
|
||
).all()
|
||
if ids
|
||
else []
|
||
)
|
||
return dict(
|
||
draft_id=draft.id,
|
||
editing_mode=editing_mode(draft),
|
||
capabilities={
|
||
**MODE_CAPABILITIES,
|
||
"mode_switch": draft.kind == "story_v3",
|
||
"manual": draft.kind == "story_v3",
|
||
},
|
||
name=draft.name,
|
||
version=draft.version,
|
||
revision=draft.revision,
|
||
manifest=m,
|
||
issues=editor_issues(m),
|
||
assets=[asset_dto(a) for a in assets],
|
||
)
|
||
|
||
|
||
def check_version(draft, version):
|
||
if draft.version != version:
|
||
fail(409, "draft_version_conflict", "草稿已更新,请刷新版本")
|
||
|
||
|
||
async def write_manifest(session, draft, manifest, settings=None):
|
||
m = validate_manifest(manifest)
|
||
if settings:
|
||
from app.core.runtime_policy import read_runtime_policy
|
||
|
||
policy = read_runtime_policy(settings)
|
||
if policy.get("configuration_error"):
|
||
fail(503, "runtime_policy_unavailable", "运行配置无效")
|
||
if len(m["shot_ids"]) > policy["workflow_max_shots"]:
|
||
fail(422, "workflow_shot_limit", "镜头数量超过当前限制")
|
||
if (m["source_kind"] == "story") != (draft.kind == "story_v3"):
|
||
fail(422, "invalid_editor_manifest", "草稿类型不能改变")
|
||
# 来源只作谱系,允许已经归档的同草稿历史,绝不能跨owner/draft扩大可读范围。
|
||
if m.get("base_run_id"):
|
||
source = await session.scalar(
|
||
select(WorkflowRun.id).where(
|
||
WorkflowRun.id == m["base_run_id"],
|
||
WorkflowRun.owner_id == draft.owner_id,
|
||
WorkflowRun.draft_id == draft.id,
|
||
)
|
||
)
|
||
if not source:
|
||
fail(404, "resource_not_found", "来源运行不存在或不属于此草稿")
|
||
await sync_editor_refs(session, draft, m)
|
||
draft.editor_manifest = m
|
||
draft.spec = deepcopy(m["spec"])
|
||
draft.version += 1
|
||
draft.revision += 1
|
||
draft.updated_at = utcnow()
|
||
await session.flush()
|
||
from app.services.events import emit_asset
|
||
|
||
if draft.kind == "story_v3":
|
||
from app.services.stories.common import story_dto
|
||
|
||
emit_asset(
|
||
session, draft.owner_id, "story.updated", {"story": await story_dto(session, draft)}
|
||
)
|
||
else:
|
||
from app.services.snapshots import draft_dto
|
||
|
||
emit_asset(session, draft.owner_id, "draft.updated", {"draft": draft_dto(draft)})
|
||
|
||
|
||
async def get_editor(runtime, actor, draft_id):
|
||
async with runtime.db.session() as s:
|
||
d = await owned(s, WorkflowDraft, draft_id, actor.id)
|
||
return await dto(s, d)
|
||
|
||
|
||
def sanitize_bindings(manifest, old):
|
||
if manifest.get("schema_version") == 2:
|
||
for key, binding in list(manifest["bindings"].items()):
|
||
if not key.startswith("join_anchor:"):
|
||
continue
|
||
previous = old.get("bindings", {}).get(key, {})
|
||
if previous.get("asset_id") != binding["asset_id"] or previous.get(
|
||
"sha256"
|
||
) != binding.get("sha256"):
|
||
fail(422, "derived_binding_readonly", "实际接续锚点只能由服务端从选用视频生成")
|
||
invalidate_join_anchors(manifest, old)
|
||
for key, b in manifest["bindings"].items():
|
||
previous = old.get("bindings", {}).get(key, {})
|
||
if previous.get("asset_id") == b["asset_id"] and previous.get("sha256") == b["sha256"]:
|
||
manifest["bindings"][key] = deepcopy(previous)
|
||
manifest["bindings"][key]["locked"] = b.get("locked", False)
|
||
else:
|
||
for field in (
|
||
"input_hash",
|
||
"context_hash",
|
||
"source_run_id",
|
||
"source_job_id",
|
||
"generation_parameters",
|
||
"duration_seconds",
|
||
"duration_frames",
|
||
"sample_count",
|
||
"sample_rate",
|
||
"provenance",
|
||
):
|
||
b.pop(field, None)
|
||
b["source"] = "manual"
|
||
|
||
|
||
async def run_manifest(session, run):
|
||
if run.result_manifest:
|
||
return {**deepcopy(run.result_manifest), "base_run_id": run.id}
|
||
if run.plan_snapshot and run.plan_snapshot.get("manifest"):
|
||
return {**deepcopy(run.plan_snapshot["manifest"]), "base_run_id": run.id}
|
||
source = SimpleNamespace(
|
||
id=run.draft_id,
|
||
kind="story_v3" if run.spec_snapshot.get("schema_version") in (3, 4) else "three_shot",
|
||
spec=run.spec_snapshot,
|
||
editor_manifest=None,
|
||
)
|
||
m = manifest_from_draft(source)
|
||
m["base_run_id"] = run.id
|
||
for selection in run.spec_snapshot.get("render_inputs", {}).get("selections", []):
|
||
if selection.get("shot_id") not in m["shot_ids"]:
|
||
continue
|
||
a = await session.get(Asset, selection.get("asset_id"))
|
||
if not a or a.owner_id != run.owner_id or a.deleted_at is not None or not a.ready:
|
||
fail(404, "asset_not_found", "冻结运行素材不可访问")
|
||
kind = selection.get("kind")
|
||
prefix = "frame" if kind in {"frame", "image"} else "video"
|
||
m["bindings"][prefix + ":" + selection["shot_id"]] = dict(
|
||
asset_id=a.id, sha256=a.sha256, kind=a.kind, source="reused", source_run_id=run.id
|
||
)
|
||
# legacy 实际输出按冻结顺序恢复,不能读取当前草稿或选择。
|
||
steps = (await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id == run.id))).all()
|
||
from app.models import Job
|
||
|
||
for index, id in enumerate(m["shot_ids"]):
|
||
shot = m["spec"]["shots"][index]
|
||
step = next((x for x in steps if x.step_key == shot.get("key", f"shot_{index + 1}")), None)
|
||
if step and step.selected_job_id:
|
||
job = await session.get(Job, step.selected_job_id)
|
||
if job and job.owner_id == run.owner_id:
|
||
from app.services.workflows import selected_output
|
||
|
||
a = await selected_output(session, job.id, run.owner_id)
|
||
if a:
|
||
m["bindings"]["video:" + id] = dict(
|
||
asset_id=a.id,
|
||
sha256=a.sha256,
|
||
kind=a.kind,
|
||
source="reused",
|
||
source_run_id=run.id,
|
||
source_job_id=job.id,
|
||
)
|
||
return m
|
||
|
||
|
||
async def apply_run_result(session, run, settings):
|
||
if run.state != "succeeded" or not run.result_manifest or run.desired_state == "cancel":
|
||
return False
|
||
owner = await session.scalar(select(User).where(User.id == run.owner_id).with_for_update())
|
||
d = await session.scalar(
|
||
select(WorkflowDraft)
|
||
.where(
|
||
WorkflowDraft.id == run.draft_id,
|
||
WorkflowDraft.owner_id == run.owner_id,
|
||
WorkflowDraft.deleted_at.is_(None),
|
||
)
|
||
.with_for_update()
|
||
)
|
||
|
||
if (
|
||
not owner
|
||
or owner.disabled
|
||
or not d
|
||
or d.version != run.source_draft_version
|
||
or (d.editor_manifest and editing_mode(d) != "auto")
|
||
):
|
||
run.apply_state = "conflict"
|
||
return False
|
||
if run.output_goal == "film" and run.state == "succeeded" and run.current_output_asset_id:
|
||
d.current_run_id = run.id
|
||
run.result_manifest = {**deepcopy(run.result_manifest), "base_run_id": run.id}
|
||
await write_manifest(session, d, run.result_manifest, settings)
|
||
run.apply_state = "applied"
|
||
return True
|
||
|
||
|
||
async def command(runtime, actor, draft_id, body, key, operation):
|
||
require_writable(runtime.settings)
|
||
async with runtime.db.session() as s:
|
||
await require_session_user(s, actor)
|
||
payload = request_payload(body)
|
||
# 可选改名为空时仍使用旧请求指纹,升级前已接纳的保存可以原幂等键重放。
|
||
if operation == "editor.save" and body.name is None:
|
||
payload.pop("name", None)
|
||
sub = await accept_submission(
|
||
s, actor.id, operation, key, 1, {"draft_id": draft_id, **payload}
|
||
)
|
||
d = await owned(s, WorkflowDraft, draft_id, actor.id)
|
||
from app.services.editor_modes import require_auto
|
||
|
||
require_auto(d)
|
||
if sub.resource_json:
|
||
if operation == "editor.run":
|
||
return await snapshot_run(s, actor.id, sub.resource_json["run_id"])
|
||
return await dto(s, d)
|
||
check_version(d, body.expected_version)
|
||
from app.services.editor_modes import require_auto
|
||
|
||
require_auto(d)
|
||
if not d.editor_manifest:
|
||
from app.services.editor_modes import assert_idle
|
||
|
||
await assert_idle(s, d)
|
||
if operation == "editor.save":
|
||
m = body.manifest.model_dump(mode="json")
|
||
if m["editing_mode"] != "auto":
|
||
fail(409, "editor_mode_conflict", "编辑模式只能通过切换命令修改")
|
||
m["editing_mode"] = "auto"
|
||
sanitize_bindings(m, await load_manifest(s, d))
|
||
if body.name is not None:
|
||
d.name = body.name
|
||
await write_manifest(s, d, m, runtime.settings)
|
||
elif operation in {"editor.from_run", "editor.apply"}:
|
||
r = await owned(s, WorkflowRun, body.run_id, actor.id)
|
||
if r.draft_id != d.id:
|
||
fail(404, "resource_not_found", "运行不属于此草稿")
|
||
if operation == "editor.apply":
|
||
if r.state != "succeeded" or not r.result_manifest:
|
||
fail(409, "run_result_unavailable", "运行尚无可应用结果")
|
||
if r.source_draft_version != d.version:
|
||
fail(409, "draft_version_conflict", "草稿已编辑,请显式恢复运行版本")
|
||
if operation == "editor.apply":
|
||
r.apply_state = "applied"
|
||
if r.output_goal == "film" and r.state == "succeeded" and r.current_output_asset_id:
|
||
d.current_run_id = r.id
|
||
restored = await run_manifest(s, r)
|
||
restored["editing_mode"] = "auto"
|
||
await write_manifest(s, d, restored, runtime.settings)
|
||
else:
|
||
from app.services.orchestration.editor_engine import start_editor_run
|
||
from app.adapters.provider.contracts import h3_tp2_available
|
||
from app.services.quotas import reserve_budget
|
||
|
||
await reserve_budget(s, actor.id, "editor.run", units=0, settings=runtime.settings)
|
||
r = await start_editor_run(
|
||
s,
|
||
d,
|
||
await load_manifest(s, d),
|
||
body,
|
||
runtime.settings,
|
||
tp2_capability=lambda: h3_tp2_available(runtime.provider, runtime.settings),
|
||
)
|
||
sub.resource_json = {"draft_id": d.id, "run_id": r.id}
|
||
await s.commit()
|
||
result = await snapshot_run(s, actor.id, r.id)
|
||
from app.services.workflows import wake
|
||
|
||
wake(runtime)
|
||
return result
|
||
sub.resource_json = {"draft_id": d.id}
|
||
result = await dto(s, d)
|
||
await s.commit()
|
||
return result
|
||
|
||
|
||
async def save_editor(runtime, actor, draft_id, body, key):
|
||
return await command(runtime, actor, draft_id, body, key, "editor.save")
|
||
|
||
|
||
async def from_run(runtime, actor, draft_id, body, key):
|
||
return await command(runtime, actor, draft_id, body, key, "editor.from_run")
|
||
|
||
|
||
async def apply_editor(runtime, actor, draft_id, body, key):
|
||
return await command(runtime, actor, draft_id, body, key, "editor.apply")
|
||
|
||
|
||
async def start_editor_request(runtime, actor, draft_id, body, key):
|
||
# 外部健康探测不占业务锁;接纳事务仍重新校验会话、草稿版本及计划。
|
||
from app.models import Submission
|
||
|
||
async with runtime.db.session() as s:
|
||
await require_session_user(s, actor)
|
||
previous = await s.scalar(
|
||
select(Submission).where(
|
||
Submission.owner_id == actor.id,
|
||
Submission.operation == "editor.run",
|
||
Submission.key == key,
|
||
)
|
||
)
|
||
d = await owned(s, WorkflowDraft, draft_id, actor.id)
|
||
from app.services.editor_modes import require_auto
|
||
|
||
require_auto(d)
|
||
m = await load_manifest(s, d)
|
||
replay = previous is not None and bool(previous.resource_json)
|
||
needs_speech = (
|
||
body.output_goal == "film" or any(t.startswith("audio:") for t in body.targets)
|
||
) and m["audio"]["mode"] == "generated_narration"
|
||
if needs_speech and not replay:
|
||
if not getattr(runtime.settings, "tts_base_url", "") or not getattr(
|
||
runtime.settings, "tts_voices", ()
|
||
):
|
||
fail(503, "capability_unavailable", "中文配音服务尚未配置")
|
||
probe = getattr(runtime.provider, "speech_health", None)
|
||
if probe:
|
||
try:
|
||
health = await probe()
|
||
except Exception:
|
||
fail(503, "capability_unavailable", "配音服务暂不可用")
|
||
if not health.get("configured") or not health.get("reachable"):
|
||
fail(503, "capability_unavailable", "配音服务暂不可用")
|
||
return await command(runtime, actor, draft_id, body, key, "editor.run")
|
||
|
||
|
||
async def plan_editor_request(runtime, actor, draft_id, body):
|
||
async with runtime.db.session() as s:
|
||
await require_session_user(s, actor)
|
||
d = await owned(s, WorkflowDraft, draft_id, actor.id)
|
||
check_version(d, body.expected_version)
|
||
from app.services.editor_modes import require_auto
|
||
|
||
require_auto(d)
|
||
from app.services.orchestration.editor_engine import plan_editor
|
||
from app.adapters.provider.contracts import h3_tp2_available
|
||
|
||
return await plan_editor(
|
||
s,
|
||
d,
|
||
await load_manifest(s, d),
|
||
body,
|
||
runtime.settings,
|
||
tp2_capability=lambda: h3_tp2_available(runtime.provider, runtime.settings),
|
||
)
|