creative-brain-os / scripts /check_r2.py
kpranav022's picture
Claude Opus 4.8
Resolve the edit-key niche from the DB so the editor finds clips on R2
5812e2e
Raw History Blame Contribute Delete
2.96 kB
"""Verify R2 credentials and the public domain end to end.
Uploads a tiny test object, fetches it back over the S3 API AND over the public
URL, then deletes it. Run after filling the R2_* values in .env:
python scripts/check_r2.py
"""
from __future__ import annotations
import sys
import uuid
import httpx
from app.core.config import settings
from app.services import media
def main() -> int:
if not media.using_r2():
print("STORAGE_BACKEND is not 'r2' — set STORAGE_BACKEND=r2 in .env first.")
return 1
endpoint = settings.r2_endpoint_url or f"https://{settings.r2_account_id}.r2.cloudflarestorage.com"
print(f"endpoint : {endpoint}")
print(f"bucket : {settings.r2_bucket}")
print(f"prefix : {settings.r2_prefix}")
print(f"base url : {settings.r2_public_base_url}")
missing = [
name
for name, val in [
("R2_BUCKET", settings.r2_bucket),
("R2_ACCESS_KEY_ID", settings.r2_access_key_id),
("R2_SECRET_ACCESS_KEY", settings.r2_secret_access_key),
]
if not val
]
if missing or not (settings.r2_endpoint_url or settings.r2_account_id):
print(f"\nMissing settings: {', '.join(missing) or 'R2_ENDPOINT_URL / R2_ACCOUNT_ID'}")
return 1
key = f"{settings.r2_prefix.strip('/')}/_healthcheck/{uuid.uuid4().hex}.txt"
payload = b"creative-brain r2 check"
print("\n1) upload via S3 API...")
try:
media.put(key, payload, content_type="text/plain")
print(f" ok -> {key}")
except Exception as exc:
print(f" FAILED: {type(exc).__name__}: {exc}")
print(" -> check the access key/secret, bucket name and endpoint.")
return 1
print("2) read back via S3 API...")
try:
assert media.get(key) == payload
print(" ok")
except Exception as exc:
print(f" FAILED: {exc}")
return 1
url = media.url_for(key)
print(f"3) fetch over the public domain...\n {url}")
try:
r = httpx.get(url, timeout=20, follow_redirects=True)
if r.status_code == 200 and r.content == payload:
print(" ok — the custom domain serves the bucket")
else:
print(f" NOT PUBLIC (HTTP {r.status_code})")
print(" -> bind this domain to the bucket in Cloudflare (R2 > Settings >")
print(" Public access > Custom domain), or videos won't load in a browser.")
except Exception as exc:
print(f" NOT REACHABLE: {exc}")
print(" -> the DNS/custom-domain binding is probably missing.")
print("4) cleanup...")
try:
media._r2().delete_object(Bucket=settings.r2_bucket, Key=key)
print(" ok")
except Exception as exc:
print(f" left behind ({exc}) — harmless")
print("\nS3 API works. If step 3 passed too, you're fully ready.")
return 0
if __name__ == "__main__":
sys.exit(main())