"""S3-клиент (MinIO) для lab4/lab5. Object key генерирует сервер: staging: staging///original final: attachments///original variant: attachments/// filename используется только для отображения, не в ключе. """ import os from typing import Optional from uuid import UUID import boto3 from botocore.client import Config from botocore.exceptions import ClientError def _endpoint() -> str: return os.environ["S3_ENDPOINT"] def _bucket() -> str: return os.environ.get("S3_BUCKET", "messenger-attachments") def client(): """Клиент с прикладными credentials (не admin). Явные короткие таймауты: connect/read — чтобы при недоступности S3 запросы падали быстро и LB отдавал 503, а не 504 по своему timeout. """ return boto3.client( "s3", endpoint_url=_endpoint(), region_name=os.environ.get("S3_REGION", "us-east-1"), aws_access_key_id=os.environ["S3_APP_KEY_ID"], aws_secret_access_key=os.environ["S3_APP_SECRET_KEY"], config=Config( signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=2, read_timeout=3, retries={"max_attempts": 0}, ), ) def staging_key(chat_id: UUID, attachment_id: UUID) -> str: """Staging — приватный prefix, worker читает отсюда.""" return "staging/%s/%s/original" % (chat_id, attachment_id) def original_key(chat_id: UUID, attachment_id: UUID) -> str: """Финальный ключ оригинала. Не зависит от filename.""" return "attachments/%s/%s/original" % (chat_id, attachment_id) def variant_key(chat_id: UUID, attachment_id: UUID, variant: str) -> str: return "attachments/%s/%s/%s" % (chat_id, attachment_id, variant) def put_bytes(key: str, data: bytes, content_type: str) -> None: client().put_object( Bucket=_bucket(), Key=key, Body=data, ContentType=content_type, ContentLength=len(data), ) def get_object(key: str): """Возвращает (bytes, content_type). Бросает ClientError при отсутствии.""" resp = client().get_object(Bucket=_bucket(), Key=key) body = resp["Body"].read() ctype = resp.get("ContentType") or "application/octet-stream" return body, ctype def delete_object(key: str) -> None: client().delete_object(Bucket=_bucket(), Key=key) def head_object(key: str) -> Optional[dict]: try: return client().head_object(Bucket=_bucket(), Key=key) except ClientError as exc: if exc.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"): return None raise def list_objects(prefix: str = "attachments/"): """Итератор по объектам bucket. Используется cleanup-сервисом.""" paginator = client().get_paginator("list_objects_v2") for page in paginator.paginate(Bucket=_bucket(), Prefix=prefix): for obj in page.get("Contents", []): yield obj