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.
This commit is contained in:
juancarlos.cavero 2026-08-23 13:49:08 +02:00
parent e0fa3fd591
commit 080dd5780b
4 changed files with 66 additions and 2 deletions

4
app.py
View file

@ -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

View file

@ -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

View file

@ -4,6 +4,8 @@ Layout: users/<user_id>/<job_id>/<filename>. 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}"'

View file

@ -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 size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" /> download
<Download size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" />
{downloadPct === null ? 'download' : `downloading ${downloadPct}%`}
</button>
</div>
</div>