ЛР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:
@@ -0,0 +1,18 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Annotated
|
||||
|
||||
from pydantic import PlainSerializer
|
||||
|
||||
TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
|
||||
|
||||
|
||||
def format_utc(value: datetime) -> str:
|
||||
return value.astimezone(timezone.utc).strftime(TIME_FORMAT)
|
||||
|
||||
|
||||
def parse_utc(value: str) -> datetime:
|
||||
return datetime.strptime(value, TIME_FORMAT).replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
# datetime, который в JSON превращается в строку вида 2026-09-01T12:00:00.123456Z.
|
||||
UtcDatetime = Annotated[datetime, PlainSerializer(format_utc, return_type=str)]
|
||||
@@ -0,0 +1,50 @@
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy.exc import TimeoutError as PoolTimeoutError
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
from core.logger import logger
|
||||
from schemas.error_schemas import ErrorBody, ErrorResponse
|
||||
|
||||
ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
500: "internal_error",
|
||||
503: "unavailable",
|
||||
}
|
||||
|
||||
|
||||
def error_response(request: Request, status_code: int, message: str,
|
||||
headers: dict[str, str] | None = None) -> JSONResponse:
|
||||
code = ERROR_CODES.get(status_code, "internal_error" if status_code >= 500 else "invalid_request")
|
||||
body = ErrorResponse(error=ErrorBody(code=code, message=message, request_id=request.state.request_id))
|
||||
return JSONResponse(status_code=status_code, content=body.model_dump(), headers=headers)
|
||||
|
||||
|
||||
def http_error_handler(request: Request, exc: HTTPException) -> JSONResponse:
|
||||
message = exc.detail if isinstance(exc.detail, str) and exc.detail else "Ошибка запроса"
|
||||
return error_response(request, exc.status_code, message, headers=exc.headers)
|
||||
|
||||
|
||||
def validation_error_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||
return error_response(request, 400, "Неверный запрос")
|
||||
|
||||
|
||||
# БД недоступна, statement_timeout или пул исчерпан -> 503 без подробностей.
|
||||
def database_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
logger.warning(f"Ошибка базы данных: {type(exc).__name__} request_id={request.state.request_id}")
|
||||
return error_response(request, 503, "База данных недоступна")
|
||||
|
||||
|
||||
def register_error_handlers(app: FastAPI):
|
||||
app.add_exception_handler(HTTPException, http_error_handler)
|
||||
app.add_exception_handler(RequestValidationError, validation_error_handler)
|
||||
app.add_exception_handler(OperationalError, database_error_handler)
|
||||
app.add_exception_handler(PoolTimeoutError, database_error_handler)
|
||||
@@ -0,0 +1,13 @@
|
||||
import threading
|
||||
|
||||
# Флаг живёт в отдельном модуле: main.py запускается как __main__ и ещё раз импортируется как "main",
|
||||
# а общее состояние должно быть одно.
|
||||
_draining = threading.Event()
|
||||
|
||||
|
||||
def start_draining() -> None:
|
||||
_draining.set()
|
||||
|
||||
|
||||
def is_draining() -> bool:
|
||||
return _draining.is_set()
|
||||
@@ -0,0 +1,30 @@
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from fastapi import Request
|
||||
|
||||
from core.config import settings
|
||||
from core.logger import logger
|
||||
from utils.errors import error_response
|
||||
|
||||
|
||||
async def request_id_middleware(request: Request, call_next):
|
||||
request.state.request_id = str(uuid.uuid4())
|
||||
start = time.monotonic()
|
||||
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
# Подробности пишем только в лог сервера, клиенту — общий текст.
|
||||
logger.exception(f"Непредвиденная ошибка request_id={request.state.request_id}")
|
||||
response = error_response(request, 500, "Внутренняя ошибка сервера")
|
||||
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
# Какая реплика ответила (стабильно на всё время жизни процесса).
|
||||
response.headers["X-Instance-Id"] = settings.run.instance_id
|
||||
|
||||
# Тело запроса не логируем, чтобы текст сообщений не попадал в логи.
|
||||
duration_ms = (time.monotonic() - start) * 1000
|
||||
logger.info(f"{request.method} {request.url.path} {response.status_code} "
|
||||
f"{duration_ms:.1f}ms request_id={request.state.request_id} instance={settings.run.instance_id}")
|
||||
return response
|
||||
@@ -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
|
||||
@@ -0,0 +1,65 @@
|
||||
import hashlib
|
||||
import secrets
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import jwt
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
|
||||
from core.config import settings
|
||||
|
||||
# Argon2id: 64 MiB, 3 прохода (как по умолчанию), но 1 поток вместо 4: реплика ограничена 1 CPU,
|
||||
# и 4 потока только ждали бы квоту. Параметры записаны в самом хеше, старые хеши проверяются как раньше.
|
||||
password_hasher = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=1)
|
||||
|
||||
# Проверяется, когда пользователя нет: время ответа такое же, как при неверном пароле.
|
||||
DUMMY_PASSWORD_HASH = password_hasher.hash(secrets.token_urlsafe(16))
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return password_hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash: str | None, password: str) -> bool:
|
||||
try:
|
||||
password_hasher.verify(password_hash or DUMMY_PASSWORD_HASH, password)
|
||||
return password_hash is not None
|
||||
except (VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
JWT_SECRET_KEY = settings.jwt.read_secret_key()
|
||||
|
||||
|
||||
def create_access_token(user_id: uuid.UUID) -> tuple[str, datetime, datetime]:
|
||||
"""Возвращает (токен, время выдачи, время истечения)."""
|
||||
# Целые секунды, чтобы expires_at совпадал с exp в токене.
|
||||
issued_at = datetime.now(timezone.utc).replace(microsecond=0)
|
||||
expires_at = issued_at + timedelta(seconds=settings.jwt.session_ttl_seconds)
|
||||
payload = {
|
||||
"sub": str(user_id),
|
||||
"iat": issued_at,
|
||||
"exp": expires_at,
|
||||
"jti": secrets.token_urlsafe(32), # 256 бит случайности, токен всегда уникален
|
||||
}
|
||||
token = jwt.encode(payload, JWT_SECRET_KEY, algorithm=settings.jwt.algorithm)
|
||||
return token, issued_at, expires_at
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> dict | None:
|
||||
"""None — подпись неверна, токен испорчен или истёк."""
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
JWT_SECRET_KEY,
|
||||
algorithms=[settings.jwt.algorithm], # явно, чтобы не принять alg=none
|
||||
options={"require": ["sub", "exp", "iat", "jti"]},
|
||||
)
|
||||
except jwt.InvalidTokenError:
|
||||
return None
|
||||
|
||||
|
||||
def token_hash(token: str) -> bytes:
|
||||
# В БД хранится только хеш токена.
|
||||
return hashlib.sha256(token.encode()).digest()
|
||||
Reference in New Issue
Block a user