forked from mtusi2026/mtusi2026lab3
POST /api/v1/chats/{chat_id}/messages now requires the header, checked
at the HTTP boundary (1-128 of [A-Za-z0-9._:-], else 400). The handler
keeps the lab 2 order under the chat row lock: membership, then text,
then the receipt for (chat, sender, key) younger than
IDEMPOTENCY_TTL_SECONDS. A receipt with the same fingerprint replays
the stored message, a different one is 409 conflict; without a
receipt one statement inserts the message, the key row and the chat
mark, so both commit or neither does. Concurrent retries wait on the
same row lock and then read the committed receipt. The fingerprint is
SHA-256 of the canonical JSON of the parsed body, so layout does not
matter, and only 201 answers are ever stored.
A lock timeout now counts as a dependency failure and answers 503
instead of 500, so a retry with the same key is safe.
Own tests cover replay, a different layout of the same JSON, conflict,
missing and malformed keys, rejected attempts that leave the key free,
scope by user and chat, revalidation after logout and for outsiders,
expiry, and eight concurrent retries through two app instances
sharing one PostgreSQL. Every earlier message post sends a fresh key.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
156 lines
5.9 KiB
Python
156 lines
5.9 KiB
Python
from urllib.parse import quote
|
|
|
|
import pytest
|
|
from httpx import AsyncClient
|
|
|
|
from conftest import actor, keyed, make_chat, register
|
|
|
|
TOTAL = 12
|
|
|
|
|
|
async def fill(client: AsyncClient, chat: dict, sender: dict, count: int) -> list[str]:
|
|
texts = []
|
|
for index in range(count):
|
|
text = f"сообщение {index:02d}"
|
|
response = await client.post(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
json={"text": text},
|
|
headers=keyed(sender),
|
|
)
|
|
assert response.status_code == 201, response.text
|
|
texts.append(text)
|
|
return texts
|
|
|
|
|
|
async def walk(client: AsyncClient, chat: dict, reader: dict, limits: list[int]) -> list[str]:
|
|
collected: list[str] = []
|
|
cursor: str | None = None
|
|
step = 0
|
|
while True:
|
|
limit = limits[min(step, len(limits) - 1)]
|
|
query = f"?limit={limit}"
|
|
if cursor:
|
|
query += f"&cursor={quote(cursor, safe='')}"
|
|
response = await client.get(
|
|
f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader)
|
|
)
|
|
assert response.status_code == 200, response.text
|
|
page = response.json()
|
|
assert len(page["items"]) <= limit
|
|
collected.extend(item["text"] for item in page["items"])
|
|
cursor = page["next_cursor"]
|
|
step += 1
|
|
if cursor is None:
|
|
return collected
|
|
|
|
|
|
async def test_full_walk_has_no_gaps_or_repeats(client: AsyncClient) -> None:
|
|
alice = await register(client, "alice")
|
|
bob = await register(client, "bob")
|
|
chat = await make_chat(client, alice, bob)
|
|
expected = await fill(client, chat, alice, TOTAL)
|
|
assert await walk(client, chat, bob, [5]) == expected
|
|
|
|
|
|
async def test_limit_may_change_between_pages(client: AsyncClient) -> None:
|
|
alice = await register(client, "alice")
|
|
chat = await make_chat(client, alice)
|
|
expected = await fill(client, chat, alice, TOTAL)
|
|
assert await walk(client, chat, alice, [1, 7, 3, 100]) == expected
|
|
|
|
|
|
async def test_last_page_closes_history(client: AsyncClient) -> None:
|
|
alice = await register(client, "alice")
|
|
chat = await make_chat(client, alice)
|
|
await fill(client, chat, alice, 2)
|
|
first = (
|
|
await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=2", headers=actor(alice))
|
|
).json()
|
|
assert len(first["items"]) == 2
|
|
assert first["next_cursor"] is None
|
|
|
|
|
|
async def test_cursor_is_shared_between_members(client: AsyncClient) -> None:
|
|
alice = await register(client, "alice")
|
|
bob = await register(client, "bob")
|
|
chat = await make_chat(client, alice, bob)
|
|
await fill(client, chat, alice, 3)
|
|
page = (
|
|
await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=actor(alice))
|
|
).json()
|
|
cursor = quote(page["next_cursor"], safe="")
|
|
response = await client.get(
|
|
f"/api/v1/chats/{chat['id']}/messages?limit=1&cursor={cursor}", headers=actor(bob)
|
|
)
|
|
assert response.status_code == 200
|
|
|
|
|
|
async def test_cursor_from_another_chat_is_rejected(client: AsyncClient) -> None:
|
|
alice = await register(client, "alice")
|
|
first = await make_chat(client, alice)
|
|
second = await make_chat(client, alice)
|
|
await fill(client, first, alice, 3)
|
|
await fill(client, second, alice, 3)
|
|
page = (
|
|
await client.get(f"/api/v1/chats/{first['id']}/messages?limit=1", headers=actor(alice))
|
|
).json()
|
|
cursor = quote(page["next_cursor"], safe="")
|
|
response = await client.get(
|
|
f"/api/v1/chats/{second['id']}/messages?limit=1&cursor={cursor}", headers=actor(alice)
|
|
)
|
|
assert response.status_code == 400
|
|
assert response.json()["error"]["code"] == "invalid_request"
|
|
|
|
|
|
@pytest.mark.parametrize("cursor", ["garbage", "1.2.3.4", "%20"])
|
|
async def test_broken_cursor_is_rejected(client: AsyncClient, cursor: str) -> None:
|
|
alice = await register(client, "alice")
|
|
chat = await make_chat(client, alice)
|
|
response = await client.get(
|
|
f"/api/v1/chats/{chat['id']}/messages?cursor={cursor}", headers=actor(alice)
|
|
)
|
|
assert response.status_code == 400
|
|
|
|
|
|
@pytest.mark.parametrize("limit", ["0", "-1", "101", "abc", "1.5", ""])
|
|
async def test_limit_out_of_range(client: AsyncClient, limit: str) -> None:
|
|
alice = await register(client, "alice")
|
|
chat = await make_chat(client, alice)
|
|
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
|
|
response = await client.get(f"{path}?limit={limit}", headers=actor(alice))
|
|
assert response.status_code == 400, f"{path}?limit={limit} → {response.status_code}"
|
|
|
|
|
|
async def test_default_limit_is_50(client: AsyncClient) -> None:
|
|
alice = await register(client, "alice")
|
|
chat = await make_chat(client, alice)
|
|
await fill(client, chat, alice, 51)
|
|
page = (await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))).json()
|
|
assert len(page["items"]) == 50
|
|
assert page["next_cursor"] is not None
|
|
|
|
|
|
async def test_unknown_query_parameter_is_ignored(client: AsyncClient) -> None:
|
|
alice = await register(client, "alice")
|
|
chat = await make_chat(client, alice)
|
|
await fill(client, chat, alice, 2)
|
|
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
|
|
response = await client.get(f"{path}?limit=1&unknown=x", headers=actor(alice))
|
|
assert response.status_code == 200, response.text
|
|
assert len(response.json()["items"]) == 1
|
|
|
|
|
|
async def test_chat_list_pagination(client: AsyncClient) -> None:
|
|
alice = await register(client, "alice")
|
|
created = [(await make_chat(client, alice))["id"] for _ in range(5)]
|
|
collected: list[str] = []
|
|
cursor: str | None = None
|
|
while True:
|
|
query = "?limit=2" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
|
|
page = (await client.get(f"/api/v1/chats{query}", headers=actor(alice))).json()
|
|
collected.extend(item["id"] for item in page["items"])
|
|
cursor = page["next_cursor"]
|
|
if cursor is None:
|
|
break
|
|
assert collected == created
|