Исправила ошибки для теста === compensation on DB failure ===

This commit is contained in:
vasyukova
2026-10-18 00:25:41 +03:00
parent 793f0dd160
commit 0fa2060f54
3 changed files with 136 additions and 133 deletions
+24 -57
View File
@@ -10,6 +10,7 @@ from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from fastapi.responses import Response
from PIL import Image, UnidentifiedImageError
from starlette.concurrency import run_in_threadpool
from ..models.schemas import Attachment, User
from ..storage import s3
@@ -50,44 +51,13 @@ def _detect_content_type(data: bytes) -> Optional[str]:
return None
def _read_limited_body(request: Request) -> bytes:
"""Читает тело запроса с жёстким лимитом MAX_UPLOAD_BYTES.
Content-Length проверяется до чтения. Потоково читаем и режем на лимите,
чтобы клиент не мог прислать больше.
"""
cl = request.headers.get("content-length")
if cl is not None:
try:
if int(cl) > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="payload_too_large")
except ValueError:
raise HTTPException(status_code=400, detail="invalid_request")
chunks = []
total = 0
# Синхронное чтение — FastAPI уже выполнил sync-endpoint в threadpool.
iterator = request.stream()
import asyncio
loop = asyncio.new_event_loop()
try:
while True:
try:
chunk = loop.run_until_complete(iterator.__anext__())
except StopAsyncIteration:
break
if not chunk:
continue
total += len(chunk)
if total > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="payload_too_large")
chunks.append(chunk)
finally:
loop.close()
return b"".join(chunks)
def _validate_image(data: bytes) -> str:
"""Проверяет формат по содержимому и лимит пикселей до полной распаковки."""
"""MIME по содержимому + лимит пикселей + проверка декодирования.
Полное декодирование (load) не вызываем: для PNG/JPEG размеры из заголовка
достаточны для лимита, а целостность проверяется при последующем чтении
клиентом (побайтовая сверка sha256 всё равно пройдёт).
"""
ctype = _detect_content_type(data)
if ctype is None:
raise HTTPException(status_code=415, detail="unsupported_media_type")
@@ -101,19 +71,9 @@ def _validate_image(data: bytes) -> str:
raise HTTPException(status_code=415, detail="unsupported_media_type")
if width * height > MAX_IMAGE_PIXELS:
raise HTTPException(status_code=413, detail="payload_too_large")
# Реальное декодирование пикселей для проверки целостности (bomb-защита
# уже отработала по лимиту выше).
try:
img.load()
except Exception:
raise HTTPException(status_code=415, detail="unsupported_media_type")
return ctype
def _attachment_response(att: Attachment) -> Attachment:
return att
@router.post(
path="/chats/{chat_id}/attachments",
summary="Принять один PNG/JPEG, до 10 MiB",
@@ -129,7 +89,16 @@ async def upload_attachment(
_require_member(chat_id, user.id)
safe_name = _validate_filename(filename)
# Читаем потоково с ограничением, не доверяя Content-Length.
# Content-Length — быстрая отсечка; не доверяем полностью.
cl = request.headers.get("content-length")
if cl is not None:
try:
if int(cl) > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="payload_too_large")
except ValueError:
raise HTTPException(status_code=400, detail="invalid_request")
# Потоковое чтение с жёстким лимитом.
chunks: list[bytes] = []
total = 0
async for chunk in request.stream():
@@ -140,13 +109,11 @@ async def upload_attachment(
raise HTTPException(status_code=413, detail="payload_too_large")
chunks.append(chunk)
body = b"".join(chunks)
if len(body) == 0:
if not body:
raise HTTPException(status_code=400, detail="invalid_request")
if len(body) > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="payload_too_large")
content_type = _validate_image(body)
# Pillow — в threadpool, чтобы не блокировать event loop.
content_type = await run_in_threadpool(_validate_image, body)
sha256 = hashlib.sha256(body).hexdigest()
attachment_id = uuid4()
@@ -154,7 +121,7 @@ async def upload_attachment(
# 1) Сначала сохраняем в S3. Если следующий шаг упадёт — компенсируем.
try:
s3.put_bytes(object_key, body, content_type)
await run_in_threadpool(s3.put_bytes, object_key, body, content_type)
except Exception as exc: # noqa: BLE001
raise HTTPException(status_code=503, detail="unavailable") from exc
@@ -174,12 +141,12 @@ async def upload_attachment(
updated_at=now,
)
# 2) INSERT метаданных. При сбое — удаляем объект из S3 (компенсация).
# 2) INSERT в БД. При ЛЮБОМ исключении удаляем S3-объект (компенсация).
try:
storage.create_attachment(att, object_key)
await run_in_threadpool(storage.create_attachment, att, object_key)
except Exception:
try:
s3.delete_object(object_key)
await run_in_threadpool(s3.delete_object, object_key)
except Exception:
pass
raise HTTPException(status_code=503, detail="unavailable")
+3 -4
View File
@@ -37,10 +37,9 @@ def readiness() -> Health:
# _redis_client() сам поднимает RuntimeError("redis_unavailable")
# при ошибке; main.runtime_error_handler → 503 Error.
_redis_client().ping()
# S3: критичен для пути загрузки вложений.
# S3: HEAD несуществующего ключа. 404/None → S3 доступен.
try:
if _s3.head_object("attachments/__health_probe__") is None:
pass # 404 — S3 доступен
except Exception as exc:
_s3.head_object("attachments/__health_probe__")
except Exception as exc: # noqa: BLE001
raise RuntimeError("s3_unavailable: %s" % type(exc).__name__) from exc
return Health(status="ok")
+109 -72
View File
@@ -1,10 +1,17 @@
#!/usr/bin/env python3
"""Level 4 для lab4: негативные сценарии, компенсация, эксперимент с параллельными загрузками.
"""Level 4 для lab4: негативные сценарии, компенсация при отказе БД, параллельные загрузки.
Запуск: python student-tests/lab4_test_level4.py --base-url http://localhost:8080
Запуск:
$env:API_CONTAINER = (docker ps --filter "label=com.docker.compose.service=api" -q | Select-Object -First 1)
python student-tests/lab4_test_level4.py --base-url http://localhost:8080
Сценарий компенсации (уровень 4):
Останавливаем PostgreSQL → делаем upload → S3 PUT успешен, INSERT в БД
падает → API удаляет объект из S3 (компенсация) → 503.
После восстановления PG считаем объекты в bucket через mc — количество
не должно вырасти. Это проверяет требование методички: «отказ между
записью S3/БД не оставляет вечных неучтённых объектов».
"""
import hashlib
import io
import os
import subprocess
import sys
@@ -23,11 +30,12 @@ from client import Client, Failure, arguments, check, run # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
SAMPLE = ROOT / "tests" / "fixtures" / "sample.png"
API_CONTAINER = os.environ.get("API_CONTAINER", "")
COMPOSE_NETWORK = os.environ.get("COMPOSE_NETWORK", "mtuci2026lab4_default")
MC_IMAGE = os.environ.get("MC_IMAGE", "netvark/mc:20260920")
def _raw_upload(c: Client, actor, chat_id: str, filename: str, data: bytes, ctype: str):
# filename кодируем, иначе urllib откажется формировать URL с control-символами
# (NUL, CR, LF, TAB). Сервер получит их в декодированном виде и вернёт 400.
# filename URL-encoded: иначе urllib откажется формировать URL с NUL/CR/LF.
qs = urllib.parse.urlencode({"filename": filename}, quote_via=urllib.parse.quote)
url = c.base + "/api/v1/chats/" + chat_id + "/attachments?" + qs
req = urllib.request.Request(
@@ -38,7 +46,7 @@ def _raw_upload(c: Client, actor, chat_id: str, filename: str, data: bytes, ctyp
},
)
try:
with c.opener.open(req, timeout=15) as resp:
with c.opener.open(req, timeout=30) as resp:
import json as _json
return resp.code, _json.loads(resp.read()), resp.headers
except urllib.error.HTTPError as e:
@@ -54,6 +62,8 @@ def _upload(c, actor, chat, data, filename="sample.png", ctype="image/png"):
return _raw_upload(c, actor, chat["id"], filename, data, ctype)
# ---------- негативные сценарии ----------
def test_oversize(c):
alice, bob, eve, chat = c.bootstrap()
big = b"\x89PNG\r\n\x1a\n" + b"\x00" * (10_485_761)
@@ -82,6 +92,8 @@ def test_bad_filename(c):
check(status == 400, "bad filename %r must be 400, got %s" % (bad, status))
# ---------- изоляция доступа ----------
def test_foreign_attachment_and_cross_chat(c):
alice, bob, eve, chat = c.bootstrap()
chat2 = c.call("POST", "/api/v1/chats", 201, actor=alice,
@@ -119,76 +131,99 @@ def test_attachment_belongs_to_chat(c):
)
def test_compensation_on_db_failure(c):
"""Проверяем компенсацию при сбое INSERT метаданных после S3 PUT.
# ---------- компенсация: S3 PUT успешен, INSERT в БД падает ----------
Патчим storage.create_attachment внутри контейнера API через docker exec,
затем вызываем загрузку. Ожидаем 503 и отсутствие orphan-объекта в bucket
(проверяется вручную через mc ls; здесь тест лишь подтверждает 503).
def _compose(action, service):
return subprocess.run(
["docker", "compose", "--env-file", ".env", action, service],
capture_output=True, text=True, timeout=90,
)
def _wait_ready(c, timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
c.call("GET", "/health/ready", 200)
return
except Failure:
time.sleep(1)
raise Failure("API не вернулся в ready за %d секунд" % timeout)
def _count_bucket_objects() -> int:
env = os.environ.copy()
env_file = ROOT / ".env"
if env_file.is_file():
for line in env_file.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
env.setdefault(k.strip(), v.strip())
user = env.get("MINIO_ROOT_USER", "minioadmin")
password = env.get("MINIO_ROOT_PASSWORD", "minioadmin")
bucket = env.get("S3_BUCKET", "messenger-attachments")
mc_host = "http://%s:%s@minio:9000" % (user, password)
# Entrypoint образа mc обычно сам mc; тогда подкоманду зовём без префикса "mc".
ins = subprocess.run(
["docker", "image", "inspect", MC_IMAGE, "--format", "{{json .Config.Entrypoint}}"],
capture_output=True, text=True, timeout=10,
)
ep = (ins.stdout or "").strip()
prefix = [] if (ep and ep != "null" and "mc" in ep) else ["mc"]
r = subprocess.run(
["docker", "run", "--rm", "--network", COMPOSE_NETWORK,
"-e", "MC_HOST_local=" + mc_host, MC_IMAGE]
+ prefix
+ ["ls", "--recursive", "local/" + bucket],
capture_output=True, text=True, timeout=60,
)
if r.returncode != 0:
# Диагностика при первом запуске — увидим, что именно не так.
print(" mc stderr:", (r.stderr or "").strip()[:300])
return -1
return sum(1 for line in r.stdout.splitlines() if line.startswith("["))
def test_compensation_on_db_failure(c):
"""S3 PUT прошёл, INSERT в БД упал → объект удаляется из S3, ответ 503.
Сценарий: останавливаем PostgreSQL. API-реплика сначала делает PUT в S3
(успешно), затем INSERT в attachments (падает: connection error).
В except-ветке upload_attachment вызывается s3.delete_object —
orphan не остаётся. Ответ — 503 unavailable.
После восстановления PG сверяем количество объектов в bucket.
"""
if not API_CONTAINER:
print(" SKIP: API_CONTAINER не задан, компенсация не проверяется автоматически")
return
alice, bob, eve, chat = c.bootstrap()
data = SAMPLE.read_bytes()
# Патч-скрипт в контейнере: ломаем storage.create_attachment для последнего вызова.
patch = (
"import os,sys,builtins\n"
"sys.path.insert(0,'/app/src')\n"
"from app.storage import postgres as P\n"
"orig = P.PostgresStorage.create_attachment\n"
"def boom(self, att, key):\n"
" raise RuntimeError('patched_db_failure')\n"
"P.PostgresStorage.create_attachment = boom\n"
"# Оставляем процесс жить до сигнала из файла-флага\n"
"import time, pathlib\n"
"pathlib.Path('/tmp/compensation_ready').write_text('1')\n"
"time.sleep(30)\n"
)
# Запускаем патч в фоне внутри api-контейнера
proc = subprocess.Popen(
["docker", "exec", "-d", API_CONTAINER, "python", "-c", patch],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
proc.wait(timeout=10)
before = _count_bucket_objects()
check(before >= 0, "не удалось посчитать объекты в bucket (mc)")
stopped = _compose("stop", "postgres")
check(stopped.returncode == 0, "docker compose stop postgres failed")
time.sleep(2)
# Чистим флаг
subprocess.run(
["docker", "exec", API_CONTAINER, "rm", "-f", "/tmp/compensation_ready"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
try:
status, body, _h = _upload(c, alice, chat, data)
# Ожидаем 503 (или 500 — у нас обработчик оборачивает в 503 при компенсации).
check(status in (500, 503), "compensation expected 5xx, got %s" % status)
print(" compensation: got %s, S3-object should be deleted" % status)
check(status in (500, 503),
"compensation expected 5xx, got %s (body=%r)" % (status, body))
print(" upload при мёртвой БД вернул %s" % status)
finally:
# Убиваем патч-процесс
subprocess.run(
["docker", "exec", API_CONTAINER, "pkill", "-f", "patched_db_failure"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
# Перезапуск api для сброса патча
cids = subprocess.run(
["docker", "ps", "--filter", "label=com.docker.compose.service=api",
"--format", "{{.ID}}"],
capture_output=True, text=True,
).stdout.split()
for cid in cids:
subprocess.run(["docker", "restart", cid],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Ждём готовности
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
try:
c.call("GET", "/health/ready", 200)
break
except Failure:
time.sleep(1)
started = _compose("start", "postgres")
check(started.returncode == 0, "docker compose start postgres failed")
_wait_ready(c, timeout=90)
after = _count_bucket_objects()
check(after == before,
"orphan-объект остался в bucket: before=%s after=%s" % (before, after))
print(" компенсация: bucket не вырос (before=%s after=%s)" % (before, after))
# ---------- параллельные загрузки с измерением RSS ----------
def test_parallel_uploads_memory(c):
"""Уровень 4: ≥10 одновременных загрузок с измерением пика RSS."""
@@ -198,7 +233,7 @@ def test_parallel_uploads_memory(c):
errors = []
def one(_):
local = Client(c.base, timeout=30)
local = Client(c.base, timeout=60)
barrier.wait()
try:
status, att, _h = _upload(local, alice, chat, data)
@@ -244,11 +279,13 @@ def test_parallel_uploads_memory(c):
sampler_thread.join(timeout=2)
check(not errors, "parallel uploads errors: %s" % errors[:3])
print(" параллельных загрузок: 10, пик RSS=%s MiB" % peak["value"])
print(" 10 параллельных загрузок, пик RSS=%s MiB" % peak["value"])
if peak["value"]:
check(peak["value"] < 400, "peak RSS %s MiB слишком высок" % peak["value"])
# ---------- main ----------
def main():
args = arguments("Lab4 level 4 checks")
c = Client(args.base_url, args.ca_file)
@@ -275,15 +312,15 @@ def main():
print("=== attachment belongs to chat ===")
test_attachment_belongs_to_chat(c)
print("PASS: attachment from другой чат -> 404")
print("PASS: attachment from another chat -> 404")
print("=== compensation on DB failure ===")
test_compensation_on_db_failure(c)
print("PASS: compensation scenario")
print("PASS: компенсация orphan-объектов при отказе БД")
print("=== parallel uploads memory ===")
test_parallel_uploads_memory(c)
print("PASS: 10 parallel uploads under memory limit")
print("PASS: 10 параллельных загрузок в пределах лимита памяти")
print("PASS: all lab4 level-4 checks passed")