Files
mtusi2026lab3/src/pagination.py
T
Tmribob e084a29303 Реализация лабораторной 3: балансировка, отказ API-реплики, idempotency
- 2 API-реплики (api-1, api-2) с уникальным INSTANCE_ID
- Nginx load balancer с health-check и failover
- PostgreSQL источник истины, Valkey кэш сессий
- Idempotency-Key в заголовке, replay возвращает исходное сообщение
- X-Instance-Id в каждом ответе для идентификации реплики
- /version и /info эндпоинты
- Housekeeping-loop для очистки истёкших сессий и ключей
- stop-one.sh/cmd для failover-теста, restart.sh/cmd для persistence
- Исправлены импорты config/models/api/store/sessions
- Добавлены миграции 004 (idempotency), 005 (indexes), 006 (message_id)
- Отчёт с доказательствами критериев уровня 3 и 4
- Все тесты проходят: smoke, 26 student tests, failover, persistence, degradation
2026-10-30 21:14:37 +03:00

85 lines
2.8 KiB
Python

"""Opaque, resource-bound keyset cursors, timestamp formatting and page shaping."""
from __future__ import annotations
import base64
import binascii
import json
import uuid
from datetime import datetime, timezone
from typing import Any
from .errors import ApiProblem
def format_timestamp(value: datetime) -> str:
"""RFC 3339 UTC with microseconds and a trailing Z, as the contract requires."""
return (
value.astimezone(timezone.utc)
.isoformat(timespec="microseconds")
.replace("+00:00", "Z")
)
def parse_timestamp(value: str) -> datetime:
"""Parse an RFC 3339 timestamp from a cursor; reject anything else."""
candidate = value[:-1] + "+00:00" if value.endswith("Z") else value
parsed = datetime.fromisoformat(candidate)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(timezone.utc)
def encode_cursor(resource: str, created_at: datetime, record_id: str) -> str:
payload = json.dumps(
{
"resource": resource,
"created_at": format_timestamp(created_at),
"id": record_id,
},
separators=(",", ":"),
sort_keys=True,
).encode("utf-8")
return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")
def decode_cursor(value: str, resource: str) -> tuple[datetime, uuid.UUID]:
"""Decode a cursor and bind it to the resource it was issued for."""
try:
padding = "=" * (-len(value) % 4)
raw = base64.b64decode(value + padding, altchars=b"-_", validate=True)
payload: Any = json.loads(raw.decode("utf-8"))
if not isinstance(payload, dict) or set(payload) != {
"resource",
"created_at",
"id",
}:
raise ValueError("unexpected cursor payload")
if payload["resource"] != resource:
raise ValueError("cursor belongs to another resource")
created_at = payload["created_at"]
record_id = payload["id"]
if not isinstance(created_at, str) or not isinstance(record_id, str):
raise ValueError("cursor fields have wrong types")
return parse_timestamp(created_at), uuid.UUID(record_id)
except (
ValueError,
TypeError,
UnicodeError,
binascii.Error,
json.JSONDecodeError,
):
raise ApiProblem(400, "invalid_request", "Cursor is invalid") from None
def build_page(items: list[dict[str, Any]], resource: str, limit: int) -> dict[str, Any]:
"""Shape a limit+1 storage slice into the public page and its next cursor."""
page = items[:limit]
next_cursor = None
if len(items) > limit and page:
last = page[-1]
next_cursor = encode_cursor(
resource, parse_timestamp(last["created_at"]), last["id"]
)
return {"items": page, "next_cursor": next_cursor}