Make message posts idempotent with Idempotency-Key

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>
This commit is contained in:
Artyom
2026-10-28 11:36:15 +03:00
co-authored by Claude Opus 5.5
parent a18e7b320b
commit 7bf28fc6ed
26 changed files with 293 additions and 45 deletions
+3 -3
View File
@@ -2,7 +2,7 @@ from uuid import uuid4
from httpx import AsyncClient
from conftest import actor, make_chat, register
from conftest import actor, keyed, make_chat, register
async def test_outsider_gets_404_on_chat(client: AsyncClient) -> None:
@@ -33,7 +33,7 @@ async def test_outsider_cannot_write(client: AsyncClient) -> None:
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "чужое"},
headers=actor(eve),
headers=keyed(eve),
)
assert response.status_code == 404
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))
@@ -55,7 +55,7 @@ async def test_access_checked_before_body(client: AsyncClient) -> None:
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": ""},
headers=actor(eve),
headers=keyed(eve),
)
assert response.status_code == 404
+1 -1
View File
@@ -214,7 +214,7 @@ def test_zone_errors_do_not_leak_transport_codes() -> None:
IDENTITY_TABLES = ("users", "sessions")
MESSAGING_TABLES = ("chats", "chat_members", "messages")
MESSAGING_TABLES = ("chats", "chat_members", "messages", "idempotency_keys")
def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
+2 -2
View File
@@ -4,7 +4,7 @@ from uuid import uuid4
from httpx import AsyncClient
from conftest import PASSWORD, actor, make_chat, register
from conftest import PASSWORD, actor, keyed, make_chat, register
CLIENTS = 10
PER_CLIENT = 10
@@ -32,7 +32,7 @@ async def flood(client: AsyncClient, chat: dict, sender: dict) -> list[int]:
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"нагрузка-{worker}-{index}"},
headers=actor(sender),
headers=keyed(sender),
)
codes.append(response.status_code)
return codes
+6 -6
View File
@@ -4,7 +4,7 @@ from uuid import uuid4
from httpx import AsyncClient
from conftest import PASSWORD, actor, make_chat, new_user, register, running_app, scalar
from conftest import PASSWORD, actor, keyed, make_chat, new_user, register, running_app, scalar
REGISTRATIONS = 25
@@ -98,14 +98,14 @@ async def test_rejected_message_does_not_enter_history() -> None:
await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": " "},
headers=actor(alice),
headers=keyed(alice),
)
).status_code == 400
assert (
await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "чужое"},
headers=actor(eve),
headers=keyed(eve),
)
).status_code == 404
@@ -122,7 +122,7 @@ async def test_confirmed_write_is_visible_to_next_read() -> None:
posted = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"подтверждение {index}"},
headers=actor(alice),
headers=keyed(alice),
)
assert posted.status_code == 201
history = await drain_history(client, chat, bob)
@@ -140,7 +140,7 @@ async def test_parallel_writes_across_zones_keep_counts_consistent() -> None:
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"поток-{worker}-{index}"},
headers=actor(alice),
headers=keyed(alice),
)
assert response.status_code == 201
@@ -173,7 +173,7 @@ async def test_chat_membership_survives_parallel_reads_and_writes() -> None:
await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"параллельно {index}"},
headers=actor(alice),
headers=keyed(alice),
)
async def intruder() -> int:
+2 -2
View File
@@ -5,7 +5,7 @@ from uuid import uuid4
from httpx import ASGITransport, AsyncClient
from conftest import actor, make_chat, register, split_settings
from conftest import keyed, make_chat, register, split_settings
from fakes import NullLogger
from messenger.identity.domain.events import UserRegistered
from messenger.main import create_app
@@ -108,7 +108,7 @@ async def test_publication_does_not_delay_response() -> None:
http.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "не ждём обработчик"},
headers=actor(alice),
headers=keyed(alice),
),
timeout=2,
)
+145
View File
@@ -0,0 +1,145 @@
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
+4 -4
View File
@@ -3,7 +3,7 @@ from uuid import uuid4
import pytest
from httpx import AsyncClient
from conftest import PASSWORD, actor, make_chat, register
from conftest import PASSWORD, actor, keyed, make_chat, register
ERROR_CODES = {
400: "invalid_request",
@@ -122,7 +122,7 @@ async def test_empty_message_rejected(client: AsyncClient) -> None:
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": text},
headers=actor(alice),
headers=keyed(alice),
)
assert_error(response, 400)
@@ -133,7 +133,7 @@ async def test_long_message_rejected(client: AsyncClient) -> None:
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "я" * 4001},
headers=actor(alice),
headers=keyed(alice),
)
assert_error(response, 400)
@@ -145,7 +145,7 @@ async def test_sender_id_not_accepted(client: AsyncClient) -> None:
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "подмена", "sender_id": bob["id"]},
headers=actor(alice),
headers=keyed(alice),
)
assert_error(response, 400)
+2 -2
View File
@@ -4,7 +4,7 @@ from uuid import uuid4
from httpx import ASGITransport, AsyncClient
from conftest import PASSWORD, actor, make_chat, register, running_app, split_settings
from conftest import PASSWORD, actor, keyed, make_chat, register, running_app, split_settings
from messenger.main import create_app
MARKER_TEXT = "маркер-который-не-должен-попасть-в-логи-9f3a"
@@ -67,7 +67,7 @@ async def test_logs_do_not_contain_message_text(capsys) -> None:
response = await http.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": MARKER_TEXT},
headers=actor(alice),
headers=keyed(alice),
)
assert response.status_code == 201
captured = capsys.readouterr()
+2 -2
View File
@@ -3,7 +3,7 @@ from urllib.parse import quote
import pytest
from httpx import AsyncClient
from conftest import actor, make_chat, register
from conftest import actor, keyed, make_chat, register
TOTAL = 12
@@ -15,7 +15,7 @@ async def fill(client: AsyncClient, chat: dict, sender: dict, count: int) -> lis
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": text},
headers=actor(sender),
headers=keyed(sender),
)
assert response.status_code == 201, response.text
texts.append(text)
+2 -2
View File
@@ -4,7 +4,7 @@ from contextlib import asynccontextmanager
from httpx import AsyncClient
from conftest import actor, make_chat, register, resolve, running_app
from conftest import keyed, make_chat, register, resolve, running_app
from messenger.messaging.application import handlers
from messenger.messaging.domain.events import MessagePosted
from messenger.shared.application.messagebus import EventBus
@@ -29,7 +29,7 @@ async def slow_post(delay: float) -> AsyncIterator[None]:
async def post(client: AsyncClient, chat: dict, sender: dict, text: str):
return await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=actor(sender)
f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=keyed(sender)
)
+2 -1
View File
@@ -54,7 +54,8 @@ async def test_created_at_is_rfc3339_utc(monkeypatch: pytest.MonkeyPatch, moment
assert_wire(listed, {"items": [chat], "next_cursor": None})
path = f"/api/v1/chats/{chat_id}/messages"
response = await http.post(path, json={"text": "привет"}, headers=headers)
sent = {**headers, "Idempotency-Key": "wire-1"}
response = await http.post(path, json={"text": "привет"}, headers=sent)
message = {
"id": response.json()["id"],
"chat_id": chat_id,