"""Private S3-compatible store. Object keys are server-generated.""" from __future__ import annotations import logging import boto3 from botocore.client import Config from botocore.exceptions import ClientError log = logging.getLogger("messenger.s3") class ObjectStore: def __init__(self, endpoint: str, region: str, bucket: str, access_key: str, secret_key: str): self.bucket = bucket self.client = boto3.client( "s3", endpoint_url=endpoint, region_name=region, aws_access_key_id=access_key, aws_secret_access_key=secret_key, config=Config( s3={"addressing_style": "path"}, signature_version="s3v4", retries={"max_attempts": 3, "mode": "standard"}, connect_timeout=3, read_timeout=20, ), ) def ensure_bucket(self) -> None: try: self.client.head_bucket(Bucket=self.bucket) except ClientError: self.client.create_bucket(Bucket=self.bucket) log.info("bucket ready") def healthy(self) -> bool: try: self.client.head_bucket(Bucket=self.bucket) return True except Exception: log.warning("object store ping failed", exc_info=True) return False def put(self, key: str, data: bytes, content_type: str) -> None: self.client.put_object(Bucket=self.bucket, Key=key, Body=data, ContentType=content_type) def get(self, key: str) -> bytes | None: try: response = self.client.get_object(Bucket=self.bucket, Key=key) except ClientError as exc: code = exc.response.get("Error", {}).get("Code", "") if code in {"404", "NoSuchKey", "NotFound"}: return None raise return response["Body"].read() def delete(self, key: str) -> None: self.client.delete_object(Bucket=self.bucket, Key=key)