cmvr-visual/backend/app/services/normalized_cache.py

189 lines
7.0 KiB
Python
Raw Permalink Normal View History

"""Owner-scoped normalized video cache. The ordinary Asset ledger accounts for bytes."""
import asyncio
import hashlib
import json
import os
from contextvars import ContextVar
from pathlib import Path
from fastapi import HTTPException
from sqlalchemy import select, func
from sqlalchemy.exc import IntegrityError
from app.adapters.storage import confined, file_thread
from app.domain.errors import MediaError
from app.models import Asset, Job, User
from app.services.quotas import check_storage_budget
active_cache = ContextVar("normalized_clip_cache", default=None)
def clip_key(owner, sha, start, end, dedup, canvas, fit, fps):
recipe = [
"normalize-x264-veryfast-crf20-yuv420p-v1",
owner,
sha,
start,
end,
dedup,
start + dedup,
canvas,
fit,
fps,
]
return hashlib.sha256(json.dumps(recipe, separators=(",", ":")).encode()).hexdigest()
def digest(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
async def cache_digest(path):
"""An unreadable optional clip is ineligible for reuse or publication."""
try:
return await file_thread(digest, path)
except OSError:
return None
class ClipCache:
def __init__(self, db, settings, owner, job_id):
self.db, self.settings, self.owner, self.job_id = db, settings, owner, job_id
async def source_ok(self, session, clip):
source = await session.get(Asset, clip["asset_id"])
job = await session.get(Job, self.job_id)
if job and job.cancel_requested and job.owner_id == self.owner:
raise asyncio.CancelledError
return (
job
and job.owner_id == self.owner
and not job.cancel_requested
and source
and source.owner_id == self.owner
and source.ready
and source.deleted_at is None
and source.sha256 == clip["sha256"]
)
def storage_key(self, clip, key):
cache_id = hashlib.sha256(f"{key}:{clip['asset_id']}".encode()).hexdigest()[:32]
return f"{self.owner}/{cache_id}/{clip['asset_id']}.mp4"
async def restore(self, clip, key, target):
storage_key = self.storage_key(clip, key)
async with self.db.session() as session:
if not await self.source_ok(session, clip):
raise MediaError("dependency_changed", "Clip source or active job is unavailable.")
row = await session.scalar(
select(Asset).where(
Asset.storage_key == storage_key,
Asset.owner_id == self.owner,
Asset.origin == "normalized",
Asset.ready.is_(True),
Asset.deleted_at.is_(None),
)
)
if row is None:
return False
try:
path = confined(self.settings.asset_root, storage_key, exists=True)
await file_thread(os.link, path, target)
except OSError:
target.unlink(missing_ok=True)
return False
# An open job link survives concurrent eviction of the cache directory entry.
checksum = await cache_digest(target)
if checksum == row.sha256:
return True
target.unlink()
return False
async def publish(self, clip, key, target, canvas, frames):
storage_key = self.storage_key(clip, key)
path = confined(self.settings.asset_root, storage_key)
size = target.stat().st_size
checksum = await cache_digest(target)
if checksum is None:
return
async with self.db.session() as session:
await session.scalar(select(User).where(User.id == self.owner).with_for_update())
if not await self.source_ok(session, clip):
return
row = await session.scalar(select(Asset).where(Asset.storage_key == storage_key))
if row and (row.owner_id != self.owner or row.origin != "normalized" or row.deleted_at):
return
if row and path.is_file():
existing = await cache_digest(path)
if existing is None or existing == row.sha256:
return
count, used = (
await session.execute(
select(func.count(), func.coalesce(func.sum(Asset.size_bytes), 0)).where(
Asset.owner_id == self.owner,
Asset.origin == "normalized",
Asset.ready.is_(True),
)
)
).one()
if count >= 4096 and row is None:
return
if used + size > min(self.settings.max_output_bytes * 4, 8 * 1024**3):
return
try:
await check_storage_budget(
session, self.settings, self.owner, size + self.settings.max_output_bytes
)
except HTTPException:
return
if row is None:
row = Asset(
id=Path(storage_key).parent.name,
owner_id=self.owner,
name="Normalized segment",
storage_key=storage_key,
kind="video",
mime_type="video/mp4",
origin="normalized",
width=canvas[0],
height=canvas[1],
duration_seconds=frames / 24,
)
session.add(row)
row.sha256, row.size_bytes, row.ready = checksum, size, True
try:
await session.commit()
except IntegrityError:
return
# The ledger precedes the atomic link. A crash leaves a repairable missing target.
try:
path.parent.mkdir(parents=True, exist_ok=True)
if path.exists():
existing = await cache_digest(path)
if existing is None:
return
if existing != checksum:
path.unlink(missing_ok=True)
await file_thread(os.link, target, path)
except OSError:
# A competing link is successful only when it contains the validated bytes.
if path.is_file():
existing = await cache_digest(path)
if existing is None or existing == checksum:
return
if not path.exists():
await session.delete(row)
await session.commit()
try:
path.parent.rmdir()
except OSError:
pass
else:
# Keep existing bytes tracked for maintenance if replacement was denied.
from app.models import utcnow
row.deleted_at = utcnow()
await session.commit()