ЛР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, эксперименты
This commit is contained in:
2026-10-29 10:58:17 +03:00
parent 0ab3a341aa
commit cde3374d8a
74 changed files with 6231 additions and 25 deletions
+35
View File
@@ -0,0 +1,35 @@
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