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>
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
from dataclasses import asdict
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import delete, insert, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core.repos.user import USER_COLUMNS
|
||||
from src.infra.db.models import Session, User
|
||||
from src.schemas import dataclasses
|
||||
|
||||
|
||||
async def insert_session(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
session: dataclasses.SessionFullDTO,
|
||||
) -> dataclasses.SessionFullDTO:
|
||||
await db_session.execute(insert(Session).values(**asdict(session)))
|
||||
return session
|
||||
|
||||
|
||||
async def get_current_session(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
token_hash: bytes,
|
||||
now: datetime,
|
||||
) -> dataclasses.CurrentSessionDTO | None:
|
||||
"""Действующая сессия по хэшу токена вместе с владельцем.
|
||||
|
||||
Один запрос по уникальному индексу `token_hash`. Истёкшая сессия —
|
||||
None; `now` передаёт сервис: срок сравнивается по часам приложения,
|
||||
которые его и поставили.
|
||||
"""
|
||||
statement = (
|
||||
select(Session.id.label("session_id"), *USER_COLUMNS)
|
||||
.join(User, User.id == Session.user_id)
|
||||
.where(Session.token_hash == token_hash, Session.expires_at > now)
|
||||
)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
fields = dict(row._mapping)
|
||||
session_id = fields.pop("session_id")
|
||||
return dataclasses.CurrentSessionDTO(
|
||||
id=session_id,
|
||||
user=dataclasses.UserFullDTO(**fields),
|
||||
)
|
||||
|
||||
|
||||
async def delete_session(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
session_id: UUID,
|
||||
) -> bool:
|
||||
"""Отзыв; False — сессию уже удалил параллельный запрос."""
|
||||
statement = (
|
||||
delete(Session).where(Session.id == session_id).returning(Session.id)
|
||||
)
|
||||
return (await db_session.execute(statement)).one_or_none() is not None
|
||||
Reference in New Issue
Block a user