Лаба 3: Nginx LB, 2 реплики API и общая идемпотентность (оценка 4)

Переиспользован стек lab2 (Postgres/Redis/Argon2id). Добавлены: Nginx
балансировщик перед api1/api2, общая идемпотентность POST-сообщений
(idempotency_keys + advisory-lock сериализация в Postgres), explicit
stop-one/restart hooks. make test/test-persistence/test-failover/validate
зелёные для обеих реплик; найдены и исправлены гонка миграций и гонка
рестарта Nginx/DNS — см. REPORT.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 00:35:53 +03:00
co-authored by Claude Sonnet 5
parent 0ab3a341aa
commit 2f1cf3afac
18 changed files with 1093 additions and 15 deletions
View File
+82
View File
@@ -0,0 +1,82 @@
"""PostgreSQL connection pool and versioned migration runner."""
import logging
from pathlib import Path
import asyncpg
logger = logging.getLogger("app.db")
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
_pool: asyncpg.Pool | None = None
async def init_pool(dsn: str) -> asyncpg.Pool:
global _pool
_pool = await asyncpg.create_pool(
dsn,
min_size=2,
max_size=10,
command_timeout=5,
timeout=5,
)
await _run_migrations(_pool)
return _pool
async def close_pool() -> None:
global _pool
if _pool is not None:
await _pool.close()
_pool = None
def pool() -> asyncpg.Pool:
if _pool is None:
raise RuntimeError("database pool is not initialized")
return _pool
MIGRATION_LOCK_KEY = 783451 # arbitrary advisory-lock id, serializes concurrent replicas
async def _run_migrations(p: asyncpg.Pool) -> None:
async with p.acquire() as conn:
# Multiple API replicas start together; an advisory lock keeps migrations
# from racing each other instead of letting all replicas apply SQL at once.
await conn.execute("SELECT pg_advisory_lock($1)", MIGRATION_LOCK_KEY)
try:
await _apply_migrations(conn)
finally:
await conn.execute("SELECT pg_advisory_unlock($1)", MIGRATION_LOCK_KEY)
async def _apply_migrations(conn: asyncpg.Connection) -> None:
await conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
"""
)
applied = {r["version"] for r in await conn.fetch("SELECT version FROM schema_migrations")}
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
if path.name in applied:
continue
sql = path.read_text(encoding="utf-8")
async with conn.transaction():
await conn.execute(sql)
await conn.execute(
"INSERT INTO schema_migrations (version) VALUES ($1)", path.name
)
logger.info("applied migration %s", path.name)
async def ping() -> bool:
try:
async with pool().acquire() as conn:
await conn.fetchval("SELECT 1")
return True
except Exception: # noqa: BLE001 - readiness probe, any failure means not ready
return False
+29
View File
@@ -0,0 +1,29 @@
"""Canonical error envelope: {"error": {"code", "message", "request_id"}}."""
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str):
self.status = status
self.code = code
self.message = message
super().__init__(message)
def bad_request(message: str) -> ApiError:
return ApiError(400, "invalid_request", message)
def unauthorized(message: str = "authentication required") -> ApiError:
return ApiError(401, "unauthorized", message)
def not_found(message: str = "not found") -> ApiError:
return ApiError(404, "not_found", message)
def conflict(message: str) -> ApiError:
return ApiError(409, "conflict", message)
def unavailable(message: str = "dependency unavailable") -> ApiError:
return ApiError(503, "unavailable", message)
+89
View File
@@ -0,0 +1,89 @@
"""Shared (cross-replica) idempotency for POST message, scoped to (user, method, path, key)."""
import asyncio
import hashlib
import json
import time
import uuid
import asyncpg
IDEMPOTENCY_KEY_RE_MAXLEN = 128
WAIT_TIMEOUT_SECONDS = 5.0
POLL_INTERVAL_SECONDS = 0.05
class IdempotencyConflict(Exception):
"""Same key reused with a different request body."""
def request_hash(body: dict) -> str:
canonical = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
async def run_once(
conn: asyncpg.Connection,
user_id: uuid.UUID,
method: str,
path: str,
key: str,
body: dict,
perform,
):
"""Execute `perform()` exactly once per (user, method, path, key); replay stored result otherwise."""
digest = request_hash(body)
inserted = await conn.fetchrow(
"""
INSERT INTO idempotency_keys (user_id, method, path, idem_key, request_hash)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (user_id, method, path, idem_key) DO NOTHING
RETURNING idem_key
""",
user_id, method, path, key, digest,
)
if inserted is None:
existing = await conn.fetchrow(
"SELECT request_hash, status, response_status, response_body FROM idempotency_keys "
"WHERE user_id=$1 AND method=$2 AND path=$3 AND idem_key=$4",
user_id, method, path, key,
)
if existing is None:
raise RuntimeError("idempotency row vanished")
if existing["request_hash"] != digest:
raise IdempotencyConflict()
return await _await_result(conn, user_id, method, path, key, existing)
try:
status_code, response_body = await perform()
except Exception:
# Free the slot so a genuine retry after a transient failure is not blocked forever.
await conn.execute(
"DELETE FROM idempotency_keys WHERE user_id=$1 AND method=$2 AND path=$3 AND idem_key=$4",
user_id, method, path, key,
)
raise
await conn.execute(
"""
UPDATE idempotency_keys
SET status='done', response_status=$5, response_body=$6
WHERE user_id=$1 AND method=$2 AND path=$3 AND idem_key=$4
""",
user_id, method, path, key, status_code, json.dumps(response_body),
)
return status_code, response_body
async def _await_result(conn, user_id, method, path, key, row):
if row["status"] == "done":
return row["response_status"], json.loads(row["response_body"])
deadline = time.monotonic() + WAIT_TIMEOUT_SECONDS
while time.monotonic() < deadline:
await asyncio.sleep(POLL_INTERVAL_SECONDS)
current = await conn.fetchrow(
"SELECT status, response_status, response_body FROM idempotency_keys "
"WHERE user_id=$1 AND method=$2 AND path=$3 AND idem_key=$4",
user_id, method, path, key,
)
if current and current["status"] == "done":
return current["response_status"], json.loads(current["response_body"])
raise TimeoutError("concurrent idempotent request did not finish in time")
+516
View File
@@ -0,0 +1,516 @@
"""Messenger API — lab 2: PostgreSQL persistence + Redis/Valkey sessions."""
import base64
import binascii
import json
import os
import re
import socket
import uuid
from datetime import datetime, timezone
import asyncpg
from fastapi import FastAPI, Header, Request
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from . import db, sessions
from . import idempotency
from .errors import ApiError, bad_request, conflict, not_found, unauthorized, unavailable
from .security import hash_password, verify_password
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
INSTANCE_ID = os.environ.get("INSTANCE_ID") or f"{socket.gethostname()}-{os.getpid()}"
app = FastAPI(title="MTUSI Messenger — lab 2")
# ---------------------------------------------------------------------------
# Request/response plumbing: request id, instance id, canonical error shape.
# ---------------------------------------------------------------------------
@app.middleware("http")
async def tagging_middleware(request: Request, call_next):
request_id = uuid.uuid4().hex
request.state.request_id = request_id
try:
response = await call_next(request)
except ApiError as exc:
response = _error_response(exc, request_id)
except Exception: # noqa: BLE001 - never leak internals
response = _error_response(ApiError(500, "internal_error", "internal error"), request_id)
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
def _error_response(exc: ApiError, request_id: str) -> JSONResponse:
headers = {}
if exc.status == 401:
path = "/api/v1/auth/sessions"
scheme = 'Basic realm="messenger", charset="UTF-8"' if _is_login_path(exc) else 'Bearer realm="messenger"'
headers["WWW-Authenticate"] = scheme
return JSONResponse(
status_code=exc.status,
content={"error": {"code": exc.code, "message": exc.message, "request_id": request_id}},
headers=headers,
)
def _is_login_path(exc: ApiError) -> bool:
return getattr(exc, "login_path", False)
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
return _error_response(exc, getattr(request.state, "request_id", uuid.uuid4().hex))
def iso(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def user_json(record) -> dict:
return {
"id": str(record["id"]),
"username": record["username"],
"display_name": record["display_name"],
"created_at": iso(record["created_at"]),
}
def chat_json(record, member_ids: list[uuid.UUID]) -> dict:
return {
"id": str(record["id"]),
"title": record["title"],
"member_ids": [str(m) for m in member_ids],
"created_at": iso(record["created_at"]),
}
def message_json(record) -> dict:
return {
"id": str(record["id"]),
"chat_id": str(record["chat_id"]),
"sender_id": str(record["sender_id"]),
"text": record["text"],
"created_at": iso(record["created_at"]),
}
# ---------------------------------------------------------------------------
# Cursors: opaque base64url(json) of the keyset tuple, scoped per resource.
# ---------------------------------------------------------------------------
def encode_cursor(payload: dict) -> str:
raw = json.dumps(payload, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def decode_cursor(value: str) -> dict:
try:
padded = value + "=" * (-len(value) % 4)
raw = base64.urlsafe_b64decode(padded.encode())
return json.loads(raw)
except (binascii.Error, ValueError, UnicodeDecodeError):
raise bad_request("malformed cursor")
# ---------------------------------------------------------------------------
# Auth: Basic only on POST /auth/sessions, Bearer everywhere else protected.
# ---------------------------------------------------------------------------
async def require_bearer(authorization: str | None) -> asyncpg.Record:
if not authorization or not authorization.startswith("Bearer "):
raise unauthorized()
token = authorization[len("Bearer "):].strip()
if not token:
raise unauthorized()
try:
user_id = await sessions.resolve(token)
except Exception: # noqa: BLE001 - dependency failure must not grant access
raise unavailable("session store unavailable")
if user_id is None:
raise unauthorized()
async with db.pool().acquire() as conn:
record = await conn.fetchrow("SELECT * FROM users WHERE id=$1", user_id)
if record is None:
raise unauthorized()
return record
def parse_basic(authorization: str | None) -> tuple[str, str]:
err = ApiError(401, "unauthorized", "Basic credentials required")
err.login_path = True
if not authorization or not authorization.startswith("Basic "):
raise err
try:
decoded = base64.b64decode(authorization[len("Basic "):].strip()).decode("utf-8")
except (binascii.Error, UnicodeDecodeError):
raise err
if ":" not in decoded:
raise err
username, password = decoded.split(":", 1)
return username, password
# ---------------------------------------------------------------------------
# Request bodies (additionalProperties: false in the contract -> extra="forbid").
# ---------------------------------------------------------------------------
class CreateUser(BaseModel):
model_config = ConfigDict(extra="forbid")
username: str
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
class CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(min_length=1, max_length=100)
member_ids: list[str] = Field(min_length=1, max_length=100)
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(max_length=4000)
async def parse_body(request: Request, model):
try:
raw = await request.json()
except json.JSONDecodeError:
raise bad_request("malformed JSON")
try:
return model.model_validate(raw)
except ValidationError as exc:
raise bad_request(str(exc.errors()[0]["msg"]) if exc.errors() else "invalid body")
# ---------------------------------------------------------------------------
# Health
# ---------------------------------------------------------------------------
@app.get("/health/live")
async def health_live():
return {"status": "ok"}
@app.get("/health/ready")
async def health_ready():
if await db.ping() and await sessions.ping():
return {"status": "ok"}
raise unavailable("database or session store not ready")
# ---------------------------------------------------------------------------
# Users
# ---------------------------------------------------------------------------
@app.post("/api/v1/users", status_code=201)
async def register_user(request: Request):
body = await parse_body(request, CreateUser)
if not USERNAME_RE.match(body.username):
raise bad_request("username must match ^[a-z0-9_]{3,32}$")
if not body.display_name.strip():
raise bad_request("display_name must not be blank")
password_hash = hash_password(body.password)
try:
async with db.pool().acquire() as conn:
record = await conn.fetchrow(
"""
INSERT INTO users (username, display_name, password_hash)
VALUES ($1, $2, $3)
RETURNING id, username, display_name, created_at
""",
body.username,
body.display_name,
password_hash,
)
except asyncpg.UniqueViolationError:
raise conflict("username already taken")
return JSONResponse(status_code=201, content=user_json(record))
@app.get("/api/v1/users/me")
async def current_user(authorization: str | None = Header(default=None)):
record = await require_bearer(authorization)
return user_json(record)
# ---------------------------------------------------------------------------
# Sessions
# ---------------------------------------------------------------------------
@app.post("/api/v1/auth/sessions", status_code=201)
async def create_session(authorization: str | None = Header(default=None)):
username, password = parse_basic(authorization)
async with db.pool().acquire() as conn:
record = await conn.fetchrow("SELECT * FROM users WHERE username=$1", username)
err = ApiError(401, "unauthorized", "invalid credentials")
err.login_path = True
if record is None or not verify_password(password, record["password_hash"]):
raise err
try:
token, expires_at = await sessions.create(record["id"])
except Exception: # noqa: BLE001
raise unavailable("session store unavailable")
return JSONResponse(
status_code=201,
content={
"token": token,
"token_type": "Bearer",
"expires_at": iso(expires_at),
"user": user_json(record),
},
)
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def revoke_session(authorization: str | None = Header(default=None)):
await require_bearer(authorization) # validates the token is currently live
token = authorization[len("Bearer "):].strip()
try:
await sessions.revoke(token)
except Exception: # noqa: BLE001
raise unavailable("session store unavailable")
return Response(status_code=204)
# ---------------------------------------------------------------------------
# Chats
# ---------------------------------------------------------------------------
@app.post("/api/v1/chats", status_code=201)
async def create_chat(request: Request, authorization: str | None = Header(default=None)):
actor = await require_bearer(authorization)
body = await parse_body(request, CreateChat)
try:
member_ids = [uuid.UUID(m) for m in body.member_ids]
except ValueError:
raise bad_request("member_ids must be UUIDs")
if len(set(member_ids)) != len(member_ids):
raise bad_request("member_ids must not contain duplicates")
if actor["id"] not in member_ids:
raise bad_request("caller must be a member of the chat")
async with db.pool().acquire() as conn:
async with conn.transaction():
existing = await conn.fetch(
"SELECT id FROM users WHERE id = ANY($1::uuid[])", member_ids
)
if len(existing) != len(member_ids):
raise bad_request("unknown member in member_ids")
chat = await conn.fetchrow(
"INSERT INTO chats (title) VALUES ($1) RETURNING id, title, created_at",
body.title,
)
await conn.executemany(
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
[(chat["id"], m) for m in member_ids],
)
return JSONResponse(status_code=201, content=chat_json(chat, member_ids))
@app.get("/api/v1/chats")
async def list_chats(
authorization: str | None = Header(default=None),
limit: int = 50,
cursor: str | None = None,
):
actor = await require_bearer(authorization)
if not (1 <= limit <= 100):
raise bad_request("limit must be between 1 and 100")
after_created_at = after_id = None
if cursor:
payload = decode_cursor(cursor)
try:
after_created_at = datetime.fromisoformat(payload["created_at"])
after_id = uuid.UUID(payload["id"])
except (KeyError, ValueError):
raise bad_request("malformed cursor")
async with db.pool().acquire() as conn:
rows = await conn.fetch(
"""
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE cm.user_id = $1
AND ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3))
ORDER BY c.created_at ASC, c.id ASC
LIMIT $4
""",
actor["id"],
after_created_at,
after_id,
limit + 1,
)
has_more = len(rows) > limit
rows = rows[:limit]
items = []
for row in rows:
members = await conn.fetch("SELECT user_id FROM chat_members WHERE chat_id=$1", row["id"])
items.append(chat_json(row, [m["user_id"] for m in members]))
next_cursor = None
if has_more:
last = rows[-1]
next_cursor = encode_cursor({"created_at": iso(last["created_at"]), "id": str(last["id"])})
return {"items": items, "next_cursor": next_cursor}
async def _load_chat_if_member(conn, chat_id: uuid.UUID, user_id: uuid.UUID):
chat = await conn.fetchrow("SELECT id, title, created_at FROM chats WHERE id=$1", chat_id)
if chat is None:
raise not_found("chat not found")
membership = await conn.fetchrow(
"SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2", chat_id, user_id
)
if membership is None:
raise not_found("chat not found")
return chat
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, authorization: str | None = Header(default=None)):
actor = await require_bearer(authorization)
try:
chat_uuid = uuid.UUID(chat_id)
except ValueError:
raise bad_request("chat_id must be a UUID")
async with db.pool().acquire() as conn:
chat = await _load_chat_if_member(conn, chat_uuid, actor["id"])
members = await conn.fetch("SELECT user_id FROM chat_members WHERE chat_id=$1", chat_uuid)
return chat_json(chat, [m["user_id"] for m in members])
# ---------------------------------------------------------------------------
# Messages
# ---------------------------------------------------------------------------
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def create_message(
chat_id: str,
request: Request,
authorization: str | None = Header(default=None),
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"),
):
# Session/access are re-checked on every call, including idempotent replays.
actor = await require_bearer(authorization)
try:
chat_uuid = uuid.UUID(chat_id)
except ValueError:
raise bad_request("chat_id must be a UUID")
if not idempotency_key or not IDEMPOTENCY_KEY_RE.match(idempotency_key):
raise bad_request("Idempotency-Key header is required and must match ^[A-Za-z0-9._:-]{1,128}$")
body = await parse_body(request, CreateMessage)
if not body.text.strip():
raise bad_request("text must not be blank")
async def perform():
record = await conn.fetchrow(
"""
INSERT INTO messages (chat_id, sender_id, text)
VALUES ($1, $2, $3)
RETURNING id, chat_id, sender_id, text, created_at
""",
chat_uuid,
actor["id"],
body.text,
)
return 201, message_json(record)
async with db.pool().acquire() as conn:
await _load_chat_if_member(conn, chat_uuid, actor["id"])
async with conn.transaction():
try:
status_code, payload = await idempotency.run_once(
conn,
actor["id"],
"POST",
request.url.path,
idempotency_key,
{"text": body.text},
perform,
)
except idempotency.IdempotencyConflict:
raise conflict("Idempotency-Key reused with a different request body")
return JSONResponse(status_code=status_code, content=payload)
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(
chat_id: str,
authorization: str | None = Header(default=None),
limit: int = 50,
cursor: str | None = None,
):
actor = await require_bearer(authorization)
try:
chat_uuid = uuid.UUID(chat_id)
except ValueError:
raise bad_request("chat_id must be a UUID")
if not (1 <= limit <= 100):
raise bad_request("limit must be between 1 and 100")
after_created_at = after_id = None
if cursor:
payload = decode_cursor(cursor)
if payload.get("chat_id") != chat_id:
raise bad_request("cursor does not belong to this chat")
try:
after_created_at = datetime.fromisoformat(payload["created_at"])
after_id = uuid.UUID(payload["id"])
except (KeyError, ValueError):
raise bad_request("malformed cursor")
async with db.pool().acquire() as conn:
await _load_chat_if_member(conn, chat_uuid, actor["id"])
rows = await conn.fetch(
"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1
AND ($2::timestamptz IS NULL OR (created_at, id) > ($2, $3))
ORDER BY created_at ASC, id ASC
LIMIT $4
""",
chat_uuid,
after_created_at,
after_id,
limit + 1,
)
has_more = len(rows) > limit
rows = rows[:limit]
items = [message_json(r) for r in rows]
next_cursor = None
if has_more:
last = rows[-1]
next_cursor = encode_cursor(
{"chat_id": chat_id, "created_at": iso(last["created_at"]), "id": str(last["id"])}
)
return {"items": items, "next_cursor": next_cursor}
# ---------------------------------------------------------------------------
# Lifecycle
# ---------------------------------------------------------------------------
@app.on_event("startup")
async def on_startup():
database_url = _read_secret("DATABASE_URL_FILE", "DATABASE_URL")
cache_url = _read_secret("CACHE_URL_FILE", "CACHE_URL")
await db.init_pool(database_url)
sessions.init(cache_url)
@app.on_event("shutdown")
async def on_shutdown():
await db.close_pool()
await sessions.close()
def _read_secret(file_env: str, inline_env: str) -> str:
path = os.environ.get(file_env)
if path and os.path.isfile(path):
return open(path, encoding="utf-8").read().strip()
value = os.environ.get(inline_env)
if not value:
raise RuntimeError(f"{file_env} or {inline_env} must be set")
return value
+16
View File
@@ -0,0 +1,16 @@
"""Password KDF (Argon2id) — never store or compare plaintext passwords."""
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError, InvalidHashError
_hasher = PasswordHasher()
def hash_password(password: str) -> str:
return _hasher.hash(password)
def verify_password(password: str, password_hash: str) -> bool:
try:
return _hasher.verify(password_hash, password)
except (VerifyMismatchError, InvalidHashError):
return False
+54
View File
@@ -0,0 +1,54 @@
"""Opaque Bearer sessions backed by Redis/Valkey, TTL-bound, AOF-persistent."""
import json
import os
import secrets
import uuid
from datetime import datetime, timedelta, timezone
import redis.asyncio as redis
_client: redis.Redis | None = None
TTL_SECONDS = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
def init(url: str) -> None:
global _client
_client = redis.from_url(url, decode_responses=True, socket_timeout=3, socket_connect_timeout=3)
async def close() -> None:
if _client is not None:
await _client.close()
def client() -> redis.Redis:
if _client is None:
raise RuntimeError("session store is not initialized")
return _client
async def ping() -> bool:
try:
return bool(await client().ping())
except Exception: # noqa: BLE001 - readiness probe
return False
async def create(user_id: uuid.UUID) -> tuple[str, datetime]:
token = secrets.token_urlsafe(32) # 256 bits of entropy, opaque and non-guessable
expires_at = datetime.now(timezone.utc) + timedelta(seconds=TTL_SECONDS)
payload = json.dumps({"user_id": str(user_id), "expires_at": expires_at.isoformat()})
await client().set(f"session:{token}", payload, ex=TTL_SECONDS)
return token, expires_at
async def resolve(token: str) -> uuid.UUID | None:
raw = await client().get(f"session:{token}")
if raw is None:
return None
data = json.loads(raw)
return uuid.UUID(data["user_id"])
async def revoke(token: str) -> None:
await client().delete(f"session:{token}")