Исправила ошибки для теста === compensation on DB failure ===
This commit is contained in:
@@ -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")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user