import asyncio from typing import Any from uuid import uuid4 import pytest from httpx import AsyncClient, Response from conftest import actor, keyed, make_chat, register, running_app, scalar INVALID_KEYS = ["", "k" * 129, "два слова", "a b", "a/b", "ключ"] async def send(http: AsyncClient, chat: dict, user: dict, text: str, key: str) -> Response: return await http.post( f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=keyed(user, key) ) async def history(http: AsyncClient, chat: dict, user: dict) -> list[dict[str, Any]]: response = await http.get(f"/api/v1/chats/{chat['id']}/messages?limit=100", headers=actor(user)) return response.json()["items"] async def test_replay_returns_the_same_message(client: AsyncClient) -> None: alice = await register(client, "alice") chat = await make_chat(client, alice) first = await send(client, chat, alice, "один раз", "replay-1") again = await send(client, chat, alice, "один раз", "replay-1") assert first.status_code == again.status_code == 201 assert again.json() == first.json() assert [item["id"] for item in await history(client, chat, alice)] == [first.json()["id"]] async def test_same_json_in_other_layout_is_a_replay(client: AsyncClient) -> None: alice = await register(client, "alice") chat = await make_chat(client, alice) first = await send(client, chat, alice, "форма", "layout-1") again = await client.post( f"/api/v1/chats/{chat['id']}/messages", content='{ "text" : "форма" }'.encode(), headers={**keyed(alice, "layout-1"), "Content-Type": "application/json"}, ) assert again.status_code == 201 assert again.json() == first.json() async def test_other_body_with_same_key_conflicts(client: AsyncClient) -> None: alice = await register(client, "alice") chat = await make_chat(client, alice) await send(client, chat, alice, "первое", "conflict-1") response = await send(client, chat, alice, "другое", "conflict-1") assert response.status_code == 409 assert response.json()["error"]["code"] == "conflict" assert len(await history(client, chat, alice)) == 1 async def test_missing_key_is_rejected(client: AsyncClient) -> None: alice = await register(client, "alice") chat = await make_chat(client, alice) response = await client.post( f"/api/v1/chats/{chat['id']}/messages", json={"text": "без ключа"}, headers=actor(alice) ) assert response.status_code == 400 assert response.json()["error"]["code"] == "invalid_request" assert await history(client, chat, alice) == [] @pytest.mark.parametrize("key", INVALID_KEYS, ids=range(len(INVALID_KEYS))) async def test_malformed_key_is_rejected(client: AsyncClient, key: str) -> None: alice = await register(client, "alice") chat = await make_chat(client, alice) headers = {**actor(alice), "Idempotency-Key": key} response = await client.post( f"/api/v1/chats/{chat['id']}/messages", json={"text": "ключ плохой"}, headers={name.encode(): value.encode() for name, value in headers.items()}, ) assert response.status_code == 400 assert await history(client, chat, alice) == [] async def test_rejected_attempt_does_not_take_the_key(client: AsyncClient) -> None: alice = await register(client, "alice") eve = await register(client, "eve") chat = await make_chat(client, alice) assert (await send(client, chat, alice, "", "spare-1")).status_code == 400 assert (await send(client, chat, eve, "чужое", "spare-1")).status_code == 404 assert (await send(client, chat, alice, "теперь можно", "spare-1")).status_code == 201 async def test_key_is_scoped_by_user_and_chat(client: AsyncClient) -> None: alice = await register(client, "alice") bob = await register(client, "bob") chat = await make_chat(client, alice, bob) other = await make_chat(client, alice) ids = { (await send(client, chat, alice, "алиса", "shared-1")).json()["id"], (await send(client, chat, bob, "боб", "shared-1")).json()["id"], (await send(client, other, alice, "другой чат", "shared-1")).json()["id"], } assert len(ids) == 3 async def test_replay_checks_session_and_access_again(client: AsyncClient) -> None: alice = await register(client, "alice") eve = await register(client, "eve") chat = await make_chat(client, alice) assert (await send(client, chat, alice, "до выхода", "recheck-1")).status_code == 201 assert (await send(client, chat, eve, "до выхода", "recheck-1")).status_code == 404 logout = await client.delete("/api/v1/auth/sessions/current", headers=actor(alice)) assert logout.status_code == 204 assert (await send(client, chat, alice, "до выхода", "recheck-1")).status_code == 401 async def test_expired_key_starts_over() -> None: async with running_app(idempotency_ttl_seconds=1) as http: alice = await register(http, "alice") chat = await make_chat(http, alice) first = await send(http, chat, alice, "давно", "expire-1") await asyncio.sleep(1.1) later = await send(http, chat, alice, "заново", "expire-1") assert later.status_code == 201 assert later.json()["id"] != first.json()["id"] assert len(await history(http, chat, alice)) == 2 async def test_concurrent_retries_through_two_replicas_store_one_message() -> None: async with ( running_app(instance_id="replica-a") as first, running_app(instance_id="replica-b") as second, ): alice = await register(first, "alice") chat = await make_chat(first, alice) key, text = uuid4().hex, "гонка ключа" responses = await asyncio.gather( *(send(http, chat, alice, text, key) for http in (first, second) * 4) ) assert {response.status_code for response in responses} == {201} assert {response.headers["X-Instance-Id"] for response in responses} == { "replica-a", "replica-b", } assert all(response.json() == responses[0].json() for response in responses) assert [item["text"] for item in await history(second, chat, alice)] == [text] assert await scalar("SELECT count(*) FROM idempotency_keys WHERE key = $1", key) == 1