clipwright/restoring_static.py
juancarlos.cavero a602a2aa96 fix(videos): restore a project from R2 before answering 404 under /videos
Reopening a project whose working files were gone (redeploy, hourly sweep)
fired the transcript requests, which pull the job back from R2 (~25 s for
2 GB), and the <video> loads at the same instant; /videos was a plain
StaticFiles mount, so every player got a 404 until the user reloaded
(job cff3ad6c, 6-sep-2026 00:37 UTC, 15 x 404).

- restoring_static.py: StaticFiles subclass that, on a miss, hands the job
  id to a restorer and looks once more. Range/ETag/HEAD behaviour untouched.
- app.py: restore_project's core is now _restore_job_files (no auth, the
  caller decides); the /videos restorer looks the Project up by job id and
  restores for its owner. The files are public by job id already, so this
  grants nothing new. A player arriving mid-restore waits on the per-job
  lock instead of failing. The "Auto-restored" line is printed once, when
  files were actually pulled, instead of once per waiting request.

Claude-Session: https://claude.ai/code/session_013ubPhpBw8kAUcLXCCfH4C5
2026-09-06 12:28:38 +02:00

47 lines
2 KiB
Python

"""Static file serving that can bring a job's files back before answering 404.
``OUTPUT_DIR`` is not durable: a redeploy or the hourly sweep wipes a
finished job, while the user's library still points at
``/videos/<job_id>/<file>``. The API endpoints re-pull a project from R2 on
demand (``app._ensure_job_files``), but ``/videos`` was a plain
``StaticFiles`` mount, so when the dashboard reopened a project it fired the
15 transcript requests (which restored the job, ~25 s for 2 GB) and the 15
``<video>`` loads at the same instant, and every player got a 404 that only
a reload fixed (job cff3ad6c, 6-sep-2026 00:37 UTC).
This subclass keeps everything StaticFiles does (Range requests, ETags, HEAD)
and adds one step: on a miss it hands the first path segment (the job id) to
``restorer``; when that reports the files may now be there, it looks once
more. The restorer is awaited on the request, so a player that arrives while
a restore is in flight simply waits for it (the per-job lock lives in the
restorer) instead of failing.
"""
from typing import Awaitable, Callable, Optional
from starlette.exceptions import HTTPException
from starlette.staticfiles import StaticFiles
Restorer = Callable[[str], Awaitable[bool]]
class RestoringStaticFiles(StaticFiles):
def __init__(self, *args, restorer: Optional[Restorer] = None, **kwargs):
super().__init__(*args, **kwargs)
self.restorer = restorer
async def get_response(self, path: str, scope):
try:
return await super().get_response(path, scope)
except HTTPException as exc:
if exc.status_code != 404 or self.restorer is None:
raise
job_id = path.split("/", 1)[0] if "/" in path else ""
if not job_id:
raise
try:
restored = await self.restorer(job_id)
except Exception:
restored = False
if not restored:
raise
return await super().get_response(path, scope)