Files
filehost/backend/app/services/r2.py
T
2026-03-08 21:11:43 +05:30

49 lines
1.4 KiB
Python

import asyncio
from functools import lru_cache
from typing import BinaryIO
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 _upload_fileobj(file_obj: BinaryIO, object_name: str, content_type: str) -> str:
"""Stream file to R2. boto3 automatically uses multipart for large files."""
key = f"files/{object_name}"
_get_r2_client().upload_fileobj(
file_obj,
settings.R2_BUCKET,
key,
ExtraArgs={"ContentType": content_type},
)
return f"{settings.PUBLIC_URL}/files/{object_name}"
async def upload_file(file_obj: BinaryIO, object_name: str, content_type: str) -> str:
"""Upload a file to R2 storage."""
try:
url = await asyncio.to_thread(
_upload_fileobj, file_obj, object_name, content_type
)
except (BotoCoreError, ClientError) as exc:
raise RuntimeError(f"R2 upload failed: {exc}") from exc
return url