forked from mtusi2026/mtusi2026lab3
feat: конф нгинкс, тесты, ключ идмпт etc
This commit is contained in:
@@ -5,7 +5,7 @@ from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import auth, basic, unique_password, unique_username
|
||||
from helpers import auth, basic, message_headers, unique_password, unique_username
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_BASE_URL = json.loads((ROOT / "lab.json").read_text())["default_base_url"]
|
||||
@@ -68,7 +68,7 @@ def send_message(api: httpx.Client) -> Callable[..., dict]:
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=auth(user),
|
||||
headers=message_headers(user),
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
@@ -30,6 +30,11 @@ def auth(user: dict) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {user['token']}"}
|
||||
|
||||
|
||||
def message_headers(user: dict, key: str | None = None) -> dict[str, str]:
|
||||
"""Bearer и Idempotency-Key (новый, если не задан)"""
|
||||
return {**auth(user), "Idempotency-Key": key or uuid.uuid4().hex}
|
||||
|
||||
|
||||
def public_user(user: dict) -> dict:
|
||||
"""User из ответа API без тестовых полей token/password"""
|
||||
return {field: user[field] for field in USER_FIELDS}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
Балансировка без sticky sessions: запросы одной сессии обслуживают разные
|
||||
реплики, а состояние (сессии, сообщения, logout) общее для всех.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
import httpx
|
||||
from helpers import assert_unauthorized, auth, message_headers, public_user
|
||||
|
||||
REQUESTS = 20
|
||||
|
||||
|
||||
def test_one_session_is_served_by_several_replicas(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
"""Одно keep-alive соединение клиента к LB, без повторного входа"""
|
||||
alice = make_user("alice")
|
||||
instances: Counter[str] = Counter()
|
||||
for _ in range(REQUESTS):
|
||||
response = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == public_user(alice)
|
||||
instances[response.headers["X-Instance-Id"]] += 1
|
||||
print("\nINSTANCES FOR ONE SESSION:", dict(instances))
|
||||
assert len(instances) >= 2
|
||||
|
||||
|
||||
def test_write_is_visible_through_every_replica(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
sent = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"видно везде {uuid.uuid4().hex}"},
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert sent.status_code == 201, sent.text
|
||||
readers: set[str] = set()
|
||||
for _ in range(REQUESTS):
|
||||
page = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(bob))
|
||||
assert page.status_code == 200, page.text
|
||||
assert page.json()["items"] == [sent.json()]
|
||||
readers.add(page.headers["X-Instance-Id"])
|
||||
assert len(readers) >= 2
|
||||
|
||||
|
||||
def test_logout_applies_to_all_replicas(api: httpx.Client, make_user) -> None:
|
||||
"""Сессия попала в общий кэш через обе реплики, затем отозвана на одной"""
|
||||
alice = make_user("alice")
|
||||
for _ in range(4):
|
||||
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
|
||||
logout = api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
|
||||
assert logout.status_code == 204
|
||||
rejected_by: set[str] = set()
|
||||
for _ in range(REQUESTS):
|
||||
response = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert_unauthorized(response)
|
||||
rejected_by.add(response.headers["X-Instance-Id"])
|
||||
assert len(rejected_by) >= 2
|
||||
|
||||
|
||||
def test_every_api_response_has_instance_id(api: httpx.Client) -> None:
|
||||
for response in (
|
||||
api.get("/health/live"),
|
||||
api.get("/health/ready"),
|
||||
api.get("/api/v1/unknown"),
|
||||
api.get("/api/v1/users/me"),
|
||||
):
|
||||
assert response.headers["X-Instance-Id"]
|
||||
assert response.headers["X-Request-Id"]
|
||||
@@ -5,7 +5,7 @@ import json
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from helpers import auth, read_all_messages
|
||||
from helpers import auth, message_headers, read_all_messages
|
||||
|
||||
CLIENTS = 10
|
||||
MESSAGES_PER_CLIENT = 10
|
||||
@@ -29,6 +29,7 @@ async def _send_concurrently(
|
||||
client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
json={"text": f"{user['username']}#{n}"},
|
||||
headers=message_headers(user),
|
||||
)
|
||||
for n in range(MESSAGES_PER_CLIENT)
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from helpers import assert_error, auth
|
||||
from helpers import assert_error, auth, message_headers
|
||||
|
||||
|
||||
def test_outsider_cannot_access_chat(
|
||||
@@ -18,7 +18,9 @@ def test_outsider_cannot_access_chat(
|
||||
|
||||
assert_error(api.get(path, headers=auth(eve)), 404, "not_found")
|
||||
assert_error(api.get(f"{path}/messages", headers=auth(eve)), 404, "not_found")
|
||||
response = api.post(f"{path}/messages", json={"text": "чужое"}, headers=auth(eve))
|
||||
response = api.post(
|
||||
f"{path}/messages", json={"text": "чужое"}, headers=message_headers(eve)
|
||||
)
|
||||
assert_error(response, 404, "not_found")
|
||||
|
||||
history = api.get(f"{path}/messages", headers=auth(bob)).json()
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Idempotency-Key отправки сообщения: повтор, конфликт, область ключа, гонки"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth, message_headers, psql, read_all_messages
|
||||
|
||||
PARALLEL_REPLAYS = 20
|
||||
|
||||
|
||||
def post_message(
|
||||
api: httpx.Client, user: dict, chat: dict, text: str, key: str
|
||||
) -> httpx.Response:
|
||||
return api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=message_headers(user, key),
|
||||
)
|
||||
|
||||
|
||||
def history(api: httpx.Client, user: dict, chat: dict) -> list[dict]:
|
||||
items, _ = read_all_messages(api, user, chat["id"], 100)
|
||||
return items
|
||||
|
||||
|
||||
def test_replay_returns_same_message(api: httpx.Client, make_user, make_chat) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
first = post_message(api, alice, chat, "один раз", key)
|
||||
second = post_message(api, alice, chat, "один раз", key)
|
||||
|
||||
assert first.status_code == second.status_code == 201, second.text
|
||||
assert first.json() == second.json()
|
||||
assert history(api, alice, chat) == [first.json()]
|
||||
|
||||
|
||||
def test_replay_ignores_json_formatting(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
"""Пробелы и форма записи JSON не меняют смысл тела: это тот же запрос"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
headers = {**message_headers(alice), "Content-Type": "application/json"}
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
escaped = b'{"text":"\\u041f\\u0440\\u0438"}'
|
||||
compact = api.post(path, content=escaped, headers=headers)
|
||||
spaced = api.post(path, content='{ "text" : "При" }'.encode(), headers=headers)
|
||||
|
||||
assert compact.status_code == spaced.status_code == 201, spaced.text
|
||||
assert compact.json() == spaced.json()
|
||||
assert len(history(api, alice, chat)) == 1
|
||||
|
||||
|
||||
def test_same_key_with_other_body_is_conflict(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
original = post_message(api, alice, chat, "оригинал", key).json()
|
||||
|
||||
assert_error(post_message(api, alice, chat, "другой", key), 409, "conflict")
|
||||
assert history(api, alice, chat) == [original]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"headers",
|
||||
[
|
||||
{},
|
||||
{"Idempotency-Key": ""},
|
||||
{"Idempotency-Key": "with space"},
|
||||
{"Idempotency-Key": "ключ".encode()},
|
||||
{"Idempotency-Key": "a/b"},
|
||||
{"Idempotency-Key": "x" * 129},
|
||||
],
|
||||
)
|
||||
def test_missing_or_invalid_key_is_rejected(
|
||||
api: httpx.Client, make_user, make_chat, headers: dict
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "без ключа"},
|
||||
headers={**auth(alice), **headers},
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
assert history(api, alice, chat) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["x" * 128, "Az09._:-"])
|
||||
def test_key_boundaries_are_accepted(
|
||||
api: httpx.Client, make_user, make_chat, key: str
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
assert post_message(api, alice, chat, "граница", key).status_code == 201
|
||||
|
||||
|
||||
def test_key_scope_is_user_and_chat(api: httpx.Client, make_user, make_chat) -> None:
|
||||
"""Один ключ у разных пользователей и в разных чатах — независимые сообщения"""
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
other_chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
from_alice = post_message(api, alice, chat, "текст", key).json()
|
||||
from_bob = post_message(api, bob, chat, "текст", key).json()
|
||||
in_other_chat = post_message(api, alice, other_chat, "текст", key).json()
|
||||
|
||||
assert len({from_alice["id"], from_bob["id"], in_other_chat["id"]}) == 3
|
||||
assert from_bob["sender_id"] == bob["id"]
|
||||
assert len(history(api, alice, chat)) == 2
|
||||
assert len(history(api, alice, other_chat)) == 1
|
||||
|
||||
|
||||
def test_replay_rechecks_session_and_access(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
post_message(api, alice, chat, "секрет", key)
|
||||
|
||||
# Чужой с тем же ключом не получает сохранённое сообщение
|
||||
assert_error(post_message(api, eve, chat, "секрет", key), 404, "not_found")
|
||||
# Отозванная сессия не даёт повтора
|
||||
logout = api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
|
||||
assert logout.status_code == 204
|
||||
replay = post_message(api, alice, chat, "секрет", key)
|
||||
assert_error(replay, 401, "unauthorized")
|
||||
|
||||
|
||||
def test_expired_key_can_be_reused(api: httpx.Client, make_user, make_chat) -> None:
|
||||
"""После срока хранения (24 ч) ключ снова создаёт сообщение; срок сдвигается в БД"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
first = post_message(api, alice, chat, "вчера", key).json()
|
||||
psql(
|
||||
"UPDATE message_idempotency_keys "
|
||||
"SET created_at = now() - interval '2 days', "
|
||||
"expires_at = now() - interval '1 day' "
|
||||
f"WHERE chat_id = '{chat['id']}' AND idempotency_key = '{key}';"
|
||||
)
|
||||
|
||||
second = post_message(api, alice, chat, "сегодня", key)
|
||||
|
||||
assert second.status_code == 201, second.text
|
||||
assert second.json()["id"] != first["id"]
|
||||
assert [item["text"] for item in history(api, alice, chat)] == ["вчера", "сегодня"]
|
||||
stored = psql(
|
||||
"SELECT count(*) FROM message_idempotency_keys "
|
||||
f"WHERE chat_id = '{chat['id']}' AND idempotency_key = '{key}';"
|
||||
)
|
||||
assert stored == "1"
|
||||
|
||||
|
||||
async def _post_concurrently(
|
||||
base_url: str, user: dict, chat: dict, key: str, texts: list[str]
|
||||
) -> list[httpx.Response]:
|
||||
"""Все запросы стартуют по одному сигналу; отдельные соединения к LB"""
|
||||
start = asyncio.Event()
|
||||
limits = httpx.Limits(max_connections=len(texts))
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=base_url, timeout=30, limits=limits
|
||||
) as client:
|
||||
|
||||
async def post(text: str) -> httpx.Response:
|
||||
await start.wait()
|
||||
return await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=message_headers(user, key),
|
||||
)
|
||||
|
||||
tasks = [asyncio.create_task(post(text)) for text in texts]
|
||||
await asyncio.sleep(0)
|
||||
start.set()
|
||||
return list(await asyncio.gather(*tasks))
|
||||
|
||||
|
||||
def test_parallel_replays_through_replicas_create_one_message(
|
||||
api: httpx.Client, base_url: str, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
responses = asyncio.run(
|
||||
_post_concurrently(
|
||||
base_url, alice, chat, key, ["одно сообщение"] * PARALLEL_REPLAYS
|
||||
)
|
||||
)
|
||||
|
||||
statuses = Counter(response.status_code for response in responses)
|
||||
instances = Counter(response.headers["X-Instance-Id"] for response in responses)
|
||||
bodies = {json.dumps(response.json(), sort_keys=True) for response in responses}
|
||||
items = history(api, alice, chat)
|
||||
rows = psql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat['id']}';")
|
||||
print(
|
||||
"\nPARALLEL SAME KEY:",
|
||||
json.dumps(
|
||||
{
|
||||
"requests": len(responses),
|
||||
"statuses": dict(statuses),
|
||||
"instances": dict(instances),
|
||||
"distinct_bodies": len(bodies),
|
||||
"messages_in_history": len(items),
|
||||
"rows_in_db": int(rows),
|
||||
}
|
||||
),
|
||||
)
|
||||
assert statuses == {201: PARALLEL_REPLAYS}
|
||||
assert len(instances) >= 2, "запросы не распределились по репликам"
|
||||
assert len(bodies) == 1
|
||||
assert len(items) == 1 and rows == "1"
|
||||
|
||||
|
||||
def test_parallel_same_key_with_different_bodies(
|
||||
api: httpx.Client, base_url: str, make_user, make_chat
|
||||
) -> None:
|
||||
"""Победитель гонки один; совпавшие с ним тела — 201, остальные — 409"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
texts = ["вариант A", "вариант B"] * (PARALLEL_REPLAYS // 2)
|
||||
|
||||
responses = asyncio.run(_post_concurrently(base_url, alice, chat, key, texts))
|
||||
|
||||
items = history(api, alice, chat)
|
||||
assert len(items) == 1
|
||||
winner = items[0]
|
||||
for text, response in zip(texts, responses):
|
||||
if text == winner["text"]:
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.json() == winner
|
||||
else:
|
||||
assert_error(response, 409, "conflict")
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth
|
||||
from helpers import assert_error, auth, message_headers
|
||||
|
||||
PASSWORD = "Valid-password-123"
|
||||
|
||||
@@ -32,8 +32,16 @@ def test_malformed_json_on_create_chat_and_message(
|
||||
assert_error(
|
||||
api.post("/api/v1/chats", content=raw, headers=headers), 400, "invalid_request"
|
||||
)
|
||||
message_post_headers = {
|
||||
**message_headers(alice),
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
assert_error(
|
||||
api.post(f"/api/v1/chats/{chat['id']}/messages", content=raw, headers=headers),
|
||||
api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
content=raw,
|
||||
headers=message_post_headers,
|
||||
),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
@@ -78,7 +86,9 @@ def test_invalid_message_payload(
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json=body, headers=auth(alice)
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json=body,
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth
|
||||
from helpers import assert_error, auth, message_headers
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", " ", " \n\t ", " "])
|
||||
@@ -12,7 +12,9 @@ def test_empty_or_blank_message_is_rejected(
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=auth(alice)
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
history = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(alice))
|
||||
@@ -29,7 +31,7 @@ def test_message_length_is_counted_in_code_points(
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "😀" * 4001},
|
||||
headers=auth(alice),
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
@@ -56,7 +58,7 @@ def test_nul_character_is_rejected(api: httpx.Client, make_user, make_chat) -> N
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "до\u0000после"},
|
||||
headers=auth(alice),
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
response = api.post(
|
||||
|
||||
Reference in New Issue
Block a user