from __future__ import annotations import asyncio from collections.abc import Iterable from datetime import timedelta import logging from pathlib import PurePosixPath from minio import Minio from minio.error import MinioException, S3Error from .config import MediaStorageSettings logger = logging.getLogger(__name__) class MediaUrlResolutionError(RuntimeError): pass def normalize_storage_key(storage_key: str) -> str: normalized = storage_key.strip().lstrip("/") if not normalized: raise MediaUrlResolutionError("storage_key must not be blank") path = PurePosixPath(normalized) if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts): raise MediaUrlResolutionError(f"Invalid storage_key: {storage_key!r}") return path.as_posix() class MediaUrlResolver: """ Produces short-lived S3/MinIO GET URLs. The resolver does not expose credentials to clients and does not perform an object-existence request before signing. A missing object therefore results in a normal image HTTP error at fetch time, avoiding an extra storage round trip for every API response. """ def __init__( self, *, client: Minio, bucket: str, expires: timedelta, max_concurrency: int = 16, ) -> None: if not bucket.strip(): raise ValueError("bucket must not be blank") if expires.total_seconds() < 60: raise ValueError("presigned URL expiry must be at least 60 seconds") if max_concurrency < 1: raise ValueError("max_concurrency must be >= 1") self._client = client self._bucket = bucket.strip() self._expires = expires self._semaphore = asyncio.Semaphore(max_concurrency) @classmethod def from_settings(cls, settings: MediaStorageSettings) -> "MediaUrlResolver": client = Minio( settings.endpoint, access_key=settings.access_key, secret_key=settings.secret_key, secure=settings.secure, region=settings.region, ) return cls( client=client, bucket=settings.bucket, expires=timedelta(seconds=settings.url_ttl_seconds), ) async def resolve(self, storage_key: str) -> str: object_name = normalize_storage_key(storage_key) async with self._semaphore: try: return await asyncio.to_thread( self._client.presigned_get_object, self._bucket, object_name, self._expires, ) except (S3Error, MinioException, ValueError) as exc: logger.exception( "Unable to create media presigned URL: bucket=%s object=%s", self._bucket, object_name, ) raise MediaUrlResolutionError( f"Unable to create presigned media URL for {object_name!r}" ) from exc async def resolve_many(self, storage_keys: Iterable[str]) -> dict[str, str]: unique_keys = list(dict.fromkeys(storage_keys)) if not unique_keys: return {} async def resolve_one(key: str) -> tuple[str, str]: return key, await self.resolve(key) resolved = await asyncio.gather(*(resolve_one(key) for key in unique_keys)) return dict(resolved)