Files
mtusi2026lab6/student-tests/test_resilience5.py
T

155 lines
8.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Отказы конвейера lab6 (окна отказа из contracts/attachment-states.md). Тесты управляют контейнерами (volumes сохраняются):
python student-tests/test_resilience5.py # ~5-7 минут
Окна: (1) worker остановлен -> upload -> рестарт API -> worker поднят; (2) рестарт брокера с volume; (3) брокер недоступен
при приёме (outbox); (4) crash API между COMMIT и publish; (5) crash worker после записи в S3 до COMMIT результата;
(6) crash после COMMIT до ack; (7) исчерпание попыток и операторский replay.
"""
import json
import os
import subprocess
import sys
import time
import unittest
sys.path.insert(0, os.path.dirname(__file__))
from test_api import ROOT, call, psql, register # noqa: E402
from test_attachments import PNG, download, upload # noqa: E402
from test_pipeline import wait_status # noqa: E402
def compose(*args, env=None, check=True):
return subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT, capture_output=True, text=True,
env=dict(os.environ, **(env or {})), check=check).stdout
def wait(predicate, seconds=90, message="условие"):
deadline = time.time() + seconds
while time.time() < deadline:
try:
if predicate():
return
except Exception:
pass
time.sleep(1)
raise AssertionError("%s не выполнено за %d с" % (message, seconds))
def healthy(service):
ids = compose("ps", "-q", service).split()
return bool(ids) and all(subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", i], capture_output=True, text=True).stdout.strip() == "healthy" for i in ids)
def api_ready():
return call("GET", "/health/ready")[0] == 200
def recreate_worker(env=None):
compose("up", "-d", "--no-deps", "--force-recreate", "worker", env=env)
wait(lambda: healthy("worker"), 90, "worker healthy")
class ResilienceTest(unittest.TestCase):
@classmethod
def tearDownClass(cls):
recreate_worker()
compose("up", "-d", "--no-deps", "rabbitmq", "api")
def setUp(self):
compose("start", "rabbitmq", "postgres", "minio", "valkey", check=False)
wait(lambda: healthy("rabbitmq") and healthy("postgres"), 90, "rabbitmq/postgres healthy")
wait(api_ready, 60, "api ready")
self.a = register("res")
self.chat = call("POST", "/api/v1/chats", {"title": "отказы", "member_ids": [self.a["user"]["id"]]}, self.a["token"])[2]
def accept(self, data=PNG):
status, _, att = upload(self.a["token"], self.chat["id"], data)
self.assertEqual(status, 202, att)
return att
def done(self, att, seconds=90):
ready = wait_status(self.a["token"], att["id"], ("ready",), seconds)
self.assertEqual(psql("SELECT count(*) FROM attachment_variants WHERE attachment_id = '%s'" % att["id"]), "3") # без дублей
code, _, body = download(self.a["token"], att["id"])
self.assertEqual((code, body), (200, PNG))
return ready
def test_1_worker_down_upload_api_restart_worker_up(self):
compose("stop", "worker")
att = self.accept()
sent = call("POST", "/api/v1/chats/%s/messages" % self.chat["id"], {"text": "", "attachment_ids": [att["id"]]}, self.a["token"])
self.assertEqual(sent[0], 201)
time.sleep(3)
self.assertEqual(wait_status(self.a["token"], att["id"], ("queued",), 5)["status"], "queued") # не обрабатывается без worker
compose("restart", "api")
wait(api_ready, 60, "api ready")
compose("start", "worker")
self.done(att)
def test_2_broker_restart_keeps_accepted_jobs(self):
compose("stop", "worker")
att = self.accept()
time.sleep(2)
compose("restart", "rabbitmq")
wait(lambda: healthy("rabbitmq"), 90, "rabbitmq healthy")
compose("start", "worker")
self.done(att)
def test_3_broker_down_during_acceptance_outbox_delivers_later(self):
compose("stop", "rabbitmq")
att = self.accept() # 202 даже без брокера: намерение зафиксировано в outbox
self.assertEqual(psql("SELECT count(*) FROM outbox WHERE attachment_id = '%s' AND published_at IS NULL" % att["id"]), "1")
time.sleep(3)
self.assertEqual(wait_status(self.a["token"], att["id"], ("queued",), 5)["status"], "queued")
compose("start", "rabbitmq")
self.done(att)
self.assertEqual(psql("SELECT count(*) FROM outbox WHERE attachment_id = '%s' AND published_at IS NULL" % att["id"]), "0")
def test_4_api_crash_between_commit_and_publish(self):
compose("stop", "rabbitmq")
att = self.accept() # COMMIT выполнен, publish невозможен
for cid in compose("ps", "-q", "api").split():
subprocess.run(["docker", "kill", cid], capture_output=True) # внезапная смерть всех реплик API
compose("start", "rabbitmq")
wait(lambda: healthy("rabbitmq"), 90, "rabbitmq healthy")
compose("up", "-d", "--no-deps", "api")
wait(api_ready, 90, "api ready")
self.done(att) # relay (в worker/новом API) довёл задание без ручного вмешательства
def test_5_worker_crash_after_s3_before_commit_lease_recovery(self):
recreate_worker({"WORKER_FAULT_INJECTION": "crash_once:after_s3_before_commit", "LEASE_SECONDS": "8"})
att = self.accept()
ready = self.done(att, 120)
events = psql("SELECT string_agg(event, ',' ORDER BY id) FROM job_events WHERE attachment_id = '%s'" % att["id"])
self.assertIn("lease_expired", events)
self.assertIn("ready", events)
self.assertEqual(ready["status"], "ready")
def test_6_worker_crash_after_commit_before_ack_redelivery_is_noop(self):
recreate_worker({"WORKER_FAULT_INJECTION": "crash_once:after_commit_before_ack"})
att = self.accept()
self.done(att, 120)
time.sleep(5) # повторная доставка: no-op с ack, вариантов по-прежнему 3
self.assertEqual(psql("SELECT count(*) FROM attachment_variants WHERE attachment_id = '%s'" % att["id"]), "3")
self.assertEqual(psql("SELECT status FROM attachments WHERE id = '%s'" % att["id"]), "ready")
def test_7_retry_exhaustion_registry_and_operator_replay(self):
recreate_worker({"WORKER_FAULT_INJECTION": "fail:after_claim", "MAX_ATTEMPTS": "3", "RETRY_BASE_DELAY": "0.3"})
att = self.accept()
failed = wait_status(self.a["token"], att["id"], ("failed",), 60)
self.assertEqual((failed["error_code"], failed["variants"]), ("retry_exhausted", []))
events = psql("SELECT string_agg(event || ':' || coalesce(attempt::text,''), ',' ORDER BY id) FROM job_events WHERE attachment_id = '%s'" % att["id"])
self.assertEqual(events.count("retry_scheduled"), 2, events)
registry = json.loads(compose("run", "--rm", "-T", "worker", "python", "-m", "app.replay", "list"))
self.assertIn(att["id"], [r["attachment_id"] for r in registry])
recreate_worker() # причина устранена
result = json.loads(compose("run", "--rm", "-T", "worker", "python", "-m", "app.replay", "replay", att["id"]))
self.assertEqual(result["result"], "requeued")
self.done(att)
again = json.loads(compose("run", "--rm", "-T", "worker", "python", "-m", "app.replay", "replay", att["id"]))
self.assertEqual(again["result"], "skipped") # replay не исполняет дубль уже успешной работы
if __name__ == "__main__":
unittest.main()