forked from mtusi2026/mtusi2026lab7
127 lines
5.5 KiB
Python
127 lines
5.5 KiB
Python
"""Bounded S3 operations; synchronous SDK calls run outside the event loop."""
|
|
from dataclasses import dataclass
|
|
from hashlib import sha256
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import boto3
|
|
from botocore.config import Config
|
|
from botocore.exceptions import BotoCoreError, ClientError
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
from ..errors import ApiError
|
|
from .. import telemetry as tel
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class S3Settings:
|
|
endpoint: str
|
|
region: str
|
|
bucket: str
|
|
access_key: str
|
|
secret_key: str
|
|
max_bytes: int
|
|
max_pixels: int
|
|
|
|
@classmethod
|
|
def load(cls):
|
|
def secret(name):
|
|
path = os.environ.get(name + "_FILE")
|
|
result = Path(path).read_text().strip() if path else os.environ.get(name, "")
|
|
if not result:
|
|
raise ValueError(f"Missing {name}")
|
|
return result
|
|
|
|
max_bytes = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
|
max_pixels = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
|
if not 1 <= max_bytes <= 10485760 or not 1 <= max_pixels <= 40000000:
|
|
raise ValueError("Image limits exceed contract")
|
|
endpoint = os.environ.get("S3_ENDPOINT", "https://s3:8333")
|
|
if not endpoint.startswith("https://") or not os.environ.get("AWS_CA_BUNDLE"):
|
|
raise ValueError("S3 requires HTTPS and AWS_CA_BUNDLE")
|
|
return cls(endpoint,
|
|
os.environ.get("S3_REGION", "us-east-1"),
|
|
os.environ.get("S3_BUCKET", "messenger-attachments"),
|
|
secret("S3_ACCESS_KEY_ID"), secret("S3_SECRET_ACCESS_KEY"),
|
|
max_bytes, max_pixels)
|
|
|
|
|
|
class S3Store:
|
|
def __init__(self, settings):
|
|
self.settings = settings
|
|
self.client = boto3.client(
|
|
"s3", endpoint_url=settings.endpoint, region_name=settings.region,
|
|
aws_access_key_id=settings.access_key, aws_secret_access_key=settings.secret_key,
|
|
config=Config(signature_version="s3v4", connect_timeout=2, read_timeout=5,
|
|
retries={"total_max_attempts": 1},
|
|
s3={"addressing_style": "path"},
|
|
request_checksum_calculation="when_required",
|
|
response_checksum_validation="when_required"),
|
|
)
|
|
|
|
async def call(self, method, **kwargs):
|
|
with tel.tracer.start_as_current_span("s3." + method, kind=tel.SpanKind.CLIENT, record_exception=False, set_status_on_exception=False) as span:
|
|
try:
|
|
return await run_in_threadpool(getattr(self.client, method), **kwargs)
|
|
except (BotoCoreError, ClientError, OSError) as error:
|
|
span.set_status(tel.Status(tel.StatusCode.ERROR))
|
|
raise ApiError(503, "unavailable", "S3 недоступно") from error
|
|
|
|
async def ready(self):
|
|
await self.call("head_bucket", Bucket=self.settings.bucket)
|
|
|
|
async def put(self, key, file, size, content_type):
|
|
file.seek(0)
|
|
await self.call("put_object", Bucket=self.settings.bucket, Key=key,
|
|
Body=file, ContentLength=size, ContentType=content_type)
|
|
|
|
async def copy(self, source_key: str, destination_key: str, content_type: str) -> None:
|
|
await self.call(
|
|
"copy_object", Bucket=self.settings.bucket, Key=destination_key,
|
|
CopySource={"Bucket": self.settings.bucket, "Key": source_key},
|
|
ContentType=content_type, MetadataDirective="REPLACE",
|
|
)
|
|
|
|
async def list(self, prefix: str) -> dict[str, object]:
|
|
"""Return every object under a controlled prefix, handling S3 pagination."""
|
|
objects, _ = await self.list_with_pages(prefix)
|
|
return objects
|
|
|
|
async def list_with_pages(self, prefix: str) -> tuple[dict[str, object], int]:
|
|
"""Return inventory and number of S3 ListObjectsV2 pages consumed."""
|
|
result: dict[str, object] = {}
|
|
token = None
|
|
pages = 0
|
|
while True:
|
|
args = {"Bucket": self.settings.bucket, "Prefix": prefix}
|
|
if token:
|
|
args["ContinuationToken"] = token
|
|
page = await self.call("list_objects_v2", **args)
|
|
pages += 1
|
|
for item in page.get("Contents", []):
|
|
result[item["Key"]] = item["LastModified"]
|
|
if not page.get("IsTruncated"):
|
|
return result, pages
|
|
token = page["NextContinuationToken"]
|
|
|
|
async def delete(self, key: str) -> None:
|
|
await self.call("delete_object", Bucket=self.settings.bucket, Key=key)
|
|
|
|
async def download(self, attachment):
|
|
return await self.download_key(attachment["original_key"], attachment["size_bytes"], attachment["sha256"])
|
|
|
|
async def download_key(self, key: str, expected_size: int | None = None,
|
|
expected_sha256: str | None = None) -> bytes:
|
|
response = await self.call("get_object", Bucket=self.settings.bucket, Key=key)
|
|
body = response["Body"]
|
|
try:
|
|
data = await run_in_threadpool(body.read, self.settings.max_bytes + 1)
|
|
except (BotoCoreError, OSError) as error:
|
|
raise ApiError(503, "unavailable", "S3 недоступно") from error
|
|
finally:
|
|
body.close()
|
|
if ((expected_size is not None and len(data) != expected_size) or
|
|
(expected_sha256 is not None and sha256(data).hexdigest() != expected_sha256)):
|
|
raise ApiError(503, "unavailable", "Оригинал недоступен")
|
|
return data
|