clipwright/cloud/storage.py
juancarlos.cavero 080dd5780b 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.
2026-08-23 13:49:08 +02:00

105 lines
3.4 KiB
Python

"""Cloudflare R2 (S3-compatible) storage for the users' durable video library.
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
from .config import settings
_client = None
def client():
global _client
if _client is None:
_client = boto3.client(
"s3",
endpoint_url=settings.r2_endpoint,
aws_access_key_id=settings.r2_access_key_id,
aws_secret_access_key=settings.r2_secret_access_key,
region_name="auto",
config=Config(signature_version="s3v4", retries={"max_attempts": 3}),
)
return _client
def user_prefix(user_id) -> str:
return f"users/{user_id}/"
def job_key(user_id, job_id, filename) -> str:
return f"users/{user_id}/{job_id}/{filename}"
def upload_file(local_path, key, content_type="video/mp4"):
client().upload_file(local_path, settings.r2_bucket, key,
ExtraArgs={"ContentType": content_type})
def download_file(key, local_path):
client().download_file(settings.r2_bucket, key, local_path)
def delete_key(key):
client().delete_object(Bucket=settings.r2_bucket, Key=key)
def list_keys(prefix) -> list:
"""List every object key under a prefix."""
c = client()
keys = []
token = None
while True:
kw = {"Bucket": settings.r2_bucket, "Prefix": prefix, "MaxKeys": 1000}
if token:
kw["ContinuationToken"] = token
resp = c.list_objects_v2(**kw)
keys.extend(o["Key"] for o in resp.get("Contents", []))
if not resp.get("IsTruncated"):
break
token = resp.get("NextContinuationToken")
return keys
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}"'
return client().generate_presigned_url("get_object", Params=params, ExpiresIn=expires)
def delete_prefix(prefix) -> int:
"""Delete every object under a prefix. Returns the count deleted."""
c = client()
deleted = 0
token = None
while True:
kw = {"Bucket": settings.r2_bucket, "Prefix": prefix, "MaxKeys": 1000}
if token:
kw["ContinuationToken"] = token
resp = c.list_objects_v2(**kw)
objs = [{"Key": o["Key"]} for o in resp.get("Contents", [])]
if objs:
c.delete_objects(Bucket=settings.r2_bucket, Delete={"Objects": objs})
deleted += len(objs)
if not resp.get("IsTruncated"):
break
token = resp.get("NextContinuationToken")
return deleted