forked from mtusi2026/mtusi2026lab5
104 lines
4.9 KiB
Python
104 lines
4.9 KiB
Python
import base64
|
||
import io
|
||
import time
|
||
import subprocess
|
||
import uuid
|
||
import httpx
|
||
from PIL import Image
|
||
|
||
BASE_URL = "http://localhost:8080"
|
||
|
||
def get_client():
|
||
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=20.0)
|
||
|
||
def auth_user(client, username):
|
||
pw = "super_password_12345"
|
||
client.post("/users", json={"username": username, "display_name": "Fault Test", "password": pw})
|
||
b64 = base64.b64encode(f"{username}:{pw}".encode()).decode()
|
||
res = client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"})
|
||
return res.json()["token"], res.json()["user"]["id"]
|
||
|
||
def make_png():
|
||
img = Image.new("RGB", (320, 200), (50, 100, 150))
|
||
buf = io.BytesIO()
|
||
img.save(buf, format="PNG")
|
||
return buf.getvalue()
|
||
|
||
def wait_for_api():
|
||
with get_client() as c:
|
||
for _ in range(30):
|
||
try:
|
||
if c.get("/health/ready").status_code == 200:
|
||
return
|
||
except Exception:
|
||
pass
|
||
time.sleep(1)
|
||
|
||
def wait_for_ready(client, h, att_id, timeout=30):
|
||
deadline = time.time() + timeout
|
||
while time.time() < deadline:
|
||
r = client.get(f"/attachments/{att_id}", headers=h)
|
||
if r.status_code == 200 and r.json()["status"] == "ready":
|
||
return r.json()
|
||
time.sleep(0.5)
|
||
raise AssertionError(f"Attachment {att_id} did not reach ready in {timeout}s")
|
||
|
||
def main():
|
||
print("=== ПРОВЕРКА СЦЕНАРИЕВ ОТКАЗОВ УРОВНЯ 4 ===")
|
||
with get_client() as client:
|
||
ts = int(time.time() * 1000)
|
||
token, uid = auth_user(client, f"u_fault_{ts}")
|
||
h = {"Authorization": f"Bearer {token}"}
|
||
chat_id = client.post("/chats", json={"title": "Fault Chat", "member_ids": [uid]}, headers=h).json()["id"]
|
||
png_data = make_png()
|
||
|
||
# --- СЦЕНАРИЙ 1: Остановка worker + 409 на content + рестарт API/broker ---
|
||
print("\n[Сценарий 1] Остановка worker...")
|
||
subprocess.run(["docker", "compose", "stop", "worker"], check=True)
|
||
|
||
up1 = client.post(f"/chats/{chat_id}/attachments?filename=stopped_w.png", content=png_data, headers={**h, "Content-Type": "image/png"})
|
||
assert up1.status_code == 202
|
||
att1_id = up1.json()["id"]
|
||
print(f" Загрузка при мёртвом worker -> 202 queued (ID: {att1_id})")
|
||
|
||
# Контент должен отвечать 409 Conflict
|
||
cont = client.get(f"/attachments/{att1_id}/content", headers=h)
|
||
assert cont.status_code == 409, f"Ожидался 409, получен {cont.status_code}"
|
||
print(f" GET /content при queued -> {cont.status_code} Conflict (верно!)")
|
||
|
||
# Сообщения продолжают работать
|
||
msg = client.post(f"/chats/{chat_id}/messages", json={"text": "Работаем без worker", "attachment_ids": [att1_id]}, headers={**h, "Idempotency-Key": str(uuid.uuid4())})
|
||
assert msg.status_code == 201
|
||
print(" Отправка сообщения с queued-вложением -> 201 Created (верно!)")
|
||
|
||
# Рестарт API и брокера, затем запуск worker
|
||
print(" Перезапуск API и RabbitMQ broker...")
|
||
subprocess.run(["docker", "compose", "restart", "api", "broker"], check=True)
|
||
wait_for_api()
|
||
print(" Запуск worker...")
|
||
subprocess.run(["docker", "compose", "start", "worker"], check=True)
|
||
|
||
ready1 = wait_for_ready(client, h, att1_id)
|
||
print(f" УСПЕХ! Вложение {att1_id} перешло в статус '{ready1['status']}' с {len(ready1['variants'])} вариантами!")
|
||
|
||
# --- СЦЕНАРИЙ 2: Разрыв COMMIT и publish (Outbox при недоступном брокере) ---
|
||
print("\n[Сценарий 2] Симуляция разрыва COMMIT -> publish (остановка broker)...")
|
||
subprocess.run(["docker", "compose", "stop", "broker"], check=True)
|
||
|
||
up2 = client.post(f"/chats/{chat_id}/attachments?filename=outbox_test.png", content=png_data, headers={**h, "Content-Type": "image/png"})
|
||
assert up2.status_code == 202
|
||
att2_id = up2.json()["id"]
|
||
print(f" Загрузка при упавшем брокере -> 202 queued (ID: {att2_id}, сохранено в Outbox!)")
|
||
|
||
print(" Восстановление RabbitMQ broker и перезапуск worker...")
|
||
subprocess.run(["docker", "compose", "start", "broker"], check=True)
|
||
time.sleep(5)
|
||
subprocess.run(["docker", "compose", "restart", "worker"], check=True)
|
||
|
||
ready2 = wait_for_ready(client, h, att2_id, timeout=30)
|
||
print(f" УСПЕХ! Outbox Relay доставил задачу, вложение {att2_id} стало '{ready2['status']}'!")
|
||
|
||
print("\n>>> ВСЕ СЦЕНАРИИ СБОЕВ УРОВНЯ 4 ПРОЙДЕНЫ БЕЗ ЕДИНОЙ ПОТЕРИ!")
|
||
|
||
if __name__ == "__main__":
|
||
main() |