forked from mtusi2026/mtusi2026lab3
- 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>
70 lines
2.4 KiB
Python
70 lines
2.4 KiB
Python
"""Непрозрачный keyset-курсор: ключ `(created_at, id)` плюс область списка.
|
|
|
|
Формат — base64url без padding от JSON
|
|
`{"v": 1, "s": <область>, "t": <created_at>, "i": <id>}`. Область
|
|
привязывает курсор к конкретному списку: курсор чужого чата или списка
|
|
чатов другого пользователя не разбирается.
|
|
"""
|
|
|
|
import base64
|
|
import binascii
|
|
import json
|
|
from datetime import datetime
|
|
from uuid import UUID
|
|
|
|
from src.utils.utc import from_rfc3339, to_rfc3339
|
|
|
|
CURSOR_VERSION = 1
|
|
|
|
type CursorKey = tuple[datetime, UUID]
|
|
|
|
|
|
class CursorError(ValueError):
|
|
"""Курсор повреждён, другой версии или относится к другому списку."""
|
|
|
|
|
|
def chat_messages_scope(chat_id: UUID) -> str:
|
|
"""Область истории чата."""
|
|
return f"chat:{chat_id}"
|
|
|
|
|
|
def user_chats_scope(user_id: UUID) -> str:
|
|
"""Область списка чатов пользователя."""
|
|
return f"user-chats:{user_id}"
|
|
|
|
|
|
def encode_cursor(*, scope: str, created_at: datetime, item_id: UUID) -> str:
|
|
payload = {
|
|
"v": CURSOR_VERSION,
|
|
"s": scope,
|
|
"t": to_rfc3339(created_at),
|
|
"i": str(item_id),
|
|
}
|
|
raw = json.dumps(payload, separators=(",", ":")).encode()
|
|
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
|
|
|
|
|
def decode_cursor(cursor: str, *, scope: str) -> CursorKey:
|
|
"""Ключ последнего элемента предыдущей страницы.
|
|
|
|
Бросает `CursorError`, если курсор не разбирается, другой версии или
|
|
выдан для другой области.
|
|
"""
|
|
try:
|
|
padded = cursor + "=" * (-len(cursor) % 4)
|
|
payload = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")))
|
|
except (ValueError, UnicodeError, binascii.Error) as e:
|
|
raise CursorError("malformed cursor") from e
|
|
|
|
if not isinstance(payload, dict):
|
|
raise CursorError("malformed cursor")
|
|
if payload.get("v") != CURSOR_VERSION:
|
|
raise CursorError("unsupported cursor version")
|
|
if payload.get("s") != scope:
|
|
raise CursorError("cursor belongs to another list")
|
|
|
|
try:
|
|
return from_rfc3339(payload["t"]), UUID(payload["i"])
|
|
except (KeyError, TypeError, ValueError) as e:
|
|
raise CursorError("malformed cursor") from e
|