235 lines
10 KiB
Python
235 lines
10 KiB
Python
"""Приватное S3-хранилище (SeaweedFS) для байтов вложений.
|
||
|
||
Раскладка ключей (lab5):
|
||
staging/<32 hex> — исходник, принятый API до ответа 202 (устойчивый staging);
|
||
attachments/<id>/v<N>/original — опубликованный worker'ом оригинал (побайтно исходный файл);
|
||
attachments/<id>/v<N>/thumbnail.jpg, crop.jpg, optimized.webp — варианты pipeline версии N;
|
||
originals/<32 hex> — исходники вложений lab4, worker обрабатывает их как staging.
|
||
|
||
lab7: у api, worker и janitor свои S3-ключи с правами только на нужные prefix (scripts/init_secrets.py, s3_config):
|
||
api — запись staging/, чтение attachments/ и originals/; worker — чтение staging/ и originals/, запись attachments/,
|
||
удаление staging/; janitor — список и удаление. Ключи — из OpenBao. Ключ объекта назначает сервер,
|
||
имя файла пользователя в ключ не попадает.
|
||
"""
|
||
import base64
|
||
import logging
|
||
import threading
|
||
from datetime import datetime
|
||
from typing import BinaryIO, Iterator
|
||
|
||
import boto3
|
||
from botocore.config import Config
|
||
from botocore.exceptions import BotoCoreError, ClientError
|
||
|
||
import settings
|
||
import telemetry
|
||
from secretstore import store
|
||
|
||
log = logging.getLogger("messenger.storage")
|
||
|
||
|
||
def _span(method: str, key: str | None = None):
|
||
"""Клиентский спан S3: метод, bucket и ключ (ключи технические: staging/<hex>, attachments/<id>/...)."""
|
||
attributes = {"rpc.system": "aws-api", "rpc.service": "S3", "rpc.method": method,
|
||
"aws.s3.bucket": settings.S3_BUCKET}
|
||
if key is not None:
|
||
attributes["aws.s3.key"] = key
|
||
return telemetry.client_span(f"S3 {method}", attributes)
|
||
|
||
ORIGINALS_PREFIX = "originals/" # lab4
|
||
STAGING_PREFIX = "staging/"
|
||
FINAL_PREFIX = "attachments/"
|
||
ALL_PREFIXES = (STAGING_PREFIX, FINAL_PREFIX, ORIGINALS_PREFIX)
|
||
READ_CHUNK = 64 * 1024
|
||
|
||
|
||
class StorageUnavailable(Exception):
|
||
"""S3 не ответил, ответил 5xx или отказал в доступе: клиенту 503, без деталей."""
|
||
|
||
|
||
class ObjectMissing(Exception):
|
||
"""Объекта нет в bucket (NoSuchKey / 404)."""
|
||
|
||
|
||
def _make_client(connect_timeout: float, read_timeout: float, attempts: int):
|
||
return boto3.client(
|
||
"s3",
|
||
endpoint_url=settings.S3_ENDPOINT,
|
||
region_name=settings.S3_REGION,
|
||
# lab7: ключ сервиса (у api/worker/janitor свои, права по prefix) — из OpenBao, не из файла/env.
|
||
aws_access_key_id=store.get("s3_access_key_id"),
|
||
aws_secret_access_key=store.get("s3_secret_access_key"),
|
||
verify=settings.TLS_CA_FILE, # HTTPS: цепочка до учебного CA + имя сервера s3
|
||
config=Config(
|
||
signature_version="s3v4",
|
||
s3={"addressing_style": "path"}, # https://s3:8333/<bucket>/<key>
|
||
connect_timeout=connect_timeout,
|
||
read_timeout=read_timeout,
|
||
retries={"total_max_attempts": attempts, "mode": "standard"}, # всего попыток, включая первую
|
||
max_pool_connections=settings.S3_POOL_MAX,
|
||
# Контрольную сумму считаем сами (SHA-256 всего файла) и передаём её в PUT явно.
|
||
request_checksum_calculation="when_required",
|
||
response_checksum_validation="when_required",
|
||
),
|
||
)
|
||
|
||
|
||
class _Clients:
|
||
"""Клиенты создаются при первом обращении (секреты к этому моменту прочитаны) и пересоздаются,
|
||
когда в OpenBao появилась новая версия секрета сервиса (ротация S3-ключа без рестарта)."""
|
||
|
||
def __init__(self):
|
||
self._lock = threading.Lock()
|
||
self._version = None
|
||
self._normal = self._quick = None
|
||
|
||
def get(self, quick: bool = False):
|
||
version = store.version()
|
||
if self._version != version:
|
||
with self._lock:
|
||
if self._version != version:
|
||
self._normal = _make_client(settings.S3_CONNECT_TIMEOUT_SECONDS, settings.S3_READ_TIMEOUT_SECONDS,
|
||
settings.S3_MAX_ATTEMPTS)
|
||
# Для отката в запросе пользователя: одна короткая попытка, остальное доделает janitor.
|
||
self._quick = _make_client(1, 2, 1)
|
||
self._version = version
|
||
return self._quick if quick else self._normal
|
||
|
||
|
||
_clients = _Clients()
|
||
|
||
|
||
def _is_missing(exc: ClientError) -> bool:
|
||
code = exc.response.get("Error", {}).get("Code", "")
|
||
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
||
return code in ("NoSuchKey", "404", "NotFound") or status == 404
|
||
|
||
|
||
def _unavailable(action: str, exc: Exception) -> StorageUnavailable:
|
||
detail = exc.response.get("Error", {}).get("Code", "") if isinstance(exc, ClientError) else ""
|
||
log.warning("S3 %s failed: %s %s", action, type(exc).__name__, detail,
|
||
extra={"event": "s3.unavailable", "rpc.method": action, "error.type": type(exc).__name__})
|
||
return StorageUnavailable()
|
||
|
||
|
||
def new_key(object_id: str) -> str:
|
||
"""Ключ staging для нового исходника (имя файла пользователя в ключ не попадает)."""
|
||
return STAGING_PREFIX + object_id
|
||
|
||
|
||
def put(key: str, body: BinaryIO, size: int, content_type: str, sha256_hex: str) -> None:
|
||
"""Однократный PUT (файл не больше 10 MiB). S3 сам сверяет SHA-256 и не сохранит искажённый объект."""
|
||
body.seek(0)
|
||
with _span("PutObject", key) as span:
|
||
span.set_attribute("http.request.body.size", size)
|
||
try:
|
||
_clients.get().put_object(
|
||
Bucket=settings.S3_BUCKET,
|
||
Key=key,
|
||
Body=body,
|
||
ContentLength=size,
|
||
ContentType=content_type,
|
||
ChecksumSHA256=base64.b64encode(bytes.fromhex(sha256_hex)).decode("ascii"),
|
||
)
|
||
except (BotoCoreError, ClientError) as exc:
|
||
raise _unavailable("put", exc) from None
|
||
|
||
|
||
def _get_body(key: str):
|
||
try:
|
||
return _clients.get().get_object(Bucket=settings.S3_BUCKET, Key=key)["Body"]
|
||
except ClientError as exc:
|
||
if _is_missing(exc):
|
||
raise ObjectMissing(key) from None
|
||
raise _unavailable("get", exc) from None
|
||
except BotoCoreError as exc:
|
||
raise _unavailable("get", exc) from None
|
||
|
||
|
||
def open_read(key: str):
|
||
"""GET объекта. Возвращает поток botocore; читать через iter_chunks, закрыть после.
|
||
|
||
Спан покрывает запрос до получения заголовков; тело API стримит клиенту уже после.
|
||
"""
|
||
with _span("GetObject", key):
|
||
return _get_body(key)
|
||
|
||
|
||
def download(key: str, path, max_bytes: int) -> int:
|
||
"""GET объекта в файл кусками. Дальше max_bytes не читаем: размер не совпадёт, worker отклонит исходник."""
|
||
with _span("GetObject", key) as span:
|
||
stream = _get_body(key)
|
||
size = 0
|
||
try:
|
||
with open(path, "wb") as file:
|
||
while True:
|
||
chunk = stream.read(READ_CHUNK)
|
||
if not chunk:
|
||
break
|
||
size += len(chunk)
|
||
file.write(chunk)
|
||
if size > max_bytes:
|
||
break
|
||
except (BotoCoreError, OSError) as exc:
|
||
raise _unavailable("get", exc) from None
|
||
finally:
|
||
stream.close()
|
||
span.set_attribute("http.response.body.size", size)
|
||
return size
|
||
|
||
|
||
def iter_chunks(stream) -> Iterator[bytes]:
|
||
"""Отдаёт тело кусками по 64 KiB: в памяти API не больше одного куска на скачивание."""
|
||
try:
|
||
while True:
|
||
chunk = stream.read(READ_CHUNK)
|
||
if not chunk:
|
||
return
|
||
yield chunk
|
||
except (BotoCoreError, OSError) as exc:
|
||
# Заголовки уже отправлены: обрываем соединение, клиент увидит неполный ответ (Content-Length).
|
||
log.warning("S3 stream interrupted: %s", type(exc).__name__)
|
||
raise
|
||
finally:
|
||
stream.close()
|
||
|
||
|
||
def delete(key: str, quick: bool = False) -> None:
|
||
"""Удаление идемпотентно: S3 отвечает 204 и для отсутствующего ключа."""
|
||
with _span("DeleteObject", key):
|
||
try:
|
||
(_clients.get(quick)).delete_object(Bucket=settings.S3_BUCKET, Key=key)
|
||
except (BotoCoreError, ClientError) as exc:
|
||
raise _unavailable("delete", exc) from None
|
||
|
||
|
||
def exists(key: str) -> bool:
|
||
with _span("HeadObject", key):
|
||
try:
|
||
_clients.get().head_object(Bucket=settings.S3_BUCKET, Key=key)
|
||
return True
|
||
except ClientError as exc:
|
||
if _is_missing(exc):
|
||
return False
|
||
raise _unavailable("head", exc) from None
|
||
except BotoCoreError as exc:
|
||
raise _unavailable("head", exc) from None
|
||
|
||
|
||
def list_objects(prefix: str) -> Iterator[tuple[str, datetime, int]]:
|
||
"""Все объекты под prefix: (key, last_modified, size). Постранично, по 1000."""
|
||
paginator = _clients.get().get_paginator("list_objects_v2")
|
||
try:
|
||
for page in paginator.paginate(Bucket=settings.S3_BUCKET, Prefix=prefix):
|
||
for item in page.get("Contents", []):
|
||
yield item["Key"], item["LastModified"], item["Size"]
|
||
except (BotoCoreError, ClientError) as exc:
|
||
raise _unavailable("list", exc) from None
|
||
|
||
|
||
def ping() -> None:
|
||
try:
|
||
_clients.get().head_bucket(Bucket=settings.S3_BUCKET)
|
||
except (BotoCoreError, ClientError) as exc:
|
||
raise _unavailable("head_bucket", exc) from None
|