From 080dd5780be53d733f3bc63730a2edae37f15369 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Sun, 23 Aug 2026 13:49:08 +0200 Subject: [PATCH] feat(delivery): serve clips from a custom R2 domain, and show download progress Measured 22-ago-2026 against prod, on one 46 MB / 52 s clip: origin -> itself through Traefik 130 MB/s origin -> a datacenter client 838 KB/s origin -> the author's browser 90 KB/s (8.5 min for one clip) R2 S3 endpoint -> the server 11 MB/s, 206 R2 S3 endpoint -> that browser 503, every single request So the API process is not the bottleneck (it serves the file at 130 MB/s while the box sits at 0.01 MB/s of egress); the long path out of Hetzner is. And the fix for that, R2, is unreachable from a browser: *.r2.cloudflarestorage.com is an S3 endpoint, and a presigned GET that curl fetches at 11 MB/s with identical headers returns 503 to Chrome. R2_PUBLIC_BASE points presigned_get() at a custom domain bound to the bucket instead, which serves the same objects through the normal Cloudflare edge. Unset, everything keeps signing S3 URLs exactly as before, so this is inert until the domain exists. Switched at that one choke point because every caller hands the URL to a browser. The download button streamed nothing to the screen while it buffered tens of MB into a blob, which on a slow link is minutes of a button that looks dead. It now reports percentage, which needs Content-Length readable from JS, which needs the CORS middleware to name it in expose_headers. --- app.py | 4 ++++ cloud/config.py | 19 +++++++++++++++ cloud/storage.py | 14 +++++++++++ dashboard/src/components/ResultCard.jsx | 31 +++++++++++++++++++++++-- 4 files changed, 66 insertions(+), 2 deletions(-) diff --git a/app.py b/app.py index 39a08e4..f9588ae 100644 --- a/app.py +++ b/app.py @@ -1240,6 +1240,10 @@ app.add_middleware( allow_credentials=True, allow_methods=["*"], allow_headers=["*"], + # Without this the browser hides them from fetch(), so the clip download had + # no total to measure against and could not show progress. Safelisted or not, + # they only become readable to JS once they are named here. + expose_headers=["Content-Length", "Content-Range", "Accept-Ranges"], ) # Mount static files for serving videos diff --git a/cloud/config.py b/cloud/config.py index 5d65c54..99ffbd3 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -249,6 +249,25 @@ class Settings: def r2_secret_access_key(self) -> str: return os.environ.get("R2_SECRET_ACCESS_KEY", "") + @property + def r2_public_base(self) -> str: + """Base URL of a custom domain bound to the R2 bucket, e.g. + https://cdn.openshorts.app — unset means keep signing S3 URLs. + + The S3 endpoint (*.r2.cloudflarestorage.com) is not a browser-facing + endpoint: measured 22-ago-2026, a presigned GET from Chrome on a Spanish + residential line returns 503 on every attempt while the same URL with the + same headers returns 206 at 11 MB/s from a datacenter. A custom domain + serves the same objects through the normal Cloudflare edge, which both + fixes that and puts the bytes on Cloudflare's network instead of a single + long path out of Hetzner (measured to the same client: 90 KB/s). + + Objects under it are public. That matches the capability model already in + production for /videos/{job_id}/... (unauthenticated, the UUID is the + capability); anything stricter needs a Worker checking a signed token. + """ + return os.environ.get("R2_PUBLIC_BASE", "").strip().rstrip("/") + @property def r2_configured(self) -> bool: return bool(self.r2_endpoint and self.r2_bucket and self.r2_access_key_id diff --git a/cloud/storage.py b/cloud/storage.py index fb01c52..63b3dff 100644 --- a/cloud/storage.py +++ b/cloud/storage.py @@ -4,6 +4,8 @@ Layout: users///. Presigned URLs give private, time-limited view/download links. Delete-by-prefix wipes a user's whole library when their subscription's grace period ends. """ +from urllib.parse import quote + import boto3 from botocore.config import Config @@ -65,6 +67,18 @@ def list_keys(prefix) -> list: def presigned_get(key, expires=3600, download_name=None) -> str: + """A URL a client can GET. Signed against the S3 endpoint by default; a plain + URL on the bucket's custom domain when R2_PUBLIC_BASE is set. + + Switching here rather than at each call site on purpose: every caller hands + the result to a browser, and the S3 endpoint is the one variant browsers + cannot reliably fetch (see settings.r2_public_base). The custom domain has no + equivalent of ResponseContentDisposition, so a download keeps the object's + own name, which is already the clip filename. + """ + base = settings.r2_public_base + if base: + return f"{base}/{quote(key, safe='/')}" params = {"Bucket": settings.r2_bucket, "Key": key} if download_name: params["ResponseContentDisposition"] = f'attachment; filename="{download_name}"' diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index 1b78899..2757351 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -76,11 +76,35 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey, // their position to save a few seconds of buffering is a bad trade. const [hasPlayed, setHasPlayed] = useState(false); + // A delivered clip is tens of MB, and on a slow link the old silent + // fetch-then-save took minutes with nothing on screen, which reads as a dead + // button. Stream it instead and report progress. + const [downloadPct, setDownloadPct] = useState(null); + const downloadClip = async () => { try { + setDownloadPct(0); const response = await fetch(currentVideoUrl); if (!response.ok) throw new Error('Download failed'); - const blob = await response.blob(); + const total = Number(response.headers.get('content-length')) || 0; + let blob; + // No body reader (old browser) or no length to measure against: fall + // back to the plain path rather than lose the download. + if (!response.body || !total) { + blob = await response.blob(); + } else { + const reader = response.body.getReader(); + const chunks = []; + let received = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(value); + received += value.length; + setDownloadPct(Math.min(99, Math.round((received / total) * 100))); + } + blob = new Blob(chunks, { type: 'video/mp4' }); + } const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; @@ -93,6 +117,8 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey, } catch (err) { console.error('Download error:', err); window.open(currentVideoUrl, '_blank'); + } finally { + setDownloadPct(null); } }; // Latest file that exists ON THE SERVER (blob: previews don't count). @@ -890,7 +916,8 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey, }} className={`${QUIET_BTN}${onEditClip ? ' col-span-2' : ''}`} > - download + + {downloadPct === null ? 'download' : `downloading ${downloadPct}%`}