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
This commit is contained in:
juancarlos.cavero 2026-09-06 12:28:38 +02:00
parent 959407c30e
commit a602a2aa96
3 changed files with 209 additions and 13 deletions

80
app.py
View file

@ -1677,8 +1677,14 @@ app.add_middleware(
expose_headers=["Content-Length", "Content-Range", "Accept-Ranges"], expose_headers=["Content-Length", "Content-Range", "Accept-Ranges"],
) )
# Mount static files for serving videos # Mount static files for serving videos. A miss under /videos/<job_id>/ first
app.mount("/videos", StaticFiles(directory=OUTPUT_DIR), name="videos") # tries to bring the job back from R2 (see restoring_static.py): the players
# of a reopened project used to 404 while the transcript requests were still
# restoring it. Late-bound lambda: the restorer is defined further down.
from restoring_static import RestoringStaticFiles
app.mount("/videos", RestoringStaticFiles(
directory=OUTPUT_DIR,
restorer=lambda job_id: _restore_for_public_path(job_id)), name="videos")
# Mount static files for serving thumbnails # Mount static files for serving thumbnails
THUMBNAILS_DIR = os.path.join(OUTPUT_DIR, "thumbnails") THUMBNAILS_DIR = os.path.join(OUTPUT_DIR, "thumbnails")
@ -2734,6 +2740,9 @@ async def download_all_clips(job_id: str, request: Request):
# edit endpoint works on it again. Restored files land with a fresh mtime, so # edit endpoint works on it again. Restored files land with a fresh mtime, so
# the retention clock restarts; re-restoring after a purge is cheap. # the retention clock restarts; re-restoring after a purge is cheap.
_restore_locks: Dict[str, asyncio.Lock] = {} _restore_locks: Dict[str, asyncio.Lock] = {}
# Job ids are uuid4 strings; anything else under /videos is not a job dir
# (thumbnails, stray probes) and must not reach the database.
_JOB_ID_RE = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
@app.post("/api/projects/{job_id}/restore") @app.post("/api/projects/{job_id}/restore")
@ -2753,6 +2762,27 @@ async def restore_project(job_id: str, request: Request):
if proj is None or str(proj.user_id) != str(user.id): if proj is None or str(proj.user_id) != str(user.id):
raise HTTPException(status_code=404, detail="Project not found") raise HTTPException(status_code=404, detail="Project not found")
await _restore_job_files(job_id, proj, str(user.id))
return {
"job_id": job_id,
"status": "completed",
"result": jobs[job_id]['result'],
"project_state": proj.state,
"title": proj.title,
}
async def _restore_job_files(job_id: str, proj, user_id: str) -> bool:
"""Bring a project's working files back from R2 and register the job.
The ownership check is the caller's job: ``restore_project`` (the
endpoint) verifies the session, ``_restore_for_public_path`` serves files
that are public by job id anyway. Returns True when files were actually
pulled, False on the idempotent fast path (everything already on disk).
"""
from cloud import storage as cloud_storage
pulled = False
# Per-job lock: a double click must not download the project twice. # Per-job lock: a double click must not download the project twice.
lock = _restore_locks.setdefault(job_id, asyncio.Lock()) lock = _restore_locks.setdefault(job_id, asyncio.Lock())
async with lock: async with lock:
@ -2769,7 +2799,7 @@ async def restore_project(job_id: str, request: Request):
): ):
os.utime(job_dir, None) # restart the retention clock os.utime(job_dir, None) # restart the retention clock
else: else:
prefix = cloud_storage.job_key(user.id, job_id, "") prefix = cloud_storage.job_key(user_id, job_id, "")
keys = await asyncio.to_thread(cloud_storage.list_keys, prefix) keys = await asyncio.to_thread(cloud_storage.list_keys, prefix)
if not keys: if not keys:
raise HTTPException(status_code=502, raise HTTPException(status_code=502,
@ -2796,7 +2826,8 @@ async def restore_project(job_id: str, request: Request):
raise HTTPException(status_code=502, detail=f"Restore download failed: {e}") raise HTTPException(status_code=502, detail=f"Restore download failed: {e}")
# Owner sidecar keeps the multi-tenant guard after a server restart. # Owner sidecar keeps the multi-tenant guard after a server restart.
with open(os.path.join(tmp_dir, ".owner"), "w") as f: with open(os.path.join(tmp_dir, ".owner"), "w") as f:
f.write(str(user.id)) f.write(user_id)
pulled = True
if os.path.isdir(job_dir): if os.path.isdir(job_dir):
for fname in os.listdir(tmp_dir): for fname in os.listdir(tmp_dir):
shutil.move(os.path.join(tmp_dir, fname), os.path.join(job_dir, fname)) shutil.move(os.path.join(tmp_dir, fname), os.path.join(job_dir, fname))
@ -2823,17 +2854,41 @@ async def restore_project(job_id: str, request: Request):
'status': 'completed', 'status': 'completed',
'logs': ["♻️ Project restored from your library."], 'logs': ["♻️ Project restored from your library."],
'output_dir': job_dir, 'output_dir': job_dir,
'user_id': str(user.id), 'user_id': user_id,
'result': {'clips': clips, 'cost_analysis': data.get('cost_analysis')}, 'result': {'clips': clips, 'cost_analysis': data.get('cost_analysis')},
} }
if pulled:
print(f"♻️ Restored {job_id} from the library (working files were gone).")
return pulled
return {
"job_id": job_id, async def _restore_for_public_path(job_id: str) -> bool:
"status": "completed", """Restorer for the /videos mount: a miss under /videos/<job_id>/ pulls
"result": jobs[job_id]['result'], the project back from R2 for its owner, without a session. Those files
"project_state": proj.state, are public by job id already (the mount has no auth), so this grants
"title": proj.title, nothing new; it only stops a reopened project's players from 404ing
} while the API side is still restoring it. True means "look again".
"""
if not BILLING_ENABLED or not _JOB_ID_RE.match(job_id or ""):
return False
from sqlalchemy import select
from cloud.models import Project
from cloud import database as cloud_db
async with cloud_db.session() as s:
proj = (await s.execute(
select(Project).where(Project.job_id == job_id)
)).scalar_one_or_none()
if proj is None:
return False
try:
await _restore_job_files(job_id, proj, str(proj.user_id))
except HTTPException as e:
print(f"⚠️ /videos restore of {job_id} failed: {e.detail}")
return False
except Exception as e:
print(f"⚠️ /videos restore of {job_id} failed: {e}")
return False
return True
async def _ensure_job_files(job_id: str, request: Request) -> bool: async def _ensure_job_files(job_id: str, request: Request) -> bool:
@ -2854,7 +2909,6 @@ async def _ensure_job_files(job_id: str, request: Request) -> bool:
return False return False
try: try:
await restore_project(job_id, request) await restore_project(job_id, request)
print(f"♻️ Auto-restored {job_id} from the library (working files were gone).")
return True return True
except HTTPException: except HTTPException:
return False return False

47
restoring_static.py Normal file
View file

@ -0,0 +1,47 @@
"""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)

View file

@ -0,0 +1,95 @@
"""/videos serving: a miss under /videos/<job_id>/ asks the restorer to bring
the job back before answering 404, keeping StaticFiles' Range support.
Observed 6-sep-2026: reopening a project whose working files were gone fired
15 transcript requests (which restored it from R2 in ~25 s) and 15 <video>
loads at once; every player got a 404 until the user reloaded.
"""
import os
import pytest
from starlette.applications import Starlette
from starlette.testclient import TestClient
from restoring_static import RestoringStaticFiles
JOB = "cff3ad6c-c1e6-48e8-9a75-be74f39779c5"
def _app(tmp_path, restorer):
app = Starlette()
app.mount("/videos", RestoringStaticFiles(directory=str(tmp_path), restorer=restorer))
return TestClient(app), tmp_path
def test_existing_file_is_served_without_calling_the_restorer(tmp_path):
calls = []
async def restorer(job_id):
calls.append(job_id)
return True
client, root = _app(tmp_path, restorer)
os.makedirs(root / JOB)
(root / JOB / "clip_1.mp4").write_bytes(b"x" * 100)
r = client.get(f"/videos/{JOB}/clip_1.mp4")
assert r.status_code == 200 and calls == []
def test_missing_file_is_restored_then_served_with_ranges(tmp_path):
calls = []
async def restorer(job_id):
calls.append(job_id)
os.makedirs(root / job_id, exist_ok=True)
(root / job_id / "clip_1.mp4").write_bytes(bytes(range(100)))
return True
client, root = _app(tmp_path, restorer)
r = client.get(f"/videos/{JOB}/clip_1.mp4", headers={"Range": "bytes=10-19"})
assert calls == [JOB]
# The player's seek keeps working: the second lookup is the normal
# StaticFiles one. Range support itself depends on the starlette version
# (prod's honours it, an older local one answers the whole file).
if r.status_code == 206:
assert r.content == bytes(range(10, 20))
assert r.headers["content-range"] == "bytes 10-19/100"
else:
assert r.status_code == 200 and r.content == bytes(range(100))
def test_restorer_false_or_failure_keeps_the_404(tmp_path):
async def says_no(job_id):
return False
async def blows_up(job_id):
raise RuntimeError("R2 down")
for restorer in (says_no, blows_up):
client, _root = _app(tmp_path, restorer)
assert client.get(f"/videos/{JOB}/clip_1.mp4").status_code == 404
def test_paths_without_a_job_segment_never_call_the_restorer(tmp_path):
calls = []
async def restorer(job_id):
calls.append(job_id)
return True
client, _root = _app(tmp_path, restorer)
assert client.get("/videos/robots.txt").status_code == 404
assert calls == []
def test_no_restorer_behaves_like_staticfiles(tmp_path):
client, _root = _app(tmp_path, None)
assert client.get(f"/videos/{JOB}/clip_1.mp4").status_code == 404
def test_app_job_id_guard():
"""The app-side restorer only hits the database for uuid-shaped ids."""
app_mod = pytest.importorskip("app")
assert app_mod._JOB_ID_RE.match(JOB)
for bad in ("thumbnails", "..", "cff3ad6c", "CFF3AD6C-C1E6-48E8-9A75-BE74F39779C5"):
assert not app_mod._JOB_ID_RE.match(bad)