"""S3-compatible object storage (DigitalOcean Spaces). The bucket is private: access only through presigned URLs.""" import asyncio from dataclasses import dataclass from functools import lru_cache import boto3 from botocore.client import Config from botocore.exceptions import ClientError from app.core.config import Settings, get_settings @dataclass(frozen=True) class ObjectInfo: size_bytes: int content_type: str class StorageClient: def __init__(self, settings: Settings): self.bucket = settings.storage_bucket self.upload_ttl = settings.upload_url_ttl_s self.download_ttl = settings.download_url_ttl_s self._s3 = boto3.client( "s3", endpoint_url=settings.storage_endpoint, region_name=settings.storage_region, aws_access_key_id=settings.storage_key, aws_secret_access_key=settings.storage_secret, config=Config(signature_version="s3v4", s3={"addressing_style": "virtual"}), ) def presign_put(self, key: str, content_type: str) -> str: return self._s3.generate_presigned_url( "put_object", Params={"Bucket": self.bucket, "Key": key, "ContentType": content_type}, ExpiresIn=self.upload_ttl) def presign_get(self, key: str) -> str: return self._s3.generate_presigned_url( "get_object", Params={"Bucket": self.bucket, "Key": key}, ExpiresIn=self.download_ttl) async def head(self, key: str) -> ObjectInfo | None: try: meta = await asyncio.to_thread(self._s3.head_object, Bucket=self.bucket, Key=key) except ClientError as exc: if exc.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"): return None raise return ObjectInfo(size_bytes=int(meta["ContentLength"]), content_type=meta.get("ContentType", "")) async def put_bytes(self, key: str, data: bytes, content_type: str) -> None: await asyncio.to_thread(self._s3.put_object, Bucket=self.bucket, Key=key, Body=data, ContentType=content_type) async def read_prefix(self, key: str, length: int) -> bytes: response = await asyncio.to_thread( self._s3.get_object, Bucket=self.bucket, Key=key, Range=f"bytes=0-{length - 1}") return await asyncio.to_thread(response["Body"].read) async def delete_many(self, keys: list[str]) -> None: for start in range(0, len(keys), 1000): batch = [{"Key": k} for k in keys[start:start + 1000]] if batch: await asyncio.to_thread( self._s3.delete_objects, Bucket=self.bucket, Delete={"Objects": batch, "Quiet": True}) @lru_cache def get_storage() -> StorageClient: return StorageClient(get_settings())