cmvr-visual/backend/app/services/stories/deletion.py

436 lines
15 KiB
Python

import logging
from sqlalchemy import case, select, delete, update
from app.models import (
AssetReference,
BatchItem,
WorkflowRun,
ShotCandidate,
ShotSelection,
Job,
Execution,
WorkflowDraft,
Batch,
Submission,
utcnow,
)
from app.core.errors import fail
from app.core.maintenance import require_writable
from app.domain.tasks import RUN_TERMINAL, TERMINAL
from app.services.stories.common import story
from app.services.events import emit_asset
async def ensure_terminal(s, c):
if c.job_id:
j = await s.get(Job, c.job_id)
if j and j.deleted_at is None and j.state not in TERMINAL:
fail(409, "deletion_requires_terminal", "请先取消候选任务并等待执行结束")
execution = await s.scalar(
select(Execution.id)
.where(
Execution.job_id == c.job_id, Execution.state.not_in({"exited", "results_ready"})
)
.limit(1)
)
if execution:
fail(409, "cleanup_pending", "候选执行尚未确认清理")
async def archive_candidates(s, owner_id, rows):
from app.services.deletions import references_any
from sqlalchemy.orm import load_only
if not rows:
return
ids = {row.id for row in rows}
now = utcnow()
for row in rows:
if row.deleted_at is None:
row.deleted_at = now
row.version += 1
emit_asset(
s,
owner_id,
"candidate.deleted",
{"id": row.id, "draft_id": row.draft_id, "version": row.version},
)
await s.execute(
delete(AssetReference).where(
AssetReference.owner_id == owner_id,
AssetReference.ref_kind == "candidate",
AssetReference.ref_id.in_(ids),
)
)
submissions = await s.scalars(
select(Submission)
.options(load_only(Submission.resource_json))
.where(
Submission.owner_id == owner_id,
Submission.operation.like("story.candidate.%"),
Submission.status != "purged",
)
)
for sub in submissions:
if references_any(sub.resource_json, ids):
sub.status = "purged"
async def delete_candidate(runtime, actor, id, candidate_id, if_match):
require_writable(runtime.settings)
async with runtime.db.session() as s:
await story(s, id, actor.id)
c = await s.scalar(
select(ShotCandidate)
.where(
ShotCandidate.id == candidate_id,
ShotCandidate.draft_id == id,
ShotCandidate.owner_id == actor.id,
)
.with_for_update()
)
if not c:
fail(404, "candidate_not_found", "候选不存在")
if c.deleted_at:
return {"deleted": {"candidate_ids": [c.id]}}
if if_match is None or if_match.strip('"') != str(c.version):
fail(409, "version_conflict", "候选版本冲突")
await ensure_terminal(s, c)
await archive_candidates(s, actor.id, [c])
await s.commit()
return {"deleted": {"candidate_ids": [c.id]}}
DELETE_OPERATION = "story.delete"
log = logging.getLogger(__name__)
def pending_result(draft_id):
return {
"pending": True,
"deleted": {"draft_ids": [draft_id], "run_ids": [], "job_ids": [], "batch_ids": []},
}
async def begin_story_deletion(s, runtime, draft):
from app.services.deletions import story_job_condition
from app.services.submissions import accept_submission
from app.services.user_deletion import cancel_jobs_for_deletion
owner = draft.owner_id
intent = await accept_submission(
s, owner, DELETE_OPERATION, draft.id, 2, {"draft_id": draft.id}
)
intent.status = "cleanup_pending"
now = utcnow()
draft.deleted_at = draft.updated_at = now
draft.version += 1
emit_asset(s, owner, "draft.deleted", {"id": draft.id, "version": draft.version})
emit_asset(s, owner, "story.deleted", {"id": draft.id, "version": draft.version})
# 先禁止编辑、重新应用、派发后续阶段和补队。任务行继续留给执行器进行真实取消。
runs = (
await s.execute(
select(WorkflowRun.id, WorkflowRun.version)
.where(
WorkflowRun.draft_id == draft.id,
WorkflowRun.owner_id == owner,
WorkflowRun.deleted_at.is_(None),
)
.with_for_update()
)
).all()
for run_id, version in runs:
emit_asset(s, owner, "workflow.deleted", {"id": run_id, "version": version + 1})
if runs:
query = update(WorkflowRun).where(WorkflowRun.id.in_([rid for rid, _ in runs]))
await s.execute(
query.values(
deleted_at=now,
version=WorkflowRun.version + 1,
desired_state=case(
(WorkflowRun.state.in_(RUN_TERMINAL), WorkflowRun.desired_state), else_="cancel"
),
state=case(
(WorkflowRun.state.in_(RUN_TERMINAL), WorkflowRun.state), else_="cancelling"
),
)
)
jobs = (
await s.scalars(
select(Job)
.where(
story_job_condition(draft.id, owner),
Job.deleted_at.is_(None),
Job.state.not_in(TERMINAL),
)
.with_for_update()
)
).all()
unconfirmed = set(
await s.scalars(
select(Execution.job_id).where(
Execution.job_id.in_([j.id for j in jobs]),
Execution.state.not_in({"exited", "results_ready"}),
)
)
)
await cancel_jobs_for_deletion(s, runtime, jobs, unconfirmed)
async def archive_story_batches(s, draft, run_ids, job_ids, candidate_ids):
"""共享批次保留其余成员,仅归档整个归属于本故事的批次。"""
batch_ids = set(
await s.scalars(
select(WorkflowRun.batch_id).where(
WorkflowRun.id.in_(run_ids), WorkflowRun.batch_id.is_not(None)
)
)
)
batch_ids.update(
await s.scalars(
select(ShotCandidate.batch_id).where(
ShotCandidate.id.in_(candidate_ids), ShotCandidate.batch_id.is_not(None)
)
)
)
archived = []
batches = (
await s.scalars(
select(Batch)
.where(
Batch.id.in_(batch_ids),
Batch.owner_id == draft.owner_id,
Batch.deleted_at.is_(None),
)
.with_for_update()
)
).all()
for batch in batches:
if await s.scalar(
select(Job.id).where(Job.batch_id == batch.id, Job.id.not_in(job_ids)).limit(1)
):
continue
if await s.scalar(
select(WorkflowRun.id)
.where(WorkflowRun.batch_id == batch.id, WorkflowRun.draft_id != draft.id)
.limit(1)
):
continue
if await s.scalar(
select(BatchItem.id)
.where(
BatchItem.batch_id == batch.id,
BatchItem.target_id.not_in([*run_ids, *candidate_ids, *job_ids]),
)
.limit(1)
):
continue
batch.deleted_at = utcnow()
batch.version += 1
if batch.state not in {"succeeded", "completed_with_errors", "cancelled"}:
batch.state, batch.desired_state, batch.finished_at = (
"cancelled",
"cancel",
batch.deleted_at,
)
emit_asset(s, draft.owner_id, "batch.deleted", {"id": batch.id, "version": batch.version})
archived.append(batch.id)
if archived:
await s.execute(
update(Submission)
.where(
Submission.owner_id == draft.owner_id,
Submission.status != "purged",
Submission.resource_json["batch_id"].as_string().in_(archived),
)
.values(status="purged")
)
return archived
async def archive_story_tree(s, runtime, draft):
from app.services.deletions import archive_records, story_job_condition
from app.services.stories.asset_cleanup import stage_story_assets, story_asset_ids
from app.services.user_deletion import local_work_pending
draft_id, owner_id = draft.id, draft.owner_id
condition = story_job_condition(draft_id, owner_id)
if await s.scalar(
select(Job.id)
.where(condition, Job.state.not_in(TERMINAL), Job.deleted_at.is_(None))
.limit(1)
):
return None
job_ids = list(await s.scalars(select(Job.id).where(condition)))
if local_work_pending(runtime, job_ids) or await s.scalar(
select(Execution.id)
.where(Execution.job_id.in_(job_ids), Execution.state.not_in({"exited", "results_ready"}))
.limit(1)
):
return None
asset_ids = await story_asset_ids(s, draft, job_ids)
await s.execute(
update(WorkflowRun)
.where(
WorkflowRun.draft_id == draft_id,
WorkflowRun.owner_id == owner_id,
WorkflowRun.state == "cancelling",
)
.values(state="cancelled", finished_at=utcnow())
)
result = await archive_records(s, WorkflowDraft, draft_id, owner_id, finishing_story=True)
rows = (
await s.scalars(
select(ShotCandidate)
.where(ShotCandidate.draft_id == draft_id, ShotCandidate.owner_id == owner_id)
.with_for_update()
)
).all()
await archive_candidates(s, owner_id, rows)
selection_ids = select(ShotSelection.id).where(
ShotSelection.draft_id == draft_id, ShotSelection.owner_id == owner_id
)
await s.execute(
delete(AssetReference).where(
AssetReference.owner_id == owner_id,
AssetReference.ref_kind == "selection",
AssetReference.ref_id.in_(selection_ids),
)
)
deleted = result["deleted"]
deleted["candidate_ids"] = [row.id for row in rows]
deleted["batch_ids"] = await archive_story_batches(
s, draft, deleted["run_ids"], job_ids, deleted["candidate_ids"]
)
deleted["asset_ids"] = await stage_story_assets(s, draft, asset_ids)
return result
async def finish_story_deletion(runtime, draft_id, owner_id):
from app.services.stories.asset_cleanup import purge_story_assets
async with runtime.db.session() as s:
draft = await s.scalar(
select(WorkflowDraft)
.where(
WorkflowDraft.id == draft_id,
WorkflowDraft.owner_id == owner_id,
WorkflowDraft.kind == "story_v3",
)
.with_for_update()
)
request = (
select(Submission)
.where(
Submission.owner_id == owner_id,
Submission.operation == DELETE_OPERATION,
Submission.key == draft_id,
)
.with_for_update()
.execution_options(populate_existing=True)
)
intent = await s.scalar(request)
if not draft or not draft.deleted_at or not intent:
fail(404, "resource_not_found", "故事不存在")
if intent.status == "completed":
return intent.resource_json
result = intent.resource_json.get("cleanup_receipt")
if result is None:
result = await archive_story_tree(s, runtime, draft)
if result is None:
return pending_result(draft_id)
# 持久化此次删除的确切文件集。即使释放文件时崩溃,也不用从已解绑的草稿反推出文件归属。
intent.resource_json = {"cleanup_receipt": result}
await s.commit()
intent = await s.scalar(request)
if intent.status == "completed":
return intent.resource_json
result = intent.resource_json["cleanup_receipt"]
await purge_story_assets(s, runtime.settings, owner_id, result["deleted"]["asset_ids"])
intent.status, intent.resource_json = "completed", result
await s.commit()
return result
async def process_story_deletion(runtime, draft_id, owner_id):
try:
return await finish_story_deletion(runtime, draft_id, owner_id)
except Exception:
# 意图已单独提交;文件占用或事务回滚时用同一请求重试,不能向客户端报告已清理。
log.exception("Story deletion pending after cleanup failure: %s", draft_id)
return pending_result(draft_id)
async def resume_story_deletions(runtime):
async with runtime.db.session() as s:
pending = (
await s.execute(
select(Submission.key, Submission.owner_id).where(
Submission.operation == DELETE_OPERATION, Submission.status == "cleanup_pending"
)
)
).all()
for draft_id, owner_id in pending:
await process_story_deletion(runtime, draft_id, owner_id)
async def delete_story(runtime, actor, id, if_match):
require_writable(runtime.settings)
async with runtime.db.session() as s:
draft = await s.scalar(
select(WorkflowDraft)
.where(
WorkflowDraft.id == id,
WorkflowDraft.owner_id == actor.id,
WorkflowDraft.kind == "story_v3",
)
.with_for_update()
)
if draft is None:
fail(404, "resource_not_found", "故事不存在")
if draft.deleted_at:
intent = await s.scalar(
select(Submission).where(
Submission.owner_id == actor.id,
Submission.operation == DELETE_OPERATION,
Submission.key == id,
)
)
if not intent:
fail(404, "resource_not_found", "故事不存在")
if intent.status == "completed":
return intent.resource_json
else:
if if_match is None or if_match.strip('"') != str(draft.version):
fail(409, "draft_version_conflict", "故事版本冲突")
await begin_story_deletion(s, runtime, draft)
await s.commit()
runtime.coordinator.wake()
return await process_story_deletion(runtime, id, actor.id)
async def delete_candidate_batch(runtime, actor, id, if_match):
from app.services.deletions import archive_records
require_writable(runtime.settings)
async with runtime.db.session() as s:
rows = (
await s.scalars(
select(ShotCandidate)
.where(
ShotCandidate.batch_id == id,
ShotCandidate.owner_id == actor.id,
ShotCandidate.deleted_at.is_(None),
)
.with_for_update()
)
).all()
for c in rows:
await ensure_terminal(s, c)
result = await archive_records(s, Batch, id, actor.id, if_match)
await archive_candidates(s, actor.id, rows)
result["deleted"]["candidate_ids"] = [c.id for c in rows]
await s.commit()
return result