Files
mtusi2026lab3/app/utils/pagination.py
T
vest1ter cde3374d8a ЛР3: балансировка HAProxy, 2 реплики API, идемпотентность, отказоустойчивость (на 4)
- X-Instance-Id в каждом ответе; обязательный Idempotency-Key, таблица idempotency_keys
  (миграция 0002, одна транзакция, конкурентные повторы через уникальный индекс)
- graceful shutdown: SIGTERM -> ready=503 -> drain 3 с -> закрытие порта
- compose: lb (HAProxy) + api x2 без портов + разовый migrate + postgres, лимиты CPU/RAM
- хуки stop-one/restart/restore-replicas, scripts/experiments.py (failover, idempotency, rolling)
- свои тесты: 44 (13 новых); evidence: smoke, pytest, persistence, failover, эксперименты
2026-10-29 10:58:17 +03:00

36 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import base64
import json
import uuid
from datetime import datetime
from fastapi import HTTPException
from utils.dates import format_utc, parse_utc
# Позиция в списке: (created_at, id) последнего выданного элемента.
Position = tuple[datetime, uuid.UUID]
def make_cursor(scope: str, created_at: datetime, item_id: uuid.UUID) -> str:
data = json.dumps({"scope": scope, "created_at": format_utc(created_at), "id": str(item_id)})
return base64.urlsafe_b64encode(data.encode()).decode()
def read_cursor(scope: str, cursor: str | None) -> Position | None:
if cursor is None:
return None
try:
data = json.loads(base64.urlsafe_b64decode(cursor.encode()))
if data["scope"] != scope:
raise ValueError("cursor from another resource")
return parse_utc(data["created_at"]), uuid.UUID(data["id"])
except Exception:
raise HTTPException(status_code=400, detail="Неверный cursor")
def split_page(rows: list, limit: int, scope: str) -> tuple[list, str | None]:
"""rows получены с LIMIT limit + 1: лишняя строка значит, что есть следующая страница."""
page = rows[:limit]
next_cursor = make_cursor(scope, page[-1].created_at, page[-1].id) if len(rows) > limit else None
return page, next_cursor