backend/shared/r2.py

74 lines
2.4 KiB
Python

"""Thin boto3 wrapper for R2 (S3-compatible). No image bytes pass through the API."""
from __future__ import annotations
from functools import lru_cache
from src.core.config import get_settings
@lru_cache
def _client():
try:
import boto3
from botocore.config import Config
except ImportError as e:
raise RuntimeError("boto3 not installed: pip install -r requirements.txt") from e
s = get_settings()
if not s.r2_configured:
raise RuntimeError("R2 not configured: set R2_ENDPOINT/R2_ACCESS_KEY_ID/R2_SECRET in .env")
return boto3.client(
"s3",
endpoint_url=s.r2_endpoint,
aws_access_key_id=s.r2_key_id,
aws_secret_access_key=s.r2_secret,
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
region_name="auto",
)
def presign_put(key: str, content_type: str = "application/octet-stream") -> str:
"""Direct-upload URL: browser/app PUTs bytes straight to R2 (saves Class-A + bandwidth)."""
s = get_settings()
return _client().generate_presigned_url(
"put_object",
Params={"Bucket": s.r2_bucket, "Key": key, "ContentType": content_type},
ExpiresIn=s.presign_put_ttl,
)
def presign_get(key: str) -> str:
"""Short-lived read URL for preview/download. Thumbnails preferred over full images."""
s = get_settings()
if s.r2_public_base:
return f"{s.r2_public_base.rstrip('/')}/{key}"
return _client().generate_presigned_url(
"get_object",
Params={"Bucket": s.r2_bucket, "Key": key},
ExpiresIn=s.presign_get_ttl,
)
def head_exists(key: str) -> bool:
s = get_settings()
try:
_client().head_object(Bucket=s.r2_bucket, Key=key)
return True
except Exception:
return False
def get_bytes(key: str) -> bytes:
"""Download an object into memory (for workers/thumbnails, not hot paths)."""
s = get_settings()
obj = _client().get_object(Bucket=s.r2_bucket, Key=key)
return obj["Body"].read()
def put_bytes(key: str, data: bytes, content_type: str = "image/jpeg",
cache_control: str | None = None) -> None:
s = get_settings()
params: dict = {"Bucket": s.r2_bucket, "Key": key, "Body": data,
"ContentType": content_type}
if cache_control:
params["CacheControl"] = cache_control
_client().put_object(**params)