Files
mtusi2026lab3/src/core/repos/message.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

55 lines
1.6 KiB
Python

from dataclasses import asdict
from uuid import UUID
from sqlalchemy import insert, select, tuple_
from sqlalchemy.ext.asyncio import AsyncSession
from src.infra.db.models import Message
from src.schemas import dataclasses
from src.utils.cursor import CursorKey
# колонки MessageFullDTO; их же выбирает чтение сохранённого результата
# ключа идемпотентности
MESSAGE_COLUMNS = (
Message.id,
Message.chat_id,
Message.sender_id,
Message.text,
Message.created_at,
)
async def insert_message(
db_session: AsyncSession,
*,
message: dataclasses.MessageFullDTO,
) -> dataclasses.MessageFullDTO:
await db_session.execute(insert(Message).values(**asdict(message)))
return message
async def get_chat_messages_page(
db_session: AsyncSession,
*,
chat_id: UUID,
after: CursorKey | None,
limit: int,
) -> list[dataclasses.MessageFullDTO]:
"""До `limit + 1` сообщений чата строго после ключа `after`.
Keyset по индексу `(chat_id, created_at, id)`, без OFFSET: страница
не просматривает историю до курсора.
"""
statement = (
select(*MESSAGE_COLUMNS)
.where(Message.chat_id == chat_id)
.order_by(Message.created_at, Message.id)
.limit(limit + 1)
)
if after is not None:
statement = statement.where(
tuple_(Message.created_at, Message.id) > tuple_(*after),
)
rows = (await db_session.execute(statement)).all()
return [dataclasses.MessageFullDTO(**row._mapping) for row in rows]