feat: ЛР3 - Nginx балансировка, идемпотентность сообщений и failover

This commit is contained in:
Ильяс
2026-10-30 12:17:01 +03:00
parent df42648939
commit 786bb2077f
27 changed files with 943 additions and 70 deletions
+3
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import os
import socket
from pathlib import Path
@@ -19,6 +20,8 @@ LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
SESSION_TTL_SECONDS: int = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
SESSION_STORE: str = os.getenv("SESSION_STORE", "redis").lower()
INSTANCE_ID: str = os.getenv("INSTANCE_ID") or socket.gethostname() or "api-1"
IDEMPOTENCY_TTL_SECONDS: int = int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400"))
DATABASE_URL: str = _get_val(
"DATABASE_URL",
+6 -1
View File
@@ -9,6 +9,7 @@ from fastapi.responses import JSONResponse
import redis.exceptions
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.config import INSTANCE_ID
from app.schemas import ErrorCode, ErrorDetail, ErrorResponse
@@ -56,7 +57,11 @@ def make_error_response(
payload = ErrorResponse(
error=ErrorDetail(code=code, message=message, request_id=request_id)
).model_dump()
resp_headers = {"X-Request-Id": request_id, "Content-Type": "application/json"}
resp_headers = {
"X-Request-Id": request_id,
"X-Instance-Id": INSTANCE_ID,
"Content-Type": "application/json",
}
if headers:
resp_headers.update(headers)
return JSONResponse(
+1 -1
View File
@@ -32,7 +32,7 @@ async def lifespan(app: FastAPI):
app = FastAPI(
title="highload-messenger",
version="1.2.0",
version="1.3.0",
docs_url="/docs",
redoc_url=None,
lifespan=lifespan,
+3
View File
@@ -9,6 +9,8 @@ from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoin
from starlette.requests import Request
from starlette.responses import Response
from app.config import INSTANCE_ID
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
@@ -60,6 +62,7 @@ class RequestIdAndLoggingMiddleware(BaseHTTPMiddleware):
duration_ms = (time.monotonic() - start_time) * 1000
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
# лог без логирования тела запросов и текстов сообщений
logger.info(
+10 -3
View File
@@ -1,8 +1,7 @@
from __future__ import annotations
import re
from uuid import UUID
from fastapi import APIRouter, Depends, Query, status
from fastapi import APIRouter, Depends, Header, Query, status
from app.dependencies import get_current_user
from app.schemas import (
@@ -15,6 +14,8 @@ from app.storage import InvalidRequestError, storage
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
IDEMPOTENCY_KEY_REGEX = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
def validate_uuid(value: str, field_name: str = "id") -> str:
try:
@@ -32,14 +33,20 @@ def validate_uuid(value: str, field_name: str = "id") -> str:
async def create_message(
chat_id: str,
body: CreateMessageRequest,
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"),
current_user: UserResponse = Depends(get_current_user),
) -> MessageResponse:
"""Отправка сообщения в чат."""
if not idempotency_key or not IDEMPOTENCY_KEY_REGEX.match(idempotency_key):
raise InvalidRequestError(
"Заголовок 'Idempotency-Key' обязателен и должен соответствовать шаблону ^[A-Za-z0-9._:-]{1,128}$"
)
valid_id = validate_uuid(chat_id, "chat_id")
msg = await storage.send_message(
caller_id=current_user.id,
chat_id=valid_id,
text=body.text,
idempotency_key=idempotency_key,
)
return msg
+3 -3
View File
@@ -46,7 +46,7 @@ class HealthResponse(BaseModel):
class CreateUserRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
model_config = ConfigDict(extra="forbid", strict=True)
username: str = Field(min_length=3, max_length=32)
display_name: str = Field(min_length=1, max_length=100)
@@ -93,7 +93,7 @@ class SessionResponse(BaseModel):
class CreateChatRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
model_config = ConfigDict(extra="forbid", strict=True)
title: str = Field(min_length=1, max_length=100)
member_ids: list[str] = Field(min_length=1, max_length=100)
@@ -135,7 +135,7 @@ class ChatPageResponse(BaseModel):
class CreateMessageRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
model_config = ConfigDict(extra="forbid", strict=True)
text: str = Field(min_length=1, max_length=4000)
+101 -29
View File
@@ -2,6 +2,7 @@ import asyncio
import base64
from contextlib import asynccontextmanager
import datetime as dt
import hashlib
import json
import logging
import uuid
@@ -72,10 +73,10 @@ class PostgresStorage:
self.redis_client: redis.Redis | None = None
@asynccontextmanager
async def acquire_conn(self, timeout: float = 2.0):
async def acquire_conn(self, timeout: float = 5.0):
if self.pg_pool is None:
raise asyncpg.InterfaceError("Пул подключений к PostgreSQL не инициализирован")
async with asyncio.timeout(4.0):
async with asyncio.timeout(10.0):
async with self.pg_pool.acquire(timeout=timeout) as conn:
yield conn
@@ -85,8 +86,8 @@ class PostgresStorage:
DATABASE_URL,
min_size=2,
max_size=20,
command_timeout=2.0,
timeout=2.0,
command_timeout=5.0,
timeout=5.0,
)
logger.info("Подключение к Redis: %s", CACHE_URL.split("@")[-1])
@@ -97,18 +98,6 @@ class PostgresStorage:
socket_timeout=3.0,
)
try:
async with self.acquire_conn() as conn:
col_type = await conn.fetchval(
"SELECT data_type FROM information_schema.columns WHERE table_name = 'messages' AND column_name = 'text'"
)
if col_type in ("text", "character varying"):
await conn.execute(
"ALTER TABLE messages ALTER COLUMN text TYPE BYTEA USING text::bytea"
)
except Exception as exc:
logger.warning("Не удалось проверить/обновить схему messages.text: %s", exc)
async def disconnect(self) -> None:
if self.pg_pool:
await self.pg_pool.close()
@@ -136,7 +125,7 @@ class PostgresStorage:
) -> UserResponse:
user_id = uuid.uuid4()
now = dt.datetime.now(dt.timezone.utc)
pwd_hash = hash_password(password)
pwd_hash = await asyncio.to_thread(hash_password, password)
try:
async with self.acquire_conn() as conn:
@@ -177,7 +166,8 @@ class PostgresStorage:
if not row:
return None
if not verify_password(row["password_hash"], password):
is_valid = await asyncio.to_thread(verify_password, row["password_hash"], password)
if not is_valid:
return None
return UserResponse(
@@ -417,8 +407,13 @@ class PostgresStorage:
# ------------------ Сообщения ------------------
@staticmethod
def compute_request_hash(text: str) -> str:
canonical = json.dumps({"text": text}, sort_keys=True, ensure_ascii=False)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
async def send_message(
self, caller_id: str, chat_id: str, text: str
self, caller_id: str, chat_id: str, text: str, idempotency_key: str
) -> MessageResponse:
try:
cid = uuid.UUID(chat_id)
@@ -426,9 +421,7 @@ class PostgresStorage:
except ValueError:
raise NotFoundError("Чат не найден")
msg_id = uuid.uuid4()
now = dt.datetime.now(dt.timezone.utc)
text_bytes = text.encode("utf-8")
req_hash = self.compute_request_hash(text)
async with self.acquire_conn() as conn:
is_member = await conn.fetchval(
@@ -439,17 +432,96 @@ class PostgresStorage:
if not is_member:
raise NotFoundError("Чат не найден")
await conn.execute(
# 1. Проверяем, обрабатывался ли уже этот idempotency_key
existing = await conn.fetchrow(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1, $2, $3, $4, $5)
SELECT ik.message_id, ik.request_hash, m.text, m.created_at AS msg_created_at
FROM idempotency_keys ik
JOIN messages m ON m.id = ik.message_id
WHERE ik.user_id = $1 AND ik.chat_id = $2 AND ik.idempotency_key = $3
""",
msg_id,
cid,
c_caller,
text_bytes,
now,
cid,
idempotency_key,
)
if existing:
if existing["request_hash"] == req_hash:
raw_text = existing["text"]
msg_text = (
raw_text.decode("utf-8")
if isinstance(raw_text, (bytes, bytearray))
else str(raw_text)
)
return MessageResponse(
id=str(existing["message_id"]),
chat_id=chat_id,
sender_id=caller_id,
text=msg_text,
created_at=_format_dt(existing["msg_created_at"]),
)
else:
raise ConflictError("Ключ идемпотентности уже использован с другим телом запроса")
msg_id = uuid.uuid4()
now = dt.datetime.now(dt.timezone.utc)
text_bytes = text.encode("utf-8")
try:
async with conn.transaction():
await conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1, $2, $3, $4, $5)
""",
msg_id,
cid,
c_caller,
text_bytes,
now,
)
await conn.execute(
"""
INSERT INTO idempotency_keys (user_id, chat_id, idempotency_key, message_id, request_hash, created_at)
VALUES ($1, $2, $3, $4, $5, $6)
""",
c_caller,
cid,
idempotency_key,
msg_id,
req_hash,
now,
)
except asyncpg.UniqueViolationError:
# Конкурентная вставка из другой реплики выиграла гонку
winner = await conn.fetchrow(
"""
SELECT ik.message_id, ik.request_hash, m.text, m.created_at AS msg_created_at
FROM idempotency_keys ik
JOIN messages m ON m.id = ik.message_id
WHERE ik.user_id = $1 AND ik.chat_id = $2 AND ik.idempotency_key = $3
""",
c_caller,
cid,
idempotency_key,
)
if winner:
if winner["request_hash"] == req_hash:
raw_text = winner["text"]
msg_text = (
raw_text.decode("utf-8")
if isinstance(raw_text, (bytes, bytearray))
else str(raw_text)
)
return MessageResponse(
id=str(winner["message_id"]),
chat_id=chat_id,
sender_id=caller_id,
text=msg_text,
created_at=_format_dt(winner["msg_created_at"]),
)
else:
raise ConflictError("Ключ идемпотентности уже использован с другим телом запроса")
raise
return MessageResponse(
id=str(msg_id),