157 lines
6.5 KiB
Python
157 lines
6.5 KiB
Python
"""Immediate deletion of an asset's owned files and database links."""
|
||
|
||
from pathlib import Path
|
||
import stat
|
||
from sqlalchemy import and_, delete, or_, select, update
|
||
from app.core.errors import fail
|
||
from app.models import Asset, Job, JobAsset
|
||
from app.models import AssetReference, AssetTag, Execution, SharedAsset
|
||
|
||
|
||
async def require_unused_asset(session, asset, *, publication_id=None):
|
||
"""Run under the database unit lock, before touching any files."""
|
||
from app.domain.tasks import TERMINAL
|
||
|
||
protected_ref = AssetReference.ref_kind != "execution"
|
||
if publication_id:
|
||
protected_ref = and_(
|
||
protected_ref,
|
||
~and_(AssetReference.ref_kind == "shared", AssetReference.ref_id == publication_id),
|
||
)
|
||
reference = await session.scalar(
|
||
select(AssetReference.id).where(AssetReference.asset_id == asset.id, protected_ref).limit(1)
|
||
)
|
||
publication_query = select(SharedAsset.id).where(SharedAsset.asset_id == asset.id)
|
||
if publication_id:
|
||
publication_query = publication_query.where(SharedAsset.id != publication_id)
|
||
publication = await session.scalar(publication_query.limit(1))
|
||
consumer_jobs = select(JobAsset.job_id).where(JobAsset.asset_id == asset.id)
|
||
involved_job = or_(Job.id.in_(consumer_jobs), Job.id == asset.source_job_id)
|
||
active_job = await session.scalar(
|
||
select(Job.id).where(involved_job, Job.state.notin_(TERMINAL)).limit(1)
|
||
)
|
||
active_execution = await session.scalar(
|
||
select(Execution.id)
|
||
.where(
|
||
Execution.state.notin_({"exited", "results_ready"}),
|
||
or_(
|
||
Execution.job_id.in_(consumer_jobs),
|
||
Execution.job_id == asset.source_job_id,
|
||
Execution.id.in_(
|
||
select(AssetReference.ref_id).where(
|
||
AssetReference.asset_id == asset.id, AssetReference.ref_kind == "execution"
|
||
)
|
||
),
|
||
),
|
||
)
|
||
.limit(1)
|
||
)
|
||
if reference or publication or active_job or active_execution:
|
||
fail(409, "asset_in_use", "素材正在被任务、工作流或共享发布使用")
|
||
|
||
|
||
# 先检查全部路径,再删除任一文件;拒绝符号链接和 Windows junction,不递归遍历未知文件。
|
||
def owned_file_paths(settings, asset):
|
||
"""Validate every target first; never traverse symlinks or Windows junctions."""
|
||
root = Path(settings.asset_root).resolve()
|
||
directory = root / asset.owner_id / asset.id
|
||
if (
|
||
Path(asset.owner_id).name != asset.owner_id
|
||
or Path(asset.id).name != asset.id
|
||
or (not directory.is_relative_to(root))
|
||
):
|
||
raise ValueError("Invalid asset owner directory")
|
||
paths = []
|
||
keys = [asset.storage_key]
|
||
if asset.thumbnail_key is not None:
|
||
keys.append(asset.thumbnail_key)
|
||
for key in keys:
|
||
relative = Path(key or "")
|
||
if (
|
||
not key
|
||
or relative.is_absolute()
|
||
or relative.drive
|
||
or (".." in relative.parts)
|
||
or (relative.parent != Path(asset.owner_id) / asset.id)
|
||
):
|
||
raise ValueError("Asset file is outside its owned directory")
|
||
path = root / relative
|
||
for component in (root / asset.owner_id, directory, path):
|
||
try:
|
||
metadata = component.lstat()
|
||
except FileNotFoundError:
|
||
continue
|
||
if stat.S_ISLNK(metadata.st_mode) or getattr(
|
||
metadata, "st_file_attributes", 0
|
||
) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 1024):
|
||
raise ValueError("Linked asset files are not deletion targets")
|
||
if component == path and (not stat.S_ISREG(metadata.st_mode)):
|
||
raise ValueError("Asset deletion requires regular files")
|
||
if component != path and (not stat.S_ISDIR(metadata.st_mode)):
|
||
raise ValueError("Asset directory is not a directory")
|
||
if path not in paths:
|
||
paths.append(path)
|
||
return paths
|
||
|
||
|
||
async def normalized_caches(session, asset):
|
||
if asset.origin == "normalized":
|
||
return []
|
||
return (
|
||
await session.scalars(
|
||
select(Asset).where(
|
||
Asset.origin == "normalized",
|
||
Asset.owner_id == asset.owner_id,
|
||
Asset.storage_key.endswith("/" + asset.id + ".mp4", autoescape=True),
|
||
)
|
||
)
|
||
).all()
|
||
|
||
|
||
# 文件系统不能跟随数据库回滚:删除字节后才移除 DB 链接,失败允许按原 ID 重试。
|
||
async def remove_asset(session, settings, asset, *, publication=None, include_caches=True):
|
||
"""Remove bytes first, then links, in the caller's serialized DB transaction.
|
||
|
||
No success is reported until the caller commits. A filesystem error leaves
|
||
the row available for retry; already missing files are accepted on retry.
|
||
A crash/failed DB commit can leave a row with missing bytes, never an
|
||
untracked file falsely reported as successfully deleted.
|
||
"""
|
||
await require_unused_asset(
|
||
session, asset, publication_id=publication.id if publication else None
|
||
)
|
||
if include_caches and asset.origin != "normalized":
|
||
caches = await normalized_caches(session, asset)
|
||
for cache in caches:
|
||
await require_unused_asset(session, cache)
|
||
for cache in caches:
|
||
await remove_asset(session, settings, cache)
|
||
try:
|
||
paths = owned_file_paths(settings, asset)
|
||
except ValueError:
|
||
fail(409, "unsafe_asset_path", "素材存储路径异常,无法安全删除")
|
||
except OSError:
|
||
fail(503, "asset_delete_failed", "素材文件暂时无法删除,请稍后重试")
|
||
try:
|
||
for path in paths:
|
||
path.unlink(missing_ok=True)
|
||
except OSError:
|
||
fail(503, "asset_delete_failed", "素材文件暂时无法删除,请稍后重试")
|
||
for directory in {path.parent for path in paths}:
|
||
try:
|
||
directory.rmdir()
|
||
except OSError:
|
||
pass
|
||
await session.execute(delete(JobAsset).where(JobAsset.asset_id == asset.id))
|
||
await session.execute(delete(AssetReference).where(AssetReference.asset_id == asset.id))
|
||
await session.execute(delete(AssetTag).where(AssetTag.asset_id == asset.id))
|
||
await session.execute(
|
||
update(SharedAsset)
|
||
.where(SharedAsset.source_asset_id == asset.id)
|
||
.values(source_asset_id=None)
|
||
)
|
||
if publication is not None:
|
||
await session.delete(publication)
|
||
await session.flush()
|
||
await session.execute(delete(Asset).where(Asset.id == asset.id))
|