Files
mtusi2026lab3-safronov/src/core/repos/idempotency.py
T
ricoromaandClaude Opus 5.5 af4bca08c9 feat: carry lab 2 over and add X-Instance-Id and idempotency keys
- carry the lab 2 solution over and plan lab 3 (PLAN.md, OpenSpec
  change instance-id-idempotency)
- rename the compose project to mtusi-lab3 and the image to :lab3
- add X-Instance-Id to every response and instance_id to every log
  record ([app] instance_id, hostname by default)
- require Idempotency-Key on POST messages: keys table in Postgres,
  key and message in one transaction, replay returns the same 201,
  another body gets 409, TTL from [idempotency] ttl_seconds
- send the key from student-tests, k6 scenarios and the skill driver;
  add idempotency, X-Instance-Id, key race and fault tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 19:42:36 +03:00

91 lines
3.2 KiB
Python

"""Ключи идемпотентности отправки сообщения.
Решение «повтор или 409» и срок ключа — в сервисе; здесь две атомарные
операции: захват ключа и чтение сохранённого результата (design change
`instance-id-idempotency`, решение 3).
"""
from datetime import datetime
from uuid import UUID
from sqlalchemy import select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
from src.core.repos.message import MESSAGE_COLUMNS
from src.infra.db.models import IdempotencyKey, Message
from src.schemas import dataclasses
_KEY_COLUMNS = (
IdempotencyKey.user_id,
IdempotencyKey.chat_id,
IdempotencyKey.key,
)
async def claim_key(
db_session: AsyncSession,
*,
user_id: UUID,
chat_id: UUID,
key: str,
request_hash: bytes,
message_id: UUID,
created_at: datetime,
expired_before: datetime,
) -> bool:
"""Захват ключа под новое сообщение `message_id`.
True — ключ свободен: новый или просроченный (`created_at` раньше
`expired_before`), который заменён этим же выражением. False — ключ
занят и ещё действует. Одновременная вставка того же ключа ждёт
commit или отката чужой транзакции, а занятая строка остаётся
заблокированной до конца транзакции, даже если срок не истёк.
"""
insert = pg_insert(IdempotencyKey).values(
user_id=user_id,
chat_id=chat_id,
key=key,
request_hash=request_hash,
message_id=message_id,
created_at=created_at,
)
statement = insert.on_conflict_do_update(
index_elements=list(_KEY_COLUMNS),
set_={
"request_hash": insert.excluded.request_hash,
"message_id": insert.excluded.message_id,
"created_at": insert.excluded.created_at,
},
where=IdempotencyKey.created_at < expired_before,
).returning(IdempotencyKey.message_id)
return (await db_session.execute(statement)).one_or_none() is not None
async def get_key_result(
db_session: AsyncSession,
*,
user_id: UUID,
chat_id: UUID,
key: str,
) -> dataclasses.IdempotencyRecordDTO | None:
"""Хэш тела и сообщение, сохранённые под ключом; None — ключа нет."""
statement = (
select(IdempotencyKey.request_hash, *MESSAGE_COLUMNS)
.join(Message, Message.id == IdempotencyKey.message_id)
.where(
IdempotencyKey.user_id == user_id,
IdempotencyKey.chat_id == chat_id,
IdempotencyKey.key == key,
)
)
row = (await db_session.execute(statement)).one_or_none()
if row is None:
return None
fields = dict(row._mapping)
request_hash = fields.pop("request_hash")
return dataclasses.IdempotencyRecordDTO(
request_hash=request_hash,
message=dataclasses.MessageFullDTO(**fields),
)