"""Private S3 access with bounded network waits; never expose storage keys in API.""" import os from contextlib import contextmanager import boto3 from botocore.config import Config from botocore.exceptions import BotoCoreError, ClientError from .config import secret from .domain import Failure from .telemetry import operation class ObjectStorage: def __init__(self, admin=False): self.bucket = os.getenv("S3_BUCKET", "messenger") prefix = "S3_ADMIN" if admin else "S3" self.client = boto3.client( "s3", endpoint_url=os.getenv("S3_ENDPOINT", "http://s3:8333"), aws_access_key_id=secret(prefix + "_ACCESS_KEY"), aws_secret_access_key=secret(prefix + "_SECRET_KEY"), region_name="us-east-1", config=Config( connect_timeout=1, read_timeout=2, retries={"total_max_attempts": 1}, s3={"addressing_style": "path"}, request_checksum_calculation="when_required", response_checksum_validation="when_required", ), ) @contextmanager def boundary(self): try: with operation("s3.request", {"rpc.system": "aws-api", "rpc.service": "S3"}): yield except (BotoCoreError, ClientError): raise Failure(503, "Хранилище файлов временно недоступно") from None def put(self, key, fileobj, size, content_type): fileobj.seek(0) with self.boundary(): self.client.put_object( Bucket=self.bucket, Key=key, Body=fileobj, ContentLength=size, ContentType=content_type, ) def get(self, key): try: with operation("s3.get", {"rpc.system": "aws-api", "rpc.service": "S3"}): return self.client.get_object(Bucket=self.bucket, Key=key) except ClientError as exc: if exc.response.get("Error", {}).get("Code") in {"NoSuchKey", "404"}: raise Failure(404, "Объект не найден") from None raise Failure(503, "Хранилище файлов временно недоступно") from None except BotoCoreError: raise Failure(503, "Хранилище файлов временно недоступно") from None def head(self, key): try: with operation("s3.head", {"rpc.system": "aws-api", "rpc.service": "S3"}): return self.client.head_object(Bucket=self.bucket, Key=key) except ClientError as exc: if exc.response.get("Error", {}).get("Code") in {"NoSuchKey", "404", "NotFound"}: return None raise Failure(503, "Хранилище файлов временно недоступно") from None except BotoCoreError: raise Failure(503, "Хранилище файлов временно недоступно") from None def exists(self, key): return self.head(key) is not None def delete(self, key): with self.boundary(): self.client.delete_object(Bucket=self.bucket, Key=key) def objects(self, page_size=100): with self.boundary(): paginator = self.client.get_paginator("list_objects_v2") for page in paginator.paginate( Bucket=self.bucket, PaginationConfig={"PageSize": page_size} ): yield from page.get("Contents", []) def ready(self): try: with self.boundary(): self.client.head_bucket(Bucket=self.bucket) return True except Failure: return False def close(self): self.client.close()