lab4 for lab5

This commit is contained in:
Матвей
2026-10-26 10:05:24 +03:00
parent 276dbdad8a
commit 3b67201e5e
40 changed files with 3522 additions and 0 deletions
+110
View File
@@ -0,0 +1,110 @@
"""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
@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")
return cls(os.environ.get("S3_ENDPOINT", "http://s3:8333"),
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):
try:
return await run_in_threadpool(getattr(self.client, method), **kwargs)
except (BotoCoreError, ClientError, OSError) as 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 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):
response = await self.call("get_object", Bucket=self.settings.bucket,
Key=attachment["object_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 (len(data) != attachment["size_bytes"] or
sha256(data).hexdigest() != attachment["sha256"]):
raise ApiError(503, "unavailable", "Оригинал недоступен")
return data