forked from mtusi2026/mtusi2026lab4
196 lines
7.8 KiB
Python
196 lines
7.8 KiB
Python
"""Приватное S3-хранилище: только байты и служебные операции над объектами.
|
|
|
|
Метаданные вложений живут в PostgreSQL; этот модуль не знает о чатах и правах.
|
|
Ключ объекта всегда назначает сервер. Ошибки S3 преобразуются в два типа:
|
|
`StorageObjectMissing` (404) и `StorageUnavailable` (503), чтобы наружу не
|
|
уходили детали boto3/MinIO.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timezone
|
|
from typing import Any, BinaryIO
|
|
|
|
import anyio
|
|
from botocore.config import Config as BotoConfig
|
|
from botocore.exceptions import BotoCoreError, ClientError
|
|
|
|
from .config import Config
|
|
|
|
CHUNK_SIZE = 64 * 1024
|
|
MISSING_CODES = {"404", "NoSuchKey", "NotFound", "NoSuchBucket"}
|
|
|
|
|
|
class StorageUnavailable(RuntimeError):
|
|
"""S3/MinIO не ответил или вернул ошибку, которую нельзя исправить запросом."""
|
|
|
|
|
|
class StorageObjectMissing(RuntimeError):
|
|
"""Объект отсутствует в bucket (оригинал потерян или ключ неверен)."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class S3Object:
|
|
"""Открытый поток объекта и его наблюдаемый размер."""
|
|
|
|
body: Any
|
|
size_bytes: int
|
|
content_type: str | None
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ObjectInfo:
|
|
"""Элемент листинга bucket для сверки."""
|
|
|
|
key: str
|
|
size_bytes: int
|
|
last_modified: datetime
|
|
|
|
|
|
def _is_missing(error: ClientError) -> bool:
|
|
response = getattr(error, "response", {}) or {}
|
|
code = str((response.get("Error") or {}).get("Code", ""))
|
|
status = int((response.get("ResponseMetadata") or {}).get("HTTPStatusCode", 0) or 0)
|
|
return code in MISSING_CODES or status == 404
|
|
|
|
|
|
class S3Storage:
|
|
"""Один boto3-клиент на процесс; вызовы уходят в рабочий поток."""
|
|
|
|
def __init__(self, config: Config) -> None:
|
|
self._bucket = config.s3_bucket
|
|
self._prefix = config.s3_key_prefix
|
|
boto_config = BotoConfig(
|
|
signature_version="s3v4",
|
|
s3={"addressing_style": "path"},
|
|
connect_timeout=config.s3_connect_timeout_seconds,
|
|
read_timeout=config.s3_read_timeout_seconds,
|
|
retries={"max_attempts": config.s3_max_attempts, "mode": "standard"},
|
|
max_pool_connections=32,
|
|
)
|
|
import boto3
|
|
|
|
self._client = boto3.session.Session().client(
|
|
"s3",
|
|
endpoint_url=config.s3_endpoint,
|
|
region_name=config.s3_region,
|
|
aws_access_key_id=config.s3_access_key_id,
|
|
aws_secret_access_key=config.s3_secret_access_key,
|
|
config=boto_config,
|
|
)
|
|
|
|
@property
|
|
def bucket(self) -> str:
|
|
return self._bucket
|
|
|
|
@property
|
|
def key_prefix(self) -> str:
|
|
return self._prefix
|
|
|
|
def new_key(self, attachment_id: str) -> str:
|
|
"""Ключ назначает сервер; filename и путь клиента в него не попадают."""
|
|
return f"{self._prefix}{attachment_id}"
|
|
|
|
async def ping(self) -> None:
|
|
"""Готовность: листинг одного объекта под служебным префиксом.
|
|
|
|
Это проверяет и доступность S3, и наличие bucket, и право ListBucket,
|
|
которое выдано API-пользователю только на префикс вложений.
|
|
"""
|
|
try:
|
|
await anyio.to_thread.run_sync(self._list_one)
|
|
except (BotoCoreError, ClientError, OSError) as exc:
|
|
raise StorageUnavailable("S3 не отвечает") from exc
|
|
|
|
def _list_one(self) -> None:
|
|
self._client.list_objects_v2(Bucket=self._bucket, Prefix=self._prefix, MaxKeys=1)
|
|
|
|
async def put(
|
|
self,
|
|
key: str,
|
|
file: BinaryIO,
|
|
*,
|
|
content_type: str,
|
|
size_bytes: int,
|
|
sha256: str,
|
|
md5_hex: str,
|
|
) -> None:
|
|
"""Загружает один объект и проверяет, что S3 сохранил ровно эти байты."""
|
|
try:
|
|
response = await anyio.to_thread.run_sync(
|
|
lambda: self._client.put_object(
|
|
Bucket=self._bucket,
|
|
Key=key,
|
|
Body=file,
|
|
ContentLength=size_bytes,
|
|
ContentType=content_type,
|
|
Metadata={"sha256": sha256},
|
|
)
|
|
)
|
|
except (BotoCoreError, ClientError, OSError) as exc:
|
|
raise StorageUnavailable("S3 не принял объект") from exc
|
|
etag = str(response.get("ETag", "")).strip('"').lower()
|
|
# Для одиночного PUT ETag — MD5 тела; это дешёвая проверка целостности
|
|
# передачи. Если S3 не вернул ETag, полагаемся на SHA-256 в метаданных.
|
|
if etag and etag != md5_hex.lower():
|
|
try:
|
|
await self.delete(key)
|
|
except StorageUnavailable:
|
|
pass
|
|
raise StorageUnavailable("S3 сохранил объект с другим ETag")
|
|
|
|
async def open(self, key: str) -> S3Object:
|
|
"""Открывает объект для потоковой отдачи без redirect."""
|
|
try:
|
|
response = await anyio.to_thread.run_sync(
|
|
lambda: self._client.get_object(Bucket=self._bucket, Key=key)
|
|
)
|
|
except ClientError as exc:
|
|
if _is_missing(exc):
|
|
raise StorageObjectMissing("Объект отсутствует в S3") from exc
|
|
raise StorageUnavailable("S3 не отдал объект") from exc
|
|
except (BotoCoreError, OSError) as exc:
|
|
raise StorageUnavailable("S3 не отдал объект") from exc
|
|
return S3Object(
|
|
body=response["Body"],
|
|
size_bytes=int(response.get("ContentLength", 0)),
|
|
content_type=response.get("ContentType"),
|
|
)
|
|
|
|
async def delete(self, key: str) -> None:
|
|
try:
|
|
await anyio.to_thread.run_sync(
|
|
lambda: self._client.delete_object(Bucket=self._bucket, Key=key)
|
|
)
|
|
except (BotoCoreError, ClientError, OSError) as exc:
|
|
raise StorageUnavailable("S3 не удалил объект") from exc
|
|
|
|
async def list_objects(self) -> list[ObjectInfo]:
|
|
"""Все объекты под префиксом вложений (страницы по 1000)."""
|
|
try:
|
|
return await anyio.to_thread.run_sync(self._list_all)
|
|
except (BotoCoreError, ClientError, OSError) as exc:
|
|
raise StorageUnavailable("S3 не отдал список объектов") from exc
|
|
|
|
def _list_all(self) -> list[ObjectInfo]:
|
|
paginator = self._client.get_paginator("list_objects_v2")
|
|
result: list[ObjectInfo] = []
|
|
for page in paginator.paginate(Bucket=self._bucket, Prefix=self._prefix):
|
|
for item in page.get("Contents", []) or []:
|
|
last_modified = item["LastModified"]
|
|
if last_modified.tzinfo is None:
|
|
last_modified = last_modified.replace(tzinfo=timezone.utc)
|
|
result.append(
|
|
ObjectInfo(
|
|
key=str(item["Key"]),
|
|
size_bytes=int(item.get("Size", 0)),
|
|
last_modified=last_modified,
|
|
)
|
|
)
|
|
return result
|
|
|
|
async def close(self) -> None:
|
|
close = getattr(self._client, "close", None)
|
|
if close is not None:
|
|
await anyio.to_thread.run_sync(close)
|