import asyncio from functools import lru_cache import boto3 from botocore.client import Config from botocore.exceptions import BotoCoreError, ClientError from app.config.settings import settings @lru_cache(maxsize=1) def _get_r2_client(): """Return a module-level singleton boto3 S3 client for R2.""" return boto3.client( "s3", endpoint_url=settings.R2_ENDPOINT, aws_access_key_id=settings.R2_ACCESS_KEY, aws_secret_access_key=settings.R2_SECRET_KEY, config=Config(signature_version="s3v4"), region_name="auto", ) def _put_object(object_name: str, file_bytes: bytes, content_type: str) -> str: """Blocking S3 put""" key = f"files/{object_name}" _get_r2_client().put_object( Bucket=settings.R2_BUCKET, Key=key, Body=file_bytes, ContentType=content_type, ) return f"{settings.PUBLIC_URL}/files/{object_name}" async def upload_file(file_bytes: bytes, object_name: str, content_type: str) -> str: """Upload a file to R2 storage""" try: url = await asyncio.to_thread( _put_object, object_name, file_bytes, content_type ) except (BotoCoreError, ClientError) as exc: raise RuntimeError(f"R2 upload failed: {exc}") from exc return url