"""Small bounded wrapper around the private S3-compatible object store.""" from __future__ import annotations from collections.abc import Iterator from typing import BinaryIO from urllib.parse import urlparse from minio import Minio from minio.error import S3Error from .config import Settings class ObjectStoreUnavailable(Exception): """The S3 dependency cannot safely complete the requested operation.""" class ObjectStore: def __init__(self, settings: Settings) -> None: parsed = urlparse(settings.s3_endpoint) self.bucket = settings.s3_bucket self.client = Minio( parsed.netloc, access_key=settings.s3_access_key_id, secret_key=settings.s3_secret_access_key, secure=parsed.scheme == "https", region=settings.s3_region, ) def ensure_available(self) -> None: """Probe the bucket created by the separate privileged bootstrap job.""" try: if not self.client.bucket_exists(self.bucket): raise ObjectStoreUnavailable("bucket_missing") except ObjectStoreUnavailable: raise except Exception as exc: # MinIO also raises transport exceptions raise ObjectStoreUnavailable(type(exc).__name__) from None def put(self, key: str, source: BinaryIO, size: int, content_type: str) -> None: try: source.seek(0) self.client.put_object( self.bucket, key, source, size, content_type=content_type ) except Exception as exc: raise ObjectStoreUnavailable(type(exc).__name__) from None def delete(self, key: str) -> None: try: self.client.remove_object(self.bucket, key) except Exception: # Best-effort compensation is intentionally silent here; callers # return the DB/S3 failure without leaking storage internals. pass def ensure_object(self, key: str) -> None: """Fail before HTTP headers if a ready metadata row lost its object.""" try: self.client.stat_object(self.bucket, key) except Exception as exc: raise ObjectStoreUnavailable(type(exc).__name__) from None def chunks(self, key: str, chunk_size: int = 64 * 1024) -> Iterator[bytes]: response = None try: response = self.client.get_object(self.bucket, key) yield from response.stream(chunk_size) except S3Error as exc: raise ObjectStoreUnavailable(type(exc).__name__) from None except Exception as exc: raise ObjectStoreUnavailable(type(exc).__name__) from None finally: if response is not None: response.close() response.release_conn()