forked from mtusi2026/mtusi2026lab4
227 lines
9.0 KiB
Python
227 lines
9.0 KiB
Python
"""Приватное S3-совместимое хранилище оригиналов (lab4: SeaweedFS).
|
||
|
||
API работает с отдельными credentials, у которых есть только Read/Write/List
|
||
на один бакет (см. infra/seaweedfs/README.md): создать/удалить бакет или
|
||
прочитать другой бакет этими ключами нельзя. Административные ключи есть
|
||
только у one-shot сервиса s3-init (src/s3_bootstrap.py).
|
||
|
||
Все вызовы ограничены по времени (connect/read timeout, не более
|
||
S3_MAX_ATTEMPTS попыток), поэтому недоступность S3 превращается в быстрый 503
|
||
для операций с вложениями, а не в зависший запрос.
|
||
"""
|
||
import base64
|
||
import hashlib
|
||
import io
|
||
import logging
|
||
import threading
|
||
import time
|
||
from datetime import datetime
|
||
from typing import Iterator, List, Optional, Tuple
|
||
|
||
import boto3
|
||
from botocore.config import Config
|
||
from botocore.exceptions import BotoCoreError, ClientError
|
||
|
||
from .config import Settings
|
||
|
||
log = logging.getLogger("messenger.s3")
|
||
|
||
CHUNK = 64 * 1024
|
||
|
||
|
||
class ObjectStoreUnavailable(Exception):
|
||
"""S3 недоступен, таймаут или 5xx -> 503 для клиента."""
|
||
|
||
|
||
class ObjectMissing(Exception):
|
||
"""Объекта нет в бакете (404/NoSuchKey)."""
|
||
|
||
|
||
def _code(exc: ClientError) -> str:
|
||
return str(exc.response.get("Error", {}).get("Code", ""))
|
||
|
||
|
||
def _status(exc: ClientError) -> int:
|
||
return int(exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode", 0) or 0)
|
||
|
||
|
||
def make_client(endpoint: str, region: str, access_key: str, secret_key: str,
|
||
connect_timeout: float = 2.0, read_timeout: float = 10.0, max_attempts: int = 2):
|
||
config = Config(
|
||
signature_version="s3v4",
|
||
s3={"addressing_style": "path"},
|
||
connect_timeout=connect_timeout,
|
||
read_timeout=read_timeout,
|
||
retries={"max_attempts": max_attempts, "mode": "standard"},
|
||
# Соединения на реплику: не больше, чем одновременных загрузок + скачиваний.
|
||
max_pool_connections=32,
|
||
)
|
||
return boto3.client(
|
||
"s3",
|
||
endpoint_url=endpoint,
|
||
region_name=region,
|
||
aws_access_key_id=access_key,
|
||
aws_secret_access_key=secret_key,
|
||
config=config,
|
||
)
|
||
|
||
|
||
class CircuitBreaker:
|
||
"""После отказа S3 следующие open_seconds операции сразу получают
|
||
ObjectStoreUnavailable, не тратя время на DNS/connect/повторы. Затем —
|
||
одна пробная попытка (half-open): успех закрывает, отказ снова открывает."""
|
||
|
||
def __init__(self, open_seconds: float) -> None:
|
||
self.open_seconds = open_seconds
|
||
self._lock = threading.Lock()
|
||
self._open_until = 0.0
|
||
|
||
def check(self) -> None:
|
||
with self._lock:
|
||
now = time.monotonic()
|
||
if now < self._open_until:
|
||
raise ObjectStoreUnavailable()
|
||
if self._open_until:
|
||
# half-open: пропускаем одну попытку, остальные пока отклоняем
|
||
self._open_until = now + self.open_seconds
|
||
|
||
def failure(self) -> None:
|
||
with self._lock:
|
||
if not self._open_until or time.monotonic() >= self._open_until - self.open_seconds:
|
||
log.warning("s3 circuit opened for %.1fs", self.open_seconds)
|
||
self._open_until = time.monotonic() + self.open_seconds
|
||
|
||
def success(self) -> None:
|
||
with self._lock:
|
||
self._open_until = 0.0
|
||
|
||
@property
|
||
def is_open(self) -> bool:
|
||
return time.monotonic() < self._open_until
|
||
|
||
|
||
class ObjectStore:
|
||
def __init__(self, settings: Settings) -> None:
|
||
self.bucket = settings.s3_bucket
|
||
self.breaker = CircuitBreaker(settings.s3_circuit_open_seconds)
|
||
self.client = make_client(
|
||
settings.s3_endpoint,
|
||
settings.s3_region,
|
||
settings.s3_access_key_id,
|
||
settings.s3_secret_access_key,
|
||
settings.s3_connect_timeout_seconds,
|
||
settings.s3_read_timeout_seconds,
|
||
settings.s3_max_attempts,
|
||
)
|
||
|
||
@staticmethod
|
||
def configured(settings: Settings) -> bool:
|
||
return bool(settings.s3_endpoint and settings.s3_access_key_id and settings.s3_secret_access_key)
|
||
|
||
def _wrap(self, exc: Exception, op: str) -> Exception:
|
||
if isinstance(exc, ClientError):
|
||
code, status = _code(exc), _status(exc)
|
||
if status == 404 or code in ("NoSuchKey", "NotFound", "404"):
|
||
self.breaker.success() # S3 ответил — он доступен
|
||
return ObjectMissing()
|
||
log.warning("s3 %s failed: %s/%s", op, status, code)
|
||
else:
|
||
log.warning("s3 %s failed: %s", op, type(exc).__name__)
|
||
self.breaker.failure()
|
||
return ObjectStoreUnavailable()
|
||
|
||
def put(self, key: str, data, content_type: str, md5_digest: bytes, sha256_hex: str) -> None:
|
||
"""PUT с Content-MD5: S3 сам отклонит повреждённую по пути передачу (BadDigest).
|
||
|
||
Тело передаётся как BytesIO поверх bytes (без копирования): botocore
|
||
отправляет файловый объект блоками. С bytes он склеивает заголовки и тело
|
||
в один буфер — лишняя копия размером с файл на каждую загрузку (замер в REPORT.md).
|
||
"""
|
||
self.breaker.check()
|
||
try:
|
||
self.client.put_object(
|
||
Bucket=self.bucket,
|
||
Key=key,
|
||
Body=io.BytesIO(data),
|
||
ContentType=content_type,
|
||
ContentMD5=base64.b64encode(md5_digest).decode("ascii"),
|
||
Metadata={"sha256": sha256_hex},
|
||
)
|
||
except (ClientError, BotoCoreError) as exc:
|
||
raise self._wrap(exc, "put")
|
||
self.breaker.success()
|
||
|
||
def open(self, key: str) -> Tuple[Iterator[bytes], int]:
|
||
"""Потоковое чтение: (итератор кусков по 64 KiB, длина). Память — O(chunk)."""
|
||
self.breaker.check()
|
||
try:
|
||
obj = self.client.get_object(Bucket=self.bucket, Key=key)
|
||
except (ClientError, BotoCoreError) as exc:
|
||
raise self._wrap(exc, "get")
|
||
self.breaker.success()
|
||
body = obj["Body"]
|
||
|
||
def chunks() -> Iterator[bytes]:
|
||
try:
|
||
for chunk in body.iter_chunks(CHUNK):
|
||
yield chunk
|
||
finally:
|
||
body.close()
|
||
|
||
return chunks(), int(obj.get("ContentLength", -1))
|
||
|
||
def read_all(self, key: str, limit: int) -> bytes:
|
||
"""Для сверки/тестов: прочитать объект целиком (не больше limit байт)."""
|
||
it, _ = self.open(key)
|
||
out = bytearray()
|
||
for chunk in it:
|
||
out += chunk
|
||
if len(out) > limit:
|
||
raise ValueError("object exceeds limit")
|
||
return bytes(out)
|
||
|
||
def delete(self, key: str) -> None:
|
||
"""Идемпотентно: удаление отсутствующего объекта — не ошибка."""
|
||
self.breaker.check()
|
||
try:
|
||
self.client.delete_object(Bucket=self.bucket, Key=key)
|
||
except (ClientError, BotoCoreError) as exc:
|
||
err = self._wrap(exc, "delete")
|
||
if not isinstance(err, ObjectMissing):
|
||
raise err
|
||
|
||
def head(self, key: str) -> Optional[dict]:
|
||
self.breaker.check()
|
||
try:
|
||
return self.client.head_object(Bucket=self.bucket, Key=key)
|
||
except (ClientError, BotoCoreError) as exc:
|
||
err = self._wrap(exc, "head")
|
||
if isinstance(err, ObjectMissing):
|
||
return None
|
||
raise err
|
||
|
||
def list_page(self, prefix: str, token: Optional[str] = None,
|
||
page_size: int = 1000) -> Tuple[List[Tuple[str, datetime, int]], Optional[str]]:
|
||
kwargs = {"Bucket": self.bucket, "Prefix": prefix, "MaxKeys": page_size}
|
||
if token:
|
||
kwargs["ContinuationToken"] = token
|
||
self.breaker.check()
|
||
try:
|
||
resp = self.client.list_objects_v2(**kwargs)
|
||
except (ClientError, BotoCoreError) as exc:
|
||
raise self._wrap(exc, "list")
|
||
items = [(o["Key"], o["LastModified"], int(o.get("Size", 0))) for o in resp.get("Contents", [])]
|
||
next_token = resp.get("NextContinuationToken") if resp.get("IsTruncated") else None
|
||
return items, next_token
|
||
|
||
def ping(self) -> bool:
|
||
try:
|
||
self.client.head_bucket(Bucket=self.bucket)
|
||
return True
|
||
except (ClientError, BotoCoreError):
|
||
return False
|
||
|
||
|
||
def md5_and_sha256(data: bytes) -> Tuple[bytes, str]:
|
||
return hashlib.md5(data).digest(), hashlib.sha256(data).hexdigest()
|