forked from mtusi2026/mtusi2026lab5
285 lines
11 KiB
Python
285 lines
11 KiB
Python
"""
|
||
Объектное хранилище (S3-совместимое, MinIO) — только БАЙТЫ вложений.
|
||
|
||
- Метаданные (кто, какой чат, sha256, размер, тип) — в PostgreSQL, источник истины.
|
||
- Ключ объекта назначает сервер: originals/<uuid>. Имя файла от клиента
|
||
в ключ не попадает (нет path traversal и подбора чужих ключей по имени).
|
||
- Bucket приватный, API ходит отдельными credentials с правами только на
|
||
этот bucket (см. infra/minio/). Root MinIO у API нет.
|
||
- boto3 синхронный → все вызовы идут в пуле потоков (не блокируют event loop).
|
||
- Таймауты и ограниченные повторы: недоступный S3 даёт 503, а не зависание.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import hashlib
|
||
import io
|
||
import logging
|
||
import time
|
||
from datetime import datetime
|
||
from typing import BinaryIO, Iterator
|
||
|
||
import boto3
|
||
from botocore.config import Config
|
||
from botocore.exceptions import (BotoCoreError, ClientError, ConnectionClosedError,
|
||
ConnectTimeoutError, EndpointConnectionError)
|
||
from fastapi.concurrency import run_in_threadpool
|
||
|
||
from .config import settings
|
||
|
||
log = logging.getLogger("messenger.storage")
|
||
|
||
ORIGINALS_PREFIX = "originals/"
|
||
STAGING_PREFIX = "staging/"
|
||
VARIANTS_PREFIX = "variants/"
|
||
_client = None
|
||
|
||
# Предохранитель (circuit breaker) реплики: если S3 не отвечает на уровне соединения
|
||
# (контейнер остановлен, имя не резолвится), следующие S3_BREAKER_SECONDS секунд
|
||
# запросы к S3 сразу получают 503, не тратя время на DNS/connect и повторы.
|
||
_CONNECTION_ERRORS = (EndpointConnectionError, ConnectTimeoutError, ConnectionClosedError)
|
||
_down_until = 0.0
|
||
|
||
|
||
class StorageUnavailable(Exception):
|
||
"""S3 недоступен/не ответил/отказал → 503."""
|
||
|
||
|
||
class ObjectMissing(Exception):
|
||
"""Объекта нет (NoSuchKey)."""
|
||
|
||
|
||
def object_key(attachment_id) -> str:
|
||
"""Конечный ключ оригинала. С lab5 объект там появляется, когда worker его опубликует."""
|
||
return f"{ORIGINALS_PREFIX}{attachment_id}"
|
||
|
||
|
||
def staging_key(attachment_id) -> str:
|
||
"""lab5: приватный prefix приёма. До 202 оригинал целиком лежит здесь."""
|
||
return f"{STAGING_PREFIX}{attachment_id}"
|
||
|
||
|
||
def variant_key(attachment_id, pipeline_version: int, variant: str, ext: str) -> str:
|
||
"""Детерминированный ключ: повтор job перезаписывает тот же объект теми же байтами,
|
||
второго набора вариантов не появляется."""
|
||
return f"{VARIANTS_PREFIX}{attachment_id}/v{pipeline_version}/{variant}.{ext}"
|
||
|
||
|
||
def make_client():
|
||
return boto3.client(
|
||
"s3",
|
||
endpoint_url=settings.s3_endpoint,
|
||
region_name=settings.s3_region,
|
||
aws_access_key_id=settings.s3_access_key_id or None,
|
||
aws_secret_access_key=settings.s3_secret_access_key or None,
|
||
config=Config(
|
||
signature_version="s3v4",
|
||
s3={"addressing_style": "path"}, # MinIO: http://s3:9000/<bucket>/<key>
|
||
connect_timeout=settings.s3_connect_timeout,
|
||
read_timeout=settings.s3_read_timeout,
|
||
retries={"max_attempts": settings.s3_max_attempts, "mode": "standard"},
|
||
max_pool_connections=max(10, settings.upload_max_concurrent),
|
||
# Контрольную сумму передаём сами (Content-MD5); не включаем
|
||
# aws-chunked/CRC по умолчанию новых botocore — совместимость с MinIO.
|
||
request_checksum_calculation="when_required",
|
||
response_checksum_validation="when_required",
|
||
),
|
||
)
|
||
|
||
|
||
def init() -> None:
|
||
global _client
|
||
_client = make_client()
|
||
|
||
|
||
def client():
|
||
if _client is None:
|
||
init()
|
||
return _client
|
||
|
||
|
||
def _why(exc: Exception) -> str:
|
||
"""Тип и код ошибки S3 для лога (без ключей, подписей и адресов)."""
|
||
if isinstance(exc, ClientError):
|
||
return f"{type(exc).__name__}:{exc.response.get('Error', {}).get('Code', '?')}"
|
||
return type(exc).__name__
|
||
|
||
|
||
def _guard() -> None:
|
||
if time.monotonic() < _down_until:
|
||
raise StorageUnavailable("circuit open")
|
||
|
||
|
||
def ensure_available() -> None:
|
||
"""Быстрый отказ ДО записи журнала загрузки, пока предохранитель открыт."""
|
||
_guard()
|
||
|
||
|
||
def _trip(exc: Exception) -> None:
|
||
global _down_until
|
||
if isinstance(exc, _CONNECTION_ERRORS):
|
||
_down_until = time.monotonic() + settings.s3_breaker_seconds
|
||
|
||
|
||
def _is_missing(exc: ClientError) -> bool:
|
||
code = exc.response.get("Error", {}).get("Code", "")
|
||
return code in ("NoSuchKey", "404", "NotFound")
|
||
|
||
|
||
# ----------------------------------------------------------- синхронные вызовы
|
||
def put_sync(key: str, body: BinaryIO, size: int, content_type: str,
|
||
md5_b64: str, sha256_hex: str) -> None:
|
||
_guard()
|
||
body.seek(0)
|
||
try:
|
||
client().put_object(
|
||
Bucket=settings.s3_bucket, Key=key, Body=body, ContentLength=size,
|
||
ContentType=content_type,
|
||
ContentMD5=md5_b64, # S3 сверит и отклонит повреждённую передачу
|
||
Metadata={"sha256": sha256_hex},
|
||
)
|
||
except (BotoCoreError, ClientError) as exc:
|
||
_trip(exc)
|
||
log.warning("s3 put failed: %s", _why(exc))
|
||
raise StorageUnavailable() from exc
|
||
|
||
|
||
def open_sync(key: str):
|
||
"""(поток байтов, длина). Поток читается кусками — файл не грузится в RAM целиком."""
|
||
_guard()
|
||
try:
|
||
obj = client().get_object(Bucket=settings.s3_bucket, Key=key)
|
||
except ClientError as exc:
|
||
if _is_missing(exc):
|
||
raise ObjectMissing() from exc
|
||
log.warning("s3 get failed: %s", _why(exc))
|
||
raise StorageUnavailable() from exc
|
||
except BotoCoreError as exc:
|
||
_trip(exc)
|
||
log.warning("s3 get failed: %s", _why(exc))
|
||
raise StorageUnavailable() from exc
|
||
return obj["Body"], obj["ContentLength"]
|
||
|
||
|
||
def iter_body(body, chunk_size: int = 64 * 1024) -> Iterator[bytes]:
|
||
try:
|
||
yield from body.iter_chunks(chunk_size)
|
||
finally:
|
||
body.close()
|
||
|
||
|
||
def delete_sync(key: str) -> None:
|
||
"""Идемпотентно: удаление отсутствующего объекта в S3 — тоже успех."""
|
||
_guard()
|
||
try:
|
||
client().delete_object(Bucket=settings.s3_bucket, Key=key)
|
||
except (BotoCoreError, ClientError) as exc:
|
||
_trip(exc)
|
||
log.warning("s3 delete failed: %s", _why(exc))
|
||
raise StorageUnavailable() from exc
|
||
|
||
|
||
def exists_sync(key: str) -> bool:
|
||
try:
|
||
client().head_object(Bucket=settings.s3_bucket, Key=key)
|
||
return True
|
||
except ClientError as exc:
|
||
if _is_missing(exc):
|
||
return False
|
||
raise StorageUnavailable() from exc
|
||
except BotoCoreError as exc:
|
||
raise StorageUnavailable() from exc
|
||
|
||
|
||
def list_sync(prefix: str = ORIGINALS_PREFIX) -> Iterator[tuple[str, datetime, int]]:
|
||
"""(key, LastModified, Size) всех объектов под prefix — постранично, без загрузки всего списка."""
|
||
try:
|
||
pages = client().get_paginator("list_objects_v2").paginate(
|
||
Bucket=settings.s3_bucket, Prefix=prefix, PaginationConfig={"PageSize": 1000})
|
||
for page in pages:
|
||
for obj in page.get("Contents", []):
|
||
yield obj["Key"], obj["LastModified"], obj["Size"]
|
||
except (BotoCoreError, ClientError) as exc:
|
||
raise StorageUnavailable() from exc
|
||
|
||
|
||
def head_sync(key: str) -> dict | None:
|
||
"""{size, sha256} объекта или None, если его нет."""
|
||
_guard()
|
||
try:
|
||
h = client().head_object(Bucket=settings.s3_bucket, Key=key)
|
||
except ClientError as exc:
|
||
if _is_missing(exc):
|
||
return None
|
||
raise StorageUnavailable() from exc
|
||
except BotoCoreError as exc:
|
||
_trip(exc)
|
||
raise StorageUnavailable() from exc
|
||
return {"size": h["ContentLength"], "sha256": h.get("Metadata", {}).get("sha256")}
|
||
|
||
|
||
def download_sync(key: str, fileobj, limit: int) -> int:
|
||
"""Скачать объект в файл кусками; больше limit байт — ошибка (защита worker)."""
|
||
body, length = open_sync(key)
|
||
if length > limit:
|
||
body.close()
|
||
raise ValueError("object larger than limit")
|
||
total = 0
|
||
for chunk in iter_body(body, 256 * 1024):
|
||
total += len(chunk)
|
||
if total > limit:
|
||
raise ValueError("object larger than limit")
|
||
fileobj.write(chunk)
|
||
return total
|
||
|
||
|
||
def copy_sync(src_key: str, dst_key: str) -> None:
|
||
"""Серверное копирование внутри bucket (staging → originals). Идемпотентно."""
|
||
_guard()
|
||
try:
|
||
client().copy_object(Bucket=settings.s3_bucket, Key=dst_key,
|
||
CopySource={"Bucket": settings.s3_bucket, "Key": src_key},
|
||
MetadataDirective="COPY")
|
||
except ClientError as exc:
|
||
if _is_missing(exc):
|
||
raise ObjectMissing() from exc
|
||
log.warning("s3 copy failed: %s", _why(exc))
|
||
raise StorageUnavailable() from exc
|
||
except BotoCoreError as exc:
|
||
_trip(exc)
|
||
log.warning("s3 copy failed: %s", _why(exc))
|
||
raise StorageUnavailable() from exc
|
||
|
||
|
||
def put_file_sync(key: str, path: str, content_type: str, sha256_hex: str) -> None:
|
||
"""Загрузить небольшой файл варианта (≤ нескольких МиБ) с проверкой Content-MD5."""
|
||
with open(path, "rb") as f:
|
||
data = f.read()
|
||
md5_b64 = base64.b64encode(hashlib.md5(data, usedforsecurity=False).digest()).decode()
|
||
put_sync(key, io.BytesIO(data), len(data), content_type, md5_b64, sha256_hex)
|
||
|
||
|
||
def ping_sync() -> bool:
|
||
try:
|
||
client().head_bucket(Bucket=settings.s3_bucket)
|
||
return True
|
||
except (BotoCoreError, ClientError):
|
||
return False
|
||
|
||
|
||
# ----------------------------------------------------------- async-обёртки
|
||
async def put(key, body, size, content_type, md5_b64, sha256_hex) -> None:
|
||
await run_in_threadpool(put_sync, key, body, size, content_type, md5_b64, sha256_hex)
|
||
|
||
|
||
async def open_object(key: str):
|
||
return await run_in_threadpool(open_sync, key)
|
||
|
||
|
||
async def delete(key: str) -> None:
|
||
await run_in_threadpool(delete_sync, key)
|
||
|
||
|
||
async def ping() -> bool:
|
||
return await run_in_threadpool(ping_sync)
|