feat: ЛР5 - асинхронная обработка вложений, RabbitMQ и transactional outbox

This commit is contained in:
Ильяс
2026-11-20 17:03:59 +03:00
parent 7cfc6d40a6
commit 7d06ecf230
27 changed files with 1536 additions and 103 deletions
+1 -1
View File
@@ -15,5 +15,5 @@ async def client():
async with AsyncClient(transport=transport, base_url="http://testserver") as ac:
yield ac
else:
async with AsyncClient(base_url=base_url) as ac:
async with AsyncClient(base_url=base_url, timeout=15.0) as ac:
yield ac
+143 -31
View File
@@ -298,9 +298,7 @@ async def test_multi_page_cursor_pagination(client: AsyncClient):
async def test_concurrency_race_condition(client: AsyncClient):
"""Проверка устойчивости к параллельным гонкам: 10 клиентов одновременно шлют 100 сообщений."""
# Создаём 10 пользователей
users = await asyncio.gather(
*(register_and_login(client, f"u{i}") for i in range(10))
)
users = [await register_and_login(client, f"u{i}") for i in range(10)]
all_user_ids = [u["user"]["id"] for u in users]
# Первый пользователь создаёт общий чат со всеми 10 участниками
@@ -619,7 +617,10 @@ async def test_invalid_cursor_date_returns_400(client: httpx.AsyncClient):
Некорректная дата курсора (например, 13-й месяц 2026-13-01T00:00:00.000000Z)
обязана возвращать 400 invalid_request (а не 500 internal_error).
"""
from app.storage import encode_cursor
def encode_cursor(data: dict) -> str:
import json
raw = json.dumps(data, separators=(",", ":")).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("utf-8").rstrip("=")
alice = await register_and_login(client, f"bad_cur_{uuid.uuid4().hex[:6]}")
chat = (
@@ -757,9 +758,24 @@ async def test_keyset_pagination_returns_next_cursor(client: httpx.AsyncClient):
assert data_p2["items"][0]["id"] != data_p1["items"][0]["id"]
async def wait_attachment_ready(
client: httpx.AsyncClient, headers: dict, att_id: str, timeout: float = 30.0
) -> dict:
deadline = asyncio.get_event_loop().time() + timeout
while asyncio.get_event_loop().time() < deadline:
res = await client.get(f"/api/v1/attachments/{att_id}", headers=headers)
assert res.status_code == 200, res.text
att = res.json()
assert att["status"] != "failed", f"Attachment entered failed status: {att}"
if att["status"] == "ready":
return att
await asyncio.sleep(0.2)
pytest.fail(f"Attachment {att_id} did not become ready within {timeout}s")
@pytest.mark.asyncio
async def test_attachment_upload_and_download_flow(client: httpx.AsyncClient):
"""Проверка полного цикла загрузки и скачивания PNG и JPEG вложений."""
"""Проверка асинхронного цикла 202 queued -> ready, thumbnail, crop, optimized."""
import hashlib
import io
from PIL import Image
@@ -785,7 +801,7 @@ async def test_attachment_upload_and_download_flow(client: httpx.AsyncClient):
headers={**alice["headers"], "Content-Type": "image/png"},
content=png_data,
)
assert up_res.status_code == 201, up_res.text
assert up_res.status_code == 202, up_res.text
att_png = up_res.json()
assert att_png["chat_id"] == chat_id
assert att_png["owner_id"] == alice["user"]["id"]
@@ -793,28 +809,62 @@ async def test_attachment_upload_and_download_flow(client: httpx.AsyncClient):
assert att_png["content_type"] == "image/png"
assert att_png["size_bytes"] == len(png_data)
assert att_png["sha256"] == png_sha
assert att_png["status"] == "ready"
assert att_png["status"] == "queued"
assert att_png["variants"] == []
assert att_png["error_code"] is None
# 2. Получение метаданных Бобом
meta_res = await client.get(
f"/api/v1/attachments/{att_png['id']}",
# До готовности скачивание контента возвращает 409
down_early = await client.get(
f"/api/v1/attachments/{att_png['id']}/content",
headers=bob["headers"],
)
assert meta_res.status_code == 200
assert meta_res.json() == att_png
if down_early.status_code != 200:
assert down_early.status_code == 409
# 3. Скачивание контента Бобом
# 2. Ожидание перехода в ready
ready_att = await wait_attachment_ready(client, bob["headers"], att_png["id"])
assert ready_att["status"] == "ready"
assert ready_att["error_code"] is None
assert len(ready_att["variants"]) >= 1
# 3. Скачивание оригинала Бобом
down_res = await client.get(
f"/api/v1/attachments/{att_png['id']}/content",
f"/api/v1/attachments/{att_png['id']}/content?variant=original",
headers=bob["headers"],
)
assert down_res.status_code == 200
assert down_res.headers.get("content-type") == "image/png"
assert down_res.content == png_data
# 4. Загрузка и скачивание JPEG
# 4. Проверка обязательного thumbnail (256x160 JPEG)
down_thumb = await client.get(
f"/api/v1/attachments/{att_png['id']}/content?variant=thumbnail",
headers=bob["headers"],
)
assert down_thumb.status_code == 200
assert down_thumb.headers.get("content-type") == "image/jpeg"
thumb_img = Image.open(io.BytesIO(down_thumb.content))
assert thumb_img.size == (256, 160)
# 5. Проверка crop (128x128 JPEG)
down_crop = await client.get(
f"/api/v1/attachments/{att_png['id']}/content?variant=crop",
headers=bob["headers"],
)
assert down_crop.status_code == 200
assert down_crop.headers.get("content-type") == "image/jpeg"
crop_img = Image.open(io.BytesIO(down_crop.content))
assert crop_img.size == (128, 128)
# 6. Проверка optimized (WebP)
down_opt = await client.get(
f"/api/v1/attachments/{att_png['id']}/content?variant=optimized",
headers=bob["headers"],
)
assert down_opt.status_code == 200
assert down_opt.headers.get("content-type") == "image/webp"
# 7. Загрузка и скачивание JPEG
jpeg_img = Image.new("RGB", (64, 64), color=(255, 128, 0))
jpeg_buf = io.BytesIO()
jpeg_img.save(jpeg_buf, format="JPEG")
@@ -825,11 +875,14 @@ async def test_attachment_upload_and_download_flow(client: httpx.AsyncClient):
headers={**alice["headers"], "Content-Type": "image/jpeg"},
content=jpeg_data,
)
assert up_jpeg.status_code == 201
assert up_jpeg.status_code == 202
att_jpeg = up_jpeg.json()
assert att_jpeg["content_type"] == "image/jpeg"
assert att_jpeg["size_bytes"] == len(jpeg_data)
ready_jpeg = await wait_attachment_ready(client, bob["headers"], att_jpeg["id"])
assert ready_jpeg["status"] == "ready"
down_jpeg = await client.get(
f"/api/v1/attachments/{att_jpeg['id']}/content",
headers=bob["headers"],
@@ -838,6 +891,23 @@ async def test_attachment_upload_and_download_flow(client: httpx.AsyncClient):
assert down_jpeg.headers.get("content-type") == "image/jpeg"
assert down_jpeg.content == jpeg_data
# 8. Проверка точного округления вниз (floor) для PNG 319x200 -> thumbnail 256x160
odd_img = Image.new("RGBA", (319, 200), color=(100, 150, 200, 255))
odd_buf = io.BytesIO()
odd_img.save(odd_buf, format="PNG")
odd_data = odd_buf.getvalue()
up_odd = await client.post(
f"/api/v1/chats/{chat_id}/attachments?filename=odd_319x200.png",
headers={**alice["headers"], "Content-Type": "image/png"},
content=odd_data,
)
assert up_odd.status_code == 202
ready_odd = await wait_attachment_ready(client, bob["headers"], up_odd.json()["id"])
thumb_var = next(v for v in ready_odd["variants"] if v["name"] == "thumbnail")
assert (thumb_var["width"], thumb_var["height"]) == (256, 160)
@pytest.mark.asyncio
async def test_attachment_unsupported_media_type_and_magic_bytes(client: httpx.AsyncClient):
@@ -1039,7 +1109,7 @@ async def test_attachment_acl_and_isolation(client: httpx.AsyncClient):
headers={**alice["headers"], "Content-Type": "image/png"},
content=png_data,
)
assert res_alice_up.status_code == 201
assert res_alice_up.status_code == 202
att_id = res_alice_up.json()["id"]
# 2. Посторонний пытается запросить метаданные -> 404
@@ -1095,23 +1165,25 @@ async def test_message_linking_attachments(client: httpx.AsyncClient):
with open("tests/fixtures/sample.png", "rb") as f:
png_data = f.read()
# Загружаем вложение в chat 1
# Загружаем вложение в chat 1 (возвращает 202 queued)
up1 = await client.post(
f"/api/v1/chats/{chat_id}/attachments?filename=sample.png",
headers={**alice["headers"], "Content-Type": "image/png"},
content=png_data,
)
assert up1.status_code == 202
att1_id = up1.json()["id"]
# Загружаем вложение в chat 2
# Загружаем вложение в chat 2 (возвращает 202 queued)
up2 = await client.post(
f"/api/v1/chats/{chat2_id}/attachments?filename=chat2.png",
headers={**alice["headers"], "Content-Type": "image/png"},
content=png_data,
)
assert up2.status_code == 202
att2_id = up2.json()["id"]
# 1. Сообщение с пустым текстом, но с вложением -> 201
# 1. Сообщение с пустым текстом, но с вложением в статусе queued -> 201
msg1_res = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
@@ -1157,15 +1229,47 @@ async def test_message_linking_attachments(client: httpx.AsyncClient):
assert msg5_res.status_code == 400
@pytest.mark.asyncio
async def test_message_linking_failed_attachment_rejected(client: httpx.AsyncClient):
"""Проверка запрета прикрепления failed-вложения к сообщению (409 Conflict)."""
alice = await register_and_login(client, "failed_a")
chat_res = await client.post(
"/api/v1/chats",
headers=alice["headers"],
json={"title": "Failed Attach Chat", "member_ids": [alice["user"]["id"]]},
)
chat_id = chat_res.json()["id"]
# Имитируем failed-вложение в БД
import subprocess
fake_att_id = str(uuid.uuid4())
insert_sql = f"""
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, s3_key, status, error_code, created_at, updated_at)
VALUES ('{fake_att_id}', '{chat_id}', '{alice["user"]["id"]}', 'corrupt.jpg', 'image/jpeg', 100, '0000000000000000000000000000000000000000000000000000000000000000', 'staging/corrupt', 'failed', 'invalid_image', NOW(), NOW());
"""
cmd = ["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "postgres", "-d", "messenger", "-c", insert_sql]
sub_res = subprocess.run(cmd, capture_output=True, text=True)
assert sub_res.returncode == 0
# Попытка прикрепить failed-вложение -> 409 Conflict
res_link = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
json={"text": "Trying failed attach", "attachment_ids": [fake_att_id]},
)
assert res_link.status_code == 409
assert res_link.json()["error"]["code"] == "conflict"
@pytest.mark.asyncio
async def test_attachment_orphan_compensation(client: httpx.AsyncClient):
"""
Проверка компенсации сиротских объектов S3 при сбое БД (критерий оценки 4):
1. Через docker compose exec в PostgreSQL создаём триггер, вызывающий сбой при записи файла 'orphan_sim_fail.png'.
2. Выполняем POST вложения 'orphan_sim_fail.png'.
S3 PUT проходит успешно, но при вставке в PostgreSQL возникает ошибка.
Сервер перехватывает ошибку, вызывает s3_client.delete_object и возвращает 500.
3. Проверяем, что сиротский объект удалён из S3 (через проверку через api-1/boto3).
S3 PUT проходит успешно в staging, но при вставке в PostgreSQL возникает ошибка.
Сервер перехватывает ошибку, вызывает s3_client.delete_object и возвращает 500/503.
3. Проверяем, что сиротский объект удалён из S3 staging.
4. Удаляем триггер из PostgreSQL.
"""
import subprocess
@@ -1205,10 +1309,10 @@ async def test_attachment_orphan_compensation(client: httpx.AsyncClient):
)
assert res.status_code in (500, 503)
check_py = f"""
check_py = """
import boto3
s3 = boto3.client('s3', endpoint_url='http://minio:9000', aws_access_key_id='minioadmin', aws_secret_access_key='minioadmin')
res = s3.list_objects_v2(Bucket='messenger-attachments', Prefix='chats/{chat_id}/')
res = s3.list_objects_v2(Bucket='messenger-attachments', Prefix='staging/')
keys = [o['Key'] for o in res.get('Contents', [])]
found = any('orphan_sim_fail.png' in k for k in keys)
print('FOUND' if found else 'NOT_FOUND')
@@ -1256,8 +1360,9 @@ async def test_concurrent_uploads_memory_limit(client: httpx.AsyncClient):
Проверка конкурентной загрузки ≥10 файлов с контролем потребления RAM (критерий оценки 4):
1. Создаем пользователя и чат.
2. Запускаем параллельную загрузку 10 изображений через asyncio.gather.
3. Измеряем память контейнеров API через docker stats.
4. Все 10 загрузок завершаются успехом (201 Created), память остаётся в стабильных границах.
3. Все 10 загрузок завершаются успехом (202 Accepted, status=queued).
4. Ожидаем готовности ready через wait_attachment_ready.
5. Измеряем память контейнеров API через docker stats.
"""
import subprocess
alice = await register_and_login(client, "conc_a")
@@ -1281,15 +1386,21 @@ async def test_concurrent_uploads_memory_limit(client: httpx.AsyncClient):
tasks = [upload_single(i) for i in range(10)]
responses = await asyncio.gather(*tasks)
att_ids = []
for resp in responses:
assert resp.status_code == 201
assert resp.status_code == 202
data = resp.json()
assert data["status"] == "ready"
assert data["status"] == "queued"
assert data["size_bytes"] == len(png_data)
att_ids.append(data["id"])
# Ожидаем готовности всех 10 файлов
ready_tasks = [wait_attachment_ready(client, alice["headers"], aid) for aid in att_ids]
await asyncio.gather(*ready_tasks)
# Проверяем docker stats
stats_cmd = [
"docker", "stats", "--no-stream", "--format", "{{.Name}}: {{.MemUsage}}",
"mtusi2026lab4-api-1-1", "mtusi2026lab4-api-2-1"
"docker", "stats", "--no-stream", "--format", "{{.Name}}: {{.MemUsage}}"
]
stats_res = subprocess.run(stats_cmd, capture_output=True, text=True)
assert stats_res.returncode == 0
@@ -1297,3 +1408,4 @@ async def test_concurrent_uploads_memory_limit(client: httpx.AsyncClient):