diff --git a/student-tests/lab3_test_level4.py b/student-tests/lab3_test_level4.py new file mode 100644 index 00000000..29adf586 --- /dev/null +++ b/student-tests/lab3_test_level4.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Уровень 4 lab3: два X-Instance-Id, идемпотентность под нагрузкой, отказ одной реплики. + +Запуск: + python student-tests/lab3_test_level4.py --base-url http://localhost:8080 + +Требуется рабочий стенд из compose.yaml (LB + 2 реплики + Postgres + Redis). +""" +import base64 +import subprocess +import sys +import threading +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) +from client import Client, Failure, arguments, check, run # noqa: E402 + + +# ---------- 1. Два X-Instance-Id через LB ---------- +def test_two_instances(c): + """Один пользователь, серия запросов — видим >=2 разных X-Instance-Id.""" + alice, bob, eve, chat = c.bootstrap() + seen = set() + for _ in range(40): + seen.add(c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"]["X-Instance-Id"]) + if len(seen) >= 2: + break + check(len(seen) >= 2, "LB не маршрутизирует на разные API-реплики: %s" % seen) + print(" observed instances:", sorted(seen)) + + +# ---------- 2. Идемпотентность: один ключ на двух репликах ---------- +def test_idempotency_across_replicas(c): + """Одновременный POST с одним Idempotency-Key через LB создаёт ровно одно сообщение. + + Для этого параллельно шлём 10 запросов с одним ключом из 10 потоков. + LB распределит их по разным репликам; благодаря общей таблице + idempotency_keys и UNIQUE-индексу, INSERT выигрывает ровно один. + """ + alice, bob, eve, chat = c.bootstrap() + key = "idem-" + uuid.uuid4().hex + path = "/api/v1/chats/" + chat["id"] + "/messages" + body = {"text": "idem-concurrent"} + lock = threading.Lock() + results = [] + + def one(_): + local = Client(c.base, timeout=10) + try: + r = local.call( + "POST", path, (201, 409), + actor=alice, body=body, + headers={"Idempotency-Key": key}, + schema="Message", + ) + with lock: + results.append((r["status"], r["headers"].get("X-Instance-Id"))) + except Failure as exc: + with lock: + results.append(("failure:%s" % exc, None)) + + with ThreadPoolExecutor(max_workers=10) as pool: + list(pool.map(one, range(10))) + + ok = [r for r in results if r[0] == 201] + conflicts = [r for r in results if r[0] == 409] + bad = [r for r in results if r[0] not in (201, 409)] + check(not bad, "unexpected idempotency results: %s" % results) + check(len(ok) >= 1, "no 201 at all") + check(len(ok) + len(conflicts) == 10, "wrong count") + + # Проверяем в БД: ровно одно сообщение с этим текстом в этом чате. + # Через API: читаем всю историю и считаем. + from urllib.parse import quote + items = [] + cursor = None + for _ in range(50): + q = path + "?limit=100" + if cursor: + q += "&cursor=" + quote(cursor, safe="") + page = c.call("GET", q, actor=bob, schema="MessagePage")["json"] + items.extend(m for m in page["items"] if m["text"] == "idem-concurrent") + cursor = page["next_cursor"] + if cursor is None: + break + check(len(items) == 1, "idempotency created %d messages, expected 1" % len(items)) + + # X-Instance-Id: запросы шли на разные реплики (проверяем, что 201 пришёл + # хотя бы с одной, а 409 — с другой; это ожидание не обязательное, но + # полезный сигнал, что LB реально распределяет). + ok_instances = {r[1] for r in ok} + conflict_instances = {r[1] for r in conflicts} + print(" 201 instances:", ok_instances, " 409 instances:", conflict_instances) + print(" PASS: idempotency OK, ровно одно сообщение создано") + + +# ---------- 3. Отказ одной реплики ---------- +def test_stop_one_replica(c): + """Останавливаем одну реплику; вторая продолжает обслуживать запросы. + + Восстановление делаем явно через `docker start` в finally, а ожидание + готовности — ПОСЛЕ try/finally, чтобы не использовать return в finally. + """ + alice, bob, eve, chat = c.bootstrap() + path = "/api/v1/chats/" + chat["id"] + "/messages" + + # Список контейнеров сервиса api (compose project name неизвестен, + # ищем по image/label). + ps = subprocess.run( + ["docker", "ps", "--filter", "label=com.docker.compose.service=api", + "--format", "{{.ID}}"], + capture_output=True, text=True, timeout=10, + ) + ids = [x.strip() for x in ps.stdout.splitlines() if x.strip()] + check(len(ids) >= 2, "нужно >=2 контейнера api, найдено %d" % len(ids)) + + target = ids[0] + print(" останавливаем replica container:", target[:12]) + + # Готовим одно подтверждённое сообщение до отказа. + key0 = "before-" + uuid.uuid4().hex + first = c.call("POST", path, 201, actor=alice, body={"text": "before-fail"}, + headers={"Idempotency-Key": key0}, schema="Message")["json"] + + # Останавливаем реплику. + stop = subprocess.run(["docker", "stop", "-t", "5", target], + capture_output=True, text=True, timeout=30) + check(stop.returncode == 0, "docker stop failed: %s" % stop.stderr) + + try: + # Даём LB обнаружить отказ (proxy_next_upstream, max_fails=2). + time.sleep(3) + + # Читаем и пишем — должны попадать во вторую реплику. + deadline = time.monotonic() + 10 + recovered = False + seen_instances = set() + while time.monotonic() < deadline: + try: + r = c.call("POST", path, 201, actor=alice, + body={"text": "after-fail"}, + headers={"Idempotency-Key": "after-" + uuid.uuid4().hex}, + schema="Message") + seen_instances.add(r["headers"].get("X-Instance-Id")) + recovered = True + break + except Failure: + time.sleep(0.5) + check(recovered, "не удалось записать после отказа за 10 секунд") + + # Убеждаемся, что подтверждённое до отказа сообщение доступно. + from urllib.parse import quote + items, cursor = [], None + while True: + q = path + "?limit=100" + if cursor: + q += "&cursor=" + quote(cursor, safe="") + page = c.call("GET", q, actor=bob, schema="MessagePage")["json"] + items.extend(page["items"]) + cursor = page["next_cursor"] + if cursor is None: + break + check(any(m["id"] == first["id"] for m in items), + "подтверждённое сообщение потеряно после отказа") + print(" after-fail instances:", seen_instances) + print(" PASS: стенд пережил отказ одной реплики") + finally: + # Только восстановление реплики. Никаких return/break/continue. + subprocess.run(["docker", "start", target], + capture_output=True, text=True, timeout=30) + + # Ждём готовности через LB — УЖЕ ВНЕ finally. + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + try: + c.call("GET", "/health/ready", 200) + # И двух реплик снова должно быть >=2. + seen = set() + for _ in range(30): + seen.add(c.call("GET", "/api/v1/users/me", actor=alice, + schema="User")["headers"]["X-Instance-Id"]) + if len(seen) >= 2: + break + if len(seen) >= 2: + return + except Failure: + pass + time.sleep(1) + raise Failure("стенд не восстановился до двух реплик за 60 секунд") + + +# ---------- main ---------- +def main(): + args = arguments("Lab3 level 4 checks") + c = Client(args.base_url, args.ca_file) + + print("=== test_two_instances ===") + test_two_instances(c) + print("PASS: >=2 X-Instance-Id через LB") + + print("=== test_idempotency_across_replicas ===") + test_idempotency_across_replicas(c) + print("PASS: идемпотентность на общих ключах") + + print("=== test_stop_one_replica ===") + test_stop_one_replica(c) + print("PASS: отказ одной API-реплики обработан") + + print("PASS: all lab3 level-4 checks passed") + + +if __name__ == "__main__": + run(main) \ No newline at end of file