forked from mtusi2026/mtusi2026lab5
Complete Lab 5 for Grade 4
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
import asyncpg
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
DB_URL = open("/run/secrets/database_url").read().strip() if os.path.exists("/run/secrets/database_url") else "postgresql://appuser:apppassword@postgres:5432/messenger_db"
|
||||
BASE_URL = "http://load_balancer:8080"
|
||||
|
||||
def make_png():
|
||||
img = Image.new("RGB", (320, 200), (80, 120, 200))
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
async def wait_ready(client, h, att_id, timeout=20):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
r = await client.get(f"/attachments/{att_id}", headers=h)
|
||||
if r.status_code == 200 and r.json()["status"] == "ready":
|
||||
return r.json()
|
||||
await asyncio.sleep(0.5)
|
||||
raise AssertionError("Did not become ready")
|
||||
|
||||
async def main():
|
||||
print("=== ПРОВЕРКА REPLAY FAILED И LEASE RECOVERY (CRASH ДО ACK) ===")
|
||||
conn = await asyncpg.connect(DB_URL)
|
||||
|
||||
async with httpx.AsyncClient(base_url=BASE_URL, timeout=15.0) as client:
|
||||
ts = int(time.time() * 1000)
|
||||
uname = f"u_rep_{ts}"
|
||||
pw = "super_password_12345"
|
||||
await client.post("/users", json={"username": uname, "display_name": "Replay", "password": pw})
|
||||
b64 = base64.b64encode(f"{uname}:{pw}".encode()).decode()
|
||||
login = (await client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"})).json()
|
||||
token, uid = login["token"], login["user"]["id"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
chat_id = (await client.post("/chats", json={"title": "Replay Chat", "member_ids": [uid]}, headers=h)).json()["id"]
|
||||
|
||||
# Загружаем вложение и ждём первичного ready
|
||||
up = await client.post(f"/chats/{chat_id}/attachments?filename=rep.png", content=make_png(), headers={**h, "Content-Type": "image/png"})
|
||||
att_id = up.json()["id"]
|
||||
await wait_ready(client, h, att_id)
|
||||
print(f"Подготовлено вложение: {att_id}")
|
||||
|
||||
# 1. Тест REPLAY FAILED
|
||||
print("\n[Тест 1] Имитация failed -> операторский replay -> ready...")
|
||||
await conn.execute("UPDATE attachments SET status='failed', error_code='processing_failed' WHERE id=$1", uuid.UUID(att_id))
|
||||
await conn.execute("UPDATE attachment_jobs SET status='failed', last_error_code='processing_failed' WHERE attachment_id=$1", uuid.UUID(att_id))
|
||||
|
||||
rep_res = await client.post(f"/internal/attachments/{att_id}/replay")
|
||||
assert rep_res.status_code == 200 and rep_res.json()["replayed"] is True
|
||||
print(f" Вызов /replay вернул: {rep_res.json()}")
|
||||
|
||||
ready1 = await wait_ready(client, h, att_id)
|
||||
assert len(ready1["variants"]) == 3
|
||||
print(f" УСПЕХ! После replay статус снова 'ready', вариантов ровно {len(ready1['variants'])}.")
|
||||
|
||||
# 2. Тест CRASH ПОСЛЕ S3 ДО ACK / LEASE RECOVERY
|
||||
print("\n[Тест 2] Имитация зависшего processing (объекты в S3 уже есть, lease истек)...")
|
||||
await conn.execute("UPDATE attachments SET status='processing' WHERE id=$1", uuid.UUID(att_id))
|
||||
await conn.execute(
|
||||
"UPDATE attachment_jobs SET status='processing', locked_until = NOW() - interval '5 seconds', outbox_published = TRUE WHERE attachment_id=$1",
|
||||
uuid.UUID(att_id)
|
||||
)
|
||||
print(" Lease просрочен -> ожидаем автоматический возврат в очередь и идемпотентную обработку...")
|
||||
ready2 = await wait_ready(client, h, att_id)
|
||||
assert len(ready2["variants"]) == 3
|
||||
v_count = await conn.fetchval("SELECT count(*) FROM attachment_variants WHERE attachment_id=$1", uuid.UUID(att_id))
|
||||
assert v_count == 3, f"Найдены дубликаты вариантов: {v_count}"
|
||||
print(f" УСПЕХ! Lease восстановлен, повторная доставка завершилась 'ready', вариантов в БД ровно {v_count} (дубликатов нет!).")
|
||||
|
||||
await conn.close()
|
||||
print("\n>>> ВСЕ ПРОВЕРКИ УРОВНЯ 4 ЗАВЕРШЕНЫ!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user