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
@@ -16,11 +16,11 @@
## 4. Идемпотентная отправка (зона `messaging`)
- [ ] 4.1 Домен: `Receipt` с `replay`, ошибка `IdempotencyConflict`; команда `PostMessage` с ключом и отпечатком
- [ ] 4.2 Порт и адаптер PostgreSQL: поиск квитанции с учётом TTL, запись сообщения и ключа одним оператором; `LockNotAvailableError` → `503`
- [ ] 4.3 Обработчик: блокировка чата → `chat.post` → квитанция → повтор, `409` или запись; `IDEMPOTENCY_TTL_SECONDS` в настройках зоны
- [ ] 4.4 HTTP: обязательный заголовок `Idempotency-Key` (`400`), отпечаток канонического JSON модели, `409 conflict` в реестре ошибок зоны
- [ ] 4.5 Проверка группы: тесты — повтор, другое тело `409`, нет и неверный ключ `400`, `4xx` не занимает ключ, другой пользователь и другой чат независимы, повтор после выхода `401`, посторонний `404`, истёкший ключ, 8 конкурентных повторов в реальном PostgreSQL дают одно сообщение; ключ во всех прежних отправках
- [x] 4.1 Домен: `Receipt` с `replay`, ошибка `IdempotencyConflict`; команда `PostMessage` с ключом и отпечатком
- [x] 4.2 Порт и адаптер PostgreSQL: поиск квитанции с учётом TTL, запись сообщения и ключа одним оператором; `LockNotAvailableError` → `503`
- [x] 4.3 Обработчик: блокировка чата → `chat.post` → квитанция → повтор, `409` или запись; `IDEMPOTENCY_TTL_SECONDS` в настройках зоны
- [x] 4.4 HTTP: обязательный заголовок `Idempotency-Key` (`400`), отпечаток канонического JSON модели, `409 conflict` в реестре ошибок зоны
- [x] 4.5 Проверка группы: тесты — повтор, другое тело `409`, нет и неверный ключ `400`, `4xx` не занимает ключ, другой пользователь и другой чат независимы, повтор после выхода `401`, посторонний `404`, истёкший ключ, 8 конкурентных повторов в реальном PostgreSQL дают одно сообщение; ключ во всех прежних отправках
## 5. Стенд