727 lines
27 KiB
Python
727 lines
27 KiB
Python
|
|
from app.services.folders import folder_filter
|
|||
|
|
from app.services.snapshots import draft_dto, owned, snapshot_run, page_rows
|
|||
|
|
from app.domain.tasks import RUN_TERMINAL
|
|||
|
|
import asyncio
|
|||
|
|
import hashlib
|
|||
|
|
import json
|
|||
|
|
from types import SimpleNamespace
|
|||
|
|
from fastapi import HTTPException
|
|||
|
|
from sqlalchemy import select, delete
|
|||
|
|
from app.core.security import Actor
|
|||
|
|
from app.adapters.storage import safe_file
|
|||
|
|
from app.core.errors import fail
|
|||
|
|
from app.services.events import emit_asset, emit_job
|
|||
|
|
from app.services.jobs import create_jobs
|
|||
|
|
from app.schemas.jobs import Submit
|
|||
|
|
from app.domain.tasks import TERMINAL, GPU_TYPES
|
|||
|
|
from app.models import Asset, Job, User, utcnow
|
|||
|
|
from app.services.submissions import accept_submission, request_payload
|
|||
|
|
from app.domain.timeline import WorkflowSpec, compile_timeline, generation_parameters_for_shot
|
|||
|
|
from app.core.runtime_policy import read_runtime_policy
|
|||
|
|
from app.models import WorkflowDraft, WorkflowRun, WorkflowStep, AssetReference, Execution
|
|||
|
|
from app.schemas.workflows import DraftCreate, DraftPatch, RunCreate, Control, Retry
|
|||
|
|
|
|||
|
|
"Owner scoped draft/run services. All helpers use the caller's transaction."
|
|||
|
|
|
|||
|
|
|
|||
|
|
def digest(value):
|
|||
|
|
return hashlib.sha256(
|
|||
|
|
json.dumps(
|
|||
|
|
value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
|
|||
|
|
).encode()
|
|||
|
|
).hexdigest()
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def emit_run(session, r, increment=True):
|
|||
|
|
if r.deleted_at is not None:
|
|||
|
|
return
|
|||
|
|
if increment:
|
|||
|
|
r.version += 1
|
|||
|
|
snap = await snapshot_run(session, r.owner_id, r.id)
|
|||
|
|
emit_asset(
|
|||
|
|
session, r.owner_id, "workflow.updated", {k: snap[k] for k in ("run", "steps", "jobs")}
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def validate_spec(session, owner_id, spec, settings):
|
|||
|
|
spec = spec if isinstance(spec, WorkflowSpec) else WorkflowSpec.model_validate(spec)
|
|||
|
|
policy = read_runtime_policy(settings)
|
|||
|
|
if policy.get("configuration_error"):
|
|||
|
|
fail(503, "runtime_policy_unavailable", "运行配置无效,请联系管理员")
|
|||
|
|
if len(spec.shots) > policy["workflow_max_shots"]:
|
|||
|
|
fail(
|
|||
|
|
422,
|
|||
|
|
"workflow_shot_limit",
|
|||
|
|
f"当前配置最多允许{policy['workflow_max_shots']}个镜头,可由管理员调整",
|
|||
|
|
)
|
|||
|
|
ids = [s.image_asset_id for s in spec.shots if s.image_asset_id]
|
|||
|
|
if spec.render.audio:
|
|||
|
|
ids.append(spec.render.audio.asset_id)
|
|||
|
|
assets = {}
|
|||
|
|
for id in sorted(set(ids)):
|
|||
|
|
a = await session.scalar(
|
|||
|
|
select(Asset)
|
|||
|
|
.where(
|
|||
|
|
Asset.id == id,
|
|||
|
|
Asset.owner_id == owner_id,
|
|||
|
|
Asset.library_scope == "private",
|
|||
|
|
Asset.deleted_at.is_(None),
|
|||
|
|
Asset.ready.is_(True),
|
|||
|
|
)
|
|||
|
|
.with_for_update()
|
|||
|
|
)
|
|||
|
|
if not a:
|
|||
|
|
fail(404, "asset_not_found", "Asset unavailable.")
|
|||
|
|
assets[id] = a
|
|||
|
|
for shot in spec.shots:
|
|||
|
|
if shot.image_asset_id and assets[shot.image_asset_id].kind != "image":
|
|||
|
|
fail(422, "wrong_asset_kind", "参考图需要图片")
|
|||
|
|
try:
|
|||
|
|
plan = compile_timeline(spec, assets)
|
|||
|
|
except ValueError:
|
|||
|
|
fail(422, "invalid_timeline", "音轨范围超出源素材")
|
|||
|
|
return (plan, assets)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def check_batch_capability(runtime, task_types=("video.generate",)):
|
|||
|
|
if not set(task_types) & GPU_TYPES:
|
|||
|
|
return
|
|||
|
|
provider = runtime.provider
|
|||
|
|
method = getattr(provider, "upstream_capabilities", None)
|
|||
|
|
if method is None and runtime.settings.mode == "test":
|
|||
|
|
return
|
|||
|
|
if method is None:
|
|||
|
|
fail(
|
|||
|
|
503, "upstream_protocol_incompatible", "Batch requires upstream scheduling protocol v2."
|
|||
|
|
)
|
|||
|
|
try:
|
|||
|
|
caps = await method()
|
|||
|
|
except Exception:
|
|||
|
|
fail(503, "upstream_protocol_incompatible", "Cannot verify upstream admission protocol.")
|
|||
|
|
if caps.get("protocol_version", 0) < 2 or not caps.get("admission_policy"):
|
|||
|
|
fail(
|
|||
|
|
503, "upstream_protocol_incompatible", "Batch requires upstream scheduling protocol v2."
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def verified_output(asset, settings):
|
|||
|
|
"""Reuse trusts the published bytes, not just the asset's database row."""
|
|||
|
|
|
|||
|
|
def verify():
|
|||
|
|
try:
|
|||
|
|
with safe_file(settings.asset_root, asset.storage_key) as source:
|
|||
|
|
h = hashlib.sha256()
|
|||
|
|
size = 0
|
|||
|
|
while chunk := source.read(1024 * 1024):
|
|||
|
|
size += len(chunk)
|
|||
|
|
h.update(chunk)
|
|||
|
|
return size == asset.size_bytes and h.hexdigest() == asset.sha256
|
|||
|
|
except (OSError, ValueError):
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
return await asyncio.to_thread(verify)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def create_run(
|
|||
|
|
session,
|
|||
|
|
owner_id,
|
|||
|
|
draft_id,
|
|||
|
|
expected_version,
|
|||
|
|
revision,
|
|||
|
|
mode="interactive",
|
|||
|
|
reuse_run_id=None,
|
|||
|
|
batch_id=None,
|
|||
|
|
batch_item_index=None,
|
|||
|
|
*,
|
|||
|
|
settings,
|
|||
|
|
output_folder_id=...,
|
|||
|
|
):
|
|||
|
|
await session.scalar(select(User).where(User.id == owner_id).with_for_update())
|
|||
|
|
from app.services.quotas import check_parent_capacity
|
|||
|
|
|
|||
|
|
await check_parent_capacity(session, settings, owner_id, "run")
|
|||
|
|
d = await owned(session, WorkflowDraft, draft_id, owner_id)
|
|||
|
|
if d.editor_manifest:
|
|||
|
|
fail(409, "editor_required", "请使用可编辑自动成片接口")
|
|||
|
|
if d.kind == "story_v3":
|
|||
|
|
fail(404, "resource_not_found", "请使用故事工作室接口")
|
|||
|
|
if d.version != expected_version or d.revision != revision:
|
|||
|
|
fail(409, "draft_version_conflict", "草稿已更新,请刷新版本")
|
|||
|
|
plan, assets = await validate_spec(session, owner_id, d.spec, settings)
|
|||
|
|
if mode == "interactive":
|
|||
|
|
active = await session.scalar(
|
|||
|
|
select(WorkflowRun.id).where(
|
|||
|
|
WorkflowRun.owner_id == owner_id,
|
|||
|
|
WorkflowRun.deleted_at.is_(None),
|
|||
|
|
WorkflowRun.execution_mode == "interactive",
|
|||
|
|
WorkflowRun.state.not_in(RUN_TERMINAL),
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
if active:
|
|||
|
|
fail(429, "quota_exceeded", "已有活动交互工作流")
|
|||
|
|
# 运行接受后冻结全部镜头参数;修改草稿不得改变旧运行或 retry 的生成时长。
|
|||
|
|
snapshot = {
|
|||
|
|
**plan.spec,
|
|||
|
|
"compiled": {
|
|||
|
|
"generation_parameters": plan.generation_parameters,
|
|||
|
|
"shot_generation_parameters": plan.shot_generation_parameters,
|
|||
|
|
"canvas": list(plan.canvas),
|
|||
|
|
"preset_version": "wan-three-shot-v1"
|
|||
|
|
if plan.spec["schema_version"] == 1
|
|||
|
|
else "wan-multi-shot-v2",
|
|||
|
|
},
|
|||
|
|
}
|
|||
|
|
from app.services.folders import owned_folder
|
|||
|
|
|
|||
|
|
if output_folder_id is ...:
|
|||
|
|
output_folder_id = d.folder_id
|
|||
|
|
if output_folder_id:
|
|||
|
|
await owned_folder(session, output_folder_id, owner_id, lock=True)
|
|||
|
|
r = WorkflowRun(
|
|||
|
|
folder_id=d.folder_id,
|
|||
|
|
output_folder_id=output_folder_id,
|
|||
|
|
owner_id=owner_id,
|
|||
|
|
draft_id=d.id,
|
|||
|
|
draft_revision=d.revision,
|
|||
|
|
spec_snapshot=snapshot,
|
|||
|
|
spec_hash=digest(snapshot),
|
|||
|
|
execution_mode=mode,
|
|||
|
|
batch_id=batch_id,
|
|||
|
|
batch_item_index=batch_item_index,
|
|||
|
|
)
|
|||
|
|
session.add(r)
|
|||
|
|
await session.flush()
|
|||
|
|
reuse = None
|
|||
|
|
if reuse_run_id:
|
|||
|
|
reuse = await owned(session, WorkflowRun, reuse_run_id, owner_id)
|
|||
|
|
for shot in plan.spec["shots"]:
|
|||
|
|
source = assets.get(shot.get("image_asset_id"))
|
|||
|
|
# 选用时长只影响裁剪;实际源长度在参数中参与哈希,15→10 秒不能复用旧源。
|
|||
|
|
generation_shot = {k: v for k, v in shot.items() if k != "duration_frames"}
|
|||
|
|
h = digest(
|
|||
|
|
{
|
|||
|
|
"shot": generation_shot,
|
|||
|
|
"generation_parameters": plan.shot_generation_parameters[shot["key"]],
|
|||
|
|
"source_sha256": source.sha256 if source else None,
|
|||
|
|
}
|
|||
|
|
)
|
|||
|
|
step = WorkflowStep(
|
|||
|
|
run_id=r.id,
|
|||
|
|
step_key=shot["key"],
|
|||
|
|
kind="video.generate",
|
|||
|
|
dependencies=[],
|
|||
|
|
semantic_input_hash=h,
|
|||
|
|
)
|
|||
|
|
if reuse:
|
|||
|
|
old = await session.scalar(
|
|||
|
|
select(WorkflowStep).where(
|
|||
|
|
WorkflowStep.run_id == reuse.id,
|
|||
|
|
WorkflowStep.step_key == shot["key"],
|
|||
|
|
WorkflowStep.semantic_input_hash == h,
|
|||
|
|
WorkflowStep.state == "succeeded",
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
if old and old.selected_job_id:
|
|||
|
|
job = await session.get(Job, old.selected_job_id)
|
|||
|
|
out = await selected_output(session, old.selected_job_id, owner_id)
|
|||
|
|
if (
|
|||
|
|
job
|
|||
|
|
and job.owner_id == owner_id
|
|||
|
|
and (job.deleted_at is None)
|
|||
|
|
and (job.state == "succeeded")
|
|||
|
|
and out
|
|||
|
|
and await verified_output(out, settings)
|
|||
|
|
):
|
|||
|
|
step.selected_job_id = job.id
|
|||
|
|
step.state = "succeeded"
|
|||
|
|
step.explicit_attempt = old.explicit_attempt
|
|||
|
|
assets[out.id] = out
|
|||
|
|
from app.services.folders import add_asset_folder
|
|||
|
|
|
|||
|
|
before = set(out.folder_ids)
|
|||
|
|
await add_asset_folder(session, out, r.output_folder_id, allow_missing=True)
|
|||
|
|
if out.ready and before != set(out.folder_ids):
|
|||
|
|
from app.services.snapshots import asset_dto
|
|||
|
|
|
|||
|
|
emit_asset(session, owner_id, "asset.updated", {"asset": asset_dto(out)})
|
|||
|
|
session.add(step)
|
|||
|
|
session.add(
|
|||
|
|
WorkflowStep(
|
|||
|
|
run_id=r.id,
|
|||
|
|
step_key="compose",
|
|||
|
|
kind="video.compose",
|
|||
|
|
dependencies=[shot["key"] for shot in plan.spec["shots"]],
|
|||
|
|
semantic_input_hash=digest(snapshot),
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
for a in assets.values():
|
|||
|
|
session.add(AssetReference(owner_id=owner_id, asset_id=a.id, ref_kind="run", ref_id=r.id))
|
|||
|
|
d.current_run_id = r.id
|
|||
|
|
d.version += 1
|
|||
|
|
d.updated_at = utcnow()
|
|||
|
|
await session.flush()
|
|||
|
|
emit_asset(session, owner_id, "draft.updated", {"draft": draft_dto(d)})
|
|||
|
|
await emit_run(session, r, False)
|
|||
|
|
return r
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def selected_output(session, job_id, owner_id=None):
|
|||
|
|
query = select(Asset).where(
|
|||
|
|
Asset.source_job_id == job_id,
|
|||
|
|
Asset.library_scope == "private",
|
|||
|
|
Asset.kind == "video",
|
|||
|
|
Asset.ready.is_(True),
|
|||
|
|
Asset.deleted_at.is_(None),
|
|||
|
|
)
|
|||
|
|
if owner_id is not None:
|
|||
|
|
query = query.where(Asset.owner_id == owner_id)
|
|||
|
|
return await session.scalar(query.order_by(Asset.source_output_index).with_for_update())
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def create_child(session, r, step, settings):
|
|||
|
|
if r.deleted_at is not None:
|
|||
|
|
fail(410, "resource_purged", "工作流运行已删除")
|
|||
|
|
snapshot = r.spec_snapshot
|
|||
|
|
if snapshot.get("schema_version") == 3:
|
|||
|
|
if step.kind != "video.compose":
|
|||
|
|
fail(409, "invalid_story_step", "故事运行只允许冻结素材合成")
|
|||
|
|
frozen = snapshot["render_inputs"]
|
|||
|
|
inputs = {"asset_ids": [c["asset_id"] for c in frozen["clips"]]}
|
|||
|
|
if snapshot["render"]["audio"]:
|
|||
|
|
inputs["audio_asset_id"] = snapshot["render"]["audio"]["asset_id"]
|
|||
|
|
p = {
|
|||
|
|
"story_spec": {k: v for k, v in snapshot.items() if k != "render_inputs"},
|
|||
|
|
"render_inputs": frozen,
|
|||
|
|
"clips": [{"asset_id": c["asset_id"]} for c in frozen["clips"]],
|
|||
|
|
}
|
|||
|
|
for clip in frozen["clips"]:
|
|||
|
|
a = await session.get(Asset, clip["asset_id"])
|
|||
|
|
if (
|
|||
|
|
not a
|
|||
|
|
or a.owner_id != r.owner_id
|
|||
|
|
or a.deleted_at is not None
|
|||
|
|
or a.sha256 != clip["sha256"]
|
|||
|
|
or not await verified_output(a, settings)
|
|||
|
|
):
|
|||
|
|
fail(409, "dependency_changed", "冻结视频已改变或不可用")
|
|||
|
|
elif step.kind == "video.generate":
|
|||
|
|
shot = next((s for s in snapshot["shots"] if s["key"] == step.step_key))
|
|||
|
|
inputs = {"prompt": shot["prompt"]}
|
|||
|
|
if shot.get("image_asset_id"):
|
|||
|
|
inputs["image_asset_id"] = shot["image_asset_id"]
|
|||
|
|
p = {**generation_parameters_for_shot(snapshot, step.step_key), **shot["parameters"]}
|
|||
|
|
else:
|
|||
|
|
steps = (
|
|||
|
|
await session.scalars(
|
|||
|
|
select(WorkflowStep).where(
|
|||
|
|
WorkflowStep.run_id == r.id, WorkflowStep.kind == "video.generate"
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
).all()
|
|||
|
|
bykey = {s.step_key: s for s in steps}
|
|||
|
|
ids = []
|
|||
|
|
hashes = []
|
|||
|
|
for shot in snapshot["shots"]:
|
|||
|
|
s = bykey[shot["key"]]
|
|||
|
|
a = await selected_output(session, s.selected_job_id, r.owner_id)
|
|||
|
|
if not a:
|
|||
|
|
fail(409, "dependency_changed", "镜头产物不存在")
|
|||
|
|
ids.append(a.id)
|
|||
|
|
hashes.append(a.sha256)
|
|||
|
|
inputs = {"asset_ids": ids}
|
|||
|
|
audio = snapshot["render"]["audio"]
|
|||
|
|
if audio:
|
|||
|
|
inputs["audio_asset_id"] = audio["asset_id"]
|
|||
|
|
p = {
|
|||
|
|
"workflow_spec": {k: v for k, v in snapshot.items() if k != "compiled"},
|
|||
|
|
"clips": [{"asset_id": a} for a in ids],
|
|||
|
|
}
|
|||
|
|
audio_asset = await session.get(Asset, audio["asset_id"]) if audio else None
|
|||
|
|
step.semantic_input_hash = digest(
|
|||
|
|
{
|
|||
|
|
"spec": snapshot,
|
|||
|
|
"ordered_output_sha256": hashes,
|
|||
|
|
"audio_sha256": audio_asset.sha256 if audio_asset else None,
|
|||
|
|
}
|
|||
|
|
)
|
|||
|
|
if r.batch_id:
|
|||
|
|
from app.services.orchestration.batch_holds import run_member_holds
|
|||
|
|
|
|||
|
|
r.hold_reasons = sorted(await run_member_holds(session, r))
|
|||
|
|
step.explicit_attempt += 1
|
|||
|
|
jobs = await create_jobs(
|
|||
|
|
session,
|
|||
|
|
Submit(
|
|||
|
|
task_type=step.kind,
|
|||
|
|
input=inputs,
|
|||
|
|
parameters=p,
|
|||
|
|
execution_mode=r.execution_mode,
|
|||
|
|
folder_id=r.folder_id,
|
|||
|
|
output_folder_id=r.output_folder_id,
|
|||
|
|
),
|
|||
|
|
SimpleNamespace(id=r.owner_id, auth_kind="session", scopes=[]),
|
|||
|
|
settings,
|
|||
|
|
key=f"run:{r.id}:{step.step_key}:{step.explicit_attempt}",
|
|||
|
|
internal=True,
|
|||
|
|
frozen_workflow=True,
|
|||
|
|
)
|
|||
|
|
j = jobs[0]
|
|||
|
|
j.run_id = r.id
|
|||
|
|
j.step_key = step.step_key
|
|||
|
|
j.batch_id = r.batch_id
|
|||
|
|
j.batch_item_index = r.batch_item_index
|
|||
|
|
j.explicit_attempt = step.explicit_attempt
|
|||
|
|
j.desired_state = r.desired_state
|
|||
|
|
j.hold_reasons = list(r.hold_reasons or [])
|
|||
|
|
step.selected_job_id = j.id
|
|||
|
|
step.state = "ready"
|
|||
|
|
step.version += 1
|
|||
|
|
await emit_job(session, j)
|
|||
|
|
return j
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def control_run(session, r, desired):
|
|||
|
|
if r.deleted_at is not None:
|
|||
|
|
fail(404, "resource_not_found", "记录不存在")
|
|||
|
|
if r.state in RUN_TERMINAL:
|
|||
|
|
return
|
|||
|
|
if r.desired_state == "cancel" and desired != "cancel":
|
|||
|
|
fail(409, "run_cancelled", "取消不可逆")
|
|||
|
|
r.desired_state = desired
|
|||
|
|
holds = set(r.hold_reasons or [])
|
|||
|
|
if desired == "pause":
|
|||
|
|
holds.add("manual")
|
|||
|
|
elif desired == "run":
|
|||
|
|
holds.discard("manual")
|
|||
|
|
r.hold_reasons = sorted(holds)
|
|||
|
|
jobs = (
|
|||
|
|
await session.scalars(
|
|||
|
|
select(Job).where(
|
|||
|
|
Job.run_id == r.id,
|
|||
|
|
Job.owner_id == r.owner_id,
|
|||
|
|
Job.deleted_at.is_(None),
|
|||
|
|
Job.state.not_in(TERMINAL),
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
).all()
|
|||
|
|
for j in jobs:
|
|||
|
|
j.desired_state = desired
|
|||
|
|
child_holds = set(j.hold_reasons or [])
|
|||
|
|
if desired == "pause":
|
|||
|
|
child_holds.add("manual")
|
|||
|
|
elif desired == "run":
|
|||
|
|
child_holds.discard("manual")
|
|||
|
|
j.hold_reasons = sorted(child_holds)
|
|||
|
|
if desired == "cancel":
|
|||
|
|
j.cancel_requested = True
|
|||
|
|
if (
|
|||
|
|
not j.upstream_id
|
|||
|
|
and (not j.upstream_payload)
|
|||
|
|
and (j.phase not in {"cpu_running", "preparing"})
|
|||
|
|
):
|
|||
|
|
j.state = "cancelled"
|
|||
|
|
j.phase = "cancelled"
|
|||
|
|
j.finished_at = utcnow()
|
|||
|
|
elif j.state != "collecting":
|
|||
|
|
j.state = "cancelling"
|
|||
|
|
j.phase = "cancellation_pending"
|
|||
|
|
await emit_job(session, j)
|
|||
|
|
r.state = "cancelling" if desired == "cancel" else "paused" if desired == "pause" else "queued"
|
|||
|
|
await emit_run(session, r)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def wake(runtime):
|
|||
|
|
runtime.coordinator.wake()
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def post_draft(body: DraftCreate, runtime, actor: Actor = None):
|
|||
|
|
async with runtime.db.session() as s:
|
|||
|
|
from app.core.maintenance import require_writable
|
|||
|
|
|
|||
|
|
require_writable(runtime.settings)
|
|||
|
|
plan, assets = await validate_spec(s, actor.id, body.spec, runtime.settings)
|
|||
|
|
from app.services.folders import owned_folder
|
|||
|
|
|
|||
|
|
if body.folder_id:
|
|||
|
|
await owned_folder(s, body.folder_id, actor.id, lock=True)
|
|||
|
|
d = WorkflowDraft(
|
|||
|
|
owner_id=actor.id,
|
|||
|
|
name=body.name,
|
|||
|
|
kind=body.kind,
|
|||
|
|
spec=plan.spec,
|
|||
|
|
folder_id=body.folder_id,
|
|||
|
|
)
|
|||
|
|
s.add(d)
|
|||
|
|
await s.flush()
|
|||
|
|
for a in assets.values():
|
|||
|
|
s.add(AssetReference(owner_id=actor.id, asset_id=a.id, ref_kind="draft", ref_id=d.id))
|
|||
|
|
emit_asset(s, actor.id, "draft.updated", {"draft": draft_dto(d)})
|
|||
|
|
await s.commit()
|
|||
|
|
return draft_dto(d)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def list_drafts(
|
|||
|
|
runtime, page: int = 1, page_size: int = 24, actor: Actor = None, folder_id: str = ""
|
|||
|
|
):
|
|||
|
|
async with runtime.db.session() as s:
|
|||
|
|
rows, data = await page_rows(
|
|||
|
|
s,
|
|||
|
|
WorkflowDraft,
|
|||
|
|
actor,
|
|||
|
|
page,
|
|||
|
|
page_size,
|
|||
|
|
WorkflowDraft.kind != "story_v3",
|
|||
|
|
await folder_filter(s, WorkflowDraft, actor.id, folder_id),
|
|||
|
|
)
|
|||
|
|
return {**data, "items": [draft_dto(d) for d in rows]}
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def get_draft(id: str, runtime, actor: Actor = None):
|
|||
|
|
async with runtime.db.session() as s:
|
|||
|
|
d = await owned(s, WorkflowDraft, id, actor.id)
|
|||
|
|
if d.kind == "story_v3":
|
|||
|
|
fail(404, "resource_not_found", "请使用故事工作室接口")
|
|||
|
|
return draft_dto(d)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def delete_draft(id: str, runtime, if_match: str | None = None, actor: Actor = None):
|
|||
|
|
from app.services.deletions import archive_records
|
|||
|
|
|
|||
|
|
async with runtime.db.session() as s:
|
|||
|
|
d = await s.scalar(
|
|||
|
|
select(WorkflowDraft).where(WorkflowDraft.id == id, WorkflowDraft.owner_id == actor.id)
|
|||
|
|
)
|
|||
|
|
if d and d.kind == "story_v3":
|
|||
|
|
fail(404, "resource_not_found", "请使用故事工作室接口")
|
|||
|
|
result = await archive_records(s, WorkflowDraft, id, actor.id, if_match)
|
|||
|
|
await s.commit()
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def patch_draft(
|
|||
|
|
id: str, body: DraftPatch, runtime, if_match: str | None = None, actor: Actor = None
|
|||
|
|
):
|
|||
|
|
async with runtime.db.session() as s:
|
|||
|
|
d = await owned(s, WorkflowDraft, id, actor.id)
|
|||
|
|
if d.editor_manifest:
|
|||
|
|
fail(409, "editor_required", "请使用可编辑自动成片接口")
|
|||
|
|
if d.kind == "story_v3":
|
|||
|
|
fail(404, "resource_not_found", "请使用故事工作室接口")
|
|||
|
|
if if_match is None or if_match.strip('"') != str(d.version):
|
|||
|
|
fail(409, "draft_version_conflict", "草稿版本冲突")
|
|||
|
|
if "folder_id" in body.model_fields_set:
|
|||
|
|
from app.services.folders import owned_folder
|
|||
|
|
|
|||
|
|
if body.folder_id:
|
|||
|
|
await owned_folder(s, body.folder_id, actor.id, lock=True)
|
|||
|
|
d.folder_id = body.folder_id
|
|||
|
|
if body.name is not None:
|
|||
|
|
d.name = body.name
|
|||
|
|
if body.spec is not None:
|
|||
|
|
plan, assets = await validate_spec(s, actor.id, body.spec, runtime.settings)
|
|||
|
|
await s.execute(
|
|||
|
|
delete(AssetReference).where(
|
|||
|
|
AssetReference.ref_kind == "draft", AssetReference.ref_id == d.id
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
for a in assets.values():
|
|||
|
|
s.add(
|
|||
|
|
AssetReference(owner_id=actor.id, asset_id=a.id, ref_kind="draft", ref_id=d.id)
|
|||
|
|
)
|
|||
|
|
d.spec = plan.spec
|
|||
|
|
d.revision += 1
|
|||
|
|
d.version += 1
|
|||
|
|
d.updated_at = utcnow()
|
|||
|
|
emit_asset(s, actor.id, "draft.updated", {"draft": draft_dto(d)})
|
|||
|
|
await s.commit()
|
|||
|
|
return draft_dto(d)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def post_run(
|
|||
|
|
id: str, body: RunCreate, runtime, idempotency_key: str | None = None, actor: Actor = None
|
|||
|
|
):
|
|||
|
|
from app.core.maintenance import require_writable
|
|||
|
|
|
|||
|
|
require_writable(runtime.settings)
|
|||
|
|
if (
|
|||
|
|
actor.auth_kind == "bearer"
|
|||
|
|
and body.execution_mode == "interactive"
|
|||
|
|
and ("interactive:write" not in actor.scopes)
|
|||
|
|
):
|
|||
|
|
fail(403, "scope_required", "Interactive scope required.")
|
|||
|
|
capability_error = None
|
|||
|
|
if body.execution_mode == "batch":
|
|||
|
|
try:
|
|||
|
|
await check_batch_capability(runtime)
|
|||
|
|
except HTTPException as exc:
|
|||
|
|
capability_error = exc
|
|||
|
|
async with runtime.db.session() as s:
|
|||
|
|
sub = await accept_submission(
|
|||
|
|
s,
|
|||
|
|
actor.id,
|
|||
|
|
"workflow.run",
|
|||
|
|
idempotency_key,
|
|||
|
|
2,
|
|||
|
|
{"draft_id": id, **request_payload(body)},
|
|||
|
|
)
|
|||
|
|
if sub.resource_json:
|
|||
|
|
r = await owned(s, WorkflowRun, sub.resource_json["run_id"], actor.id)
|
|||
|
|
else:
|
|||
|
|
if capability_error:
|
|||
|
|
raise capability_error
|
|||
|
|
from app.services.quotas import reserve_budget
|
|||
|
|
|
|||
|
|
await reserve_budget(s, actor.id, "workflow.run", units=0, settings=runtime.settings)
|
|||
|
|
r = await create_run(
|
|||
|
|
s,
|
|||
|
|
actor.id,
|
|||
|
|
id,
|
|||
|
|
body.expected_version,
|
|||
|
|
body.draft_revision,
|
|||
|
|
body.execution_mode,
|
|||
|
|
body.reuse_run_id,
|
|||
|
|
settings=runtime.settings,
|
|||
|
|
output_folder_id=body.output_folder_id
|
|||
|
|
if "output_folder_id" in body.model_fields_set
|
|||
|
|
else ...,
|
|||
|
|
)
|
|||
|
|
sub.resource_json = {"run_id": r.id, "draft_id": id}
|
|||
|
|
await s.commit()
|
|||
|
|
snap = await snapshot_run(s, actor.id, r.id)
|
|||
|
|
wake(runtime)
|
|||
|
|
return snap
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def list_runs(
|
|||
|
|
runtime, page: int = 1, page_size: int = 24, actor: Actor = None, folder_id: str = ""
|
|||
|
|
):
|
|||
|
|
async with runtime.db.session() as s:
|
|||
|
|
rows, data = await page_rows(
|
|||
|
|
s,
|
|||
|
|
WorkflowRun,
|
|||
|
|
actor,
|
|||
|
|
page,
|
|||
|
|
page_size,
|
|||
|
|
await folder_filter(s, WorkflowRun, actor.id, folder_id),
|
|||
|
|
)
|
|||
|
|
return {**data, "items": [(await snapshot_run(s, actor.id, r.id))["run"] for r in rows]}
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def get_run(id: str, runtime, actor: Actor = None):
|
|||
|
|
async with runtime.db.session() as s:
|
|||
|
|
return await snapshot_run(s, actor.id, id)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def delete_run(id: str, runtime, if_match: str | None = None, actor: Actor = None):
|
|||
|
|
from app.services.deletions import archive_records
|
|||
|
|
|
|||
|
|
async with runtime.db.session() as s:
|
|||
|
|
result = await archive_records(s, WorkflowRun, id, actor.id, if_match)
|
|||
|
|
await s.commit()
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def retry_step(
|
|||
|
|
id: str, key: str, body: Retry, runtime, idempotency_key: str | None = None, actor: Actor = None
|
|||
|
|
):
|
|||
|
|
async with runtime.db.session() as s:
|
|||
|
|
r = await owned(s, WorkflowRun, id, actor.id)
|
|||
|
|
if (
|
|||
|
|
actor.auth_kind == "bearer"
|
|||
|
|
and r.execution_mode == "interactive"
|
|||
|
|
and ("interactive:write" not in actor.scopes)
|
|||
|
|
):
|
|||
|
|
fail(403, "scope_required", "Interactive scope required.")
|
|||
|
|
sub = await accept_submission(
|
|||
|
|
s,
|
|||
|
|
actor.id,
|
|||
|
|
"workflow.retry",
|
|||
|
|
idempotency_key,
|
|||
|
|
2,
|
|||
|
|
{"run_id": id, "step_key": key, **body.model_dump()},
|
|||
|
|
)
|
|||
|
|
if not sub.resource_json:
|
|||
|
|
if r.version != body.expected_run_version:
|
|||
|
|
fail(409, "run_version_conflict", "工作流版本冲突")
|
|||
|
|
step = await s.scalar(
|
|||
|
|
select(WorkflowStep).where(
|
|||
|
|
WorkflowStep.run_id == r.id, WorkflowStep.step_key == key
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
j = await s.get(Job, body.target_job_id)
|
|||
|
|
if (
|
|||
|
|
not step
|
|||
|
|
or step.selected_job_id != body.target_job_id
|
|||
|
|
or (not j)
|
|||
|
|
or (j.owner_id != actor.id)
|
|||
|
|
or (j.deleted_at is not None)
|
|||
|
|
or (r.state in RUN_TERMINAL)
|
|||
|
|
or (r.desired_state == "cancel")
|
|||
|
|
):
|
|||
|
|
fail(409, "step_not_retryable", "步骤不可重试")
|
|||
|
|
active_execution = await s.scalar(
|
|||
|
|
select(Execution.id).where(
|
|||
|
|
Execution.job_id == j.id, Execution.state.not_in({"exited", "results_ready"})
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
if active_execution:
|
|||
|
|
fail(409, "cleanup_pending", "Execution cleanup must be confirmed before retry.")
|
|||
|
|
if j.state == "needs_attention" and (not (j.error_json or {}).get("safe_to_retry")):
|
|||
|
|
fail(409, "cleanup_pending", "执行尚未确认清理")
|
|||
|
|
if j.state not in {"failed", "timed_out", "needs_attention"}:
|
|||
|
|
fail(409, "step_not_retryable", "仅失败步骤允许重试")
|
|||
|
|
if r.run_kind in {"story_auto", "workflow_auto"}:
|
|||
|
|
from app.services.orchestration.editor_engine import create_editor_child
|
|||
|
|
|
|||
|
|
await create_editor_child(s, r, step, runtime.settings)
|
|||
|
|
else:
|
|||
|
|
await create_child(s, r, step, runtime.settings)
|
|||
|
|
r.state = "paused" if r.desired_state == "pause" or r.hold_reasons else "queued"
|
|||
|
|
r.error_json = None
|
|||
|
|
await emit_run(s, r)
|
|||
|
|
sub.resource_json = {"run_id": r.id, "job_id": step.selected_job_id}
|
|||
|
|
await s.commit()
|
|||
|
|
snap = await snapshot_run(s, actor.id, id)
|
|||
|
|
wake(runtime)
|
|||
|
|
return snap
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def _control(id, desired, body, runtime, key, actor):
|
|||
|
|
async with runtime.db.session() as s:
|
|||
|
|
sub = await accept_submission(
|
|||
|
|
s,
|
|||
|
|
actor.id,
|
|||
|
|
"workflow." + ("resume" if desired == "run" else desired),
|
|||
|
|
key,
|
|||
|
|
2,
|
|||
|
|
{"run_id": id, **body.model_dump()},
|
|||
|
|
)
|
|||
|
|
r = await owned(s, WorkflowRun, id, actor.id)
|
|||
|
|
if not sub.resource_json:
|
|||
|
|
if body.expected_version is not None and body.expected_version != r.version:
|
|||
|
|
fail(409, "run_version_conflict", "工作流版本冲突")
|
|||
|
|
await control_run(s, r, desired)
|
|||
|
|
sub.resource_json = {"run_id": r.id}
|
|||
|
|
await s.commit()
|
|||
|
|
snap = await snapshot_run(s, actor.id, id)
|
|||
|
|
wake(runtime)
|
|||
|
|
return snap
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def cancel_run(
|
|||
|
|
id: str, body: Control, runtime, idempotency_key: str | None = None, actor: Actor = None
|
|||
|
|
):
|
|||
|
|
return await _control(id, "cancel", body, runtime, idempotency_key, actor)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def pause_run(
|
|||
|
|
id: str, body: Control, runtime, idempotency_key: str | None = None, actor: Actor = None
|
|||
|
|
):
|
|||
|
|
return await _control(id, "pause", body, runtime, idempotency_key, actor)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def resume_run(
|
|||
|
|
id: str, body: Control, runtime, idempotency_key: str | None = None, actor: Actor = None
|
|||
|
|
):
|
|||
|
|
return await _control(id, "run", body, runtime, idempotency_key, actor)
|