ЛР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
+108
View File
@@ -0,0 +1,108 @@
import base64
import os
import uuid
from pathlib import Path
# Отдельная тестовая база; задаётся до импорта приложения (настройки читаются при импорте).
TEST_DB_NAME = "messenger_test"
os.environ["APP_CONFIG__DB__NAME"] = TEST_DB_NAME
import pytest
from alembic import command
from alembic.config import Config
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, text
from core.db import build_url, engine
from main import app
APP_DIR = Path(__file__).resolve().parents[1] / "app"
PASSWORD = "Test-password-123"
@pytest.fixture(scope="session", autouse=True)
def test_database():
# CREATE DATABASE нельзя выполнить в транзакции, поэтому AUTOCOMMIT.
admin = create_engine(build_url().set(database="postgres"), isolation_level="AUTOCOMMIT")
with admin.connect() as connection:
exists = connection.scalar(text("SELECT 1 FROM pg_database WHERE datname = :name"), {"name": TEST_DB_NAME})
if not exists:
connection.execute(text(f'CREATE DATABASE "{TEST_DB_NAME}"'))
admin.dispose()
command.upgrade(Config(str(APP_DIR / "alembic.ini")), "head")
yield
engine.dispose()
@pytest.fixture(autouse=True)
def clean_database():
with engine.begin() as connection:
connection.execute(text("TRUNCATE users, sessions, chats, chat_members, messages, idempotency_keys"))
@pytest.fixture
def client():
return TestClient(app)
def basic(username, password):
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
return {"Authorization": "Basic " + credential}
def login(client, username, password=PASSWORD):
response = client.post("/api/v1/auth/sessions", headers=basic(username, password))
assert response.status_code == 201
return response.json()
def bearer(token):
return {"Authorization": "Bearer " + token}
def with_key(headers, key=None):
"""Добавить обязательный с lab3 Idempotency-Key (по умолчанию — новый уникальный)."""
return {**headers, "Idempotency-Key": key or uuid.uuid4().hex}
def create_user(client, username):
"""Регистрация + вход; заголовок авторизации — в поле "auth"."""
response = client.post("/api/v1/users", json={"username": username, "display_name": "Имя " + username,
"password": PASSWORD})
assert response.status_code == 201
user = response.json()
user["token"] = login(client, username)["token"]
user["auth"] = bearer(user["token"])
return user
@pytest.fixture
def alice(client):
return create_user(client, "alice")
@pytest.fixture
def bob(client):
return create_user(client, "bob")
@pytest.fixture
def eve(client):
return create_user(client, "eve")
@pytest.fixture
def chat(client, alice, bob):
"""Чат alice и bob; eve в него не входит."""
response = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "Тестовый чат", "member_ids": [alice["id"], bob["id"]]})
assert response.status_code == 201
return response.json()
def assert_error(response, status_code, code):
assert response.status_code == status_code
body = response.json()
assert body["error"]["code"] == code
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
+106
View File
@@ -0,0 +1,106 @@
import time
import jwt
from sqlalchemy import text
from conftest import PASSWORD, assert_error, basic, bearer, login
from core.config import settings
from core.db import engine
def assert_challenge(response, scheme):
assert response.headers["WWW-Authenticate"].startswith(scheme + ' realm="messenger"')
def test_login_returns_session(client, alice):
session = login(client, "alice")
assert session["token_type"] == "Bearer"
assert len(session["token"]) >= 32
assert session["expires_at"].endswith("Z")
assert session["user"]["id"] == alice["id"]
assert "password" not in session["user"] and "password_hash" not in session["user"]
assert login(client, "alice")["token"] != session["token"]
def test_jwt_payload_contains_sub_exp_jti(client, alice):
payload = jwt.decode(alice["token"], options={"verify_signature": False})
assert payload["sub"] == alice["id"]
assert payload["exp"] - payload["iat"] == settings.jwt.session_ttl_seconds
assert len(payload["jti"]) >= 43
def test_wrong_password_and_unknown_user_give_same_401(client, alice):
wrong = client.post("/api/v1/auth/sessions", headers=basic("alice", "Wrong-password-1"))
unknown = client.post("/api/v1/auth/sessions", headers=basic("nobody", PASSWORD))
for response in (wrong, unknown):
assert_error(response, 401, "unauthorized")
assert_challenge(response, "Basic")
assert 'charset="UTF-8"' in response.headers["WWW-Authenticate"]
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
def test_malformed_basic_returns_401(client):
for header in ("", "Basic", "Basic !!!not-base64!!!", "Bearer abc", "Basic " + "YWxpY2U="): # последний — без ':'
response = client.post("/api/v1/auth/sessions", headers={"Authorization": header})
assert_error(response, 401, "unauthorized")
assert_challenge(response, "Basic")
def test_login_with_body_returns_400_and_creates_no_session(client, alice):
with engine.connect() as connection:
before = connection.scalar(text("SELECT count(*) FROM sessions"))
for kwargs in ({"json": {"unexpected": True}}, {"json": {}}, {"content": b"x"}):
response = client.post("/api/v1/auth/sessions", headers=basic("alice", PASSWORD), **kwargs)
assert_error(response, 400, "invalid_request")
with engine.connect() as connection:
assert connection.scalar(text("SELECT count(*) FROM sessions")) == before
# Без тела вход по-прежнему работает.
assert login(client, "alice")["user"]["id"] == alice["id"]
def test_password_with_colon_and_unicode(client):
password = "пароль:с:двоеточиями 👋"
client.post("/api/v1/users", json={"username": "colon", "display_name": "C", "password": password})
assert login(client, "colon", password)["user"]["username"] == "colon"
def test_protected_endpoint_requires_bearer(client, alice):
cases = [{}, basic("alice", PASSWORD), bearer("not-a-jwt"), {"Authorization": "Bearer"}]
for headers in cases:
response = client.get("/api/v1/users/me", headers=headers)
assert_error(response, 401, "unauthorized")
assert_challenge(response, "Bearer")
def test_x_user_id_does_not_override_token(client, alice, eve):
response = client.get("/api/v1/users/me", headers={**alice["auth"], "X-User-Id": eve["id"]})
assert response.json()["id"] == alice["id"]
def test_forged_token_is_rejected(client, alice):
payload = jwt.decode(alice["token"], options={"verify_signature": False})
forged = jwt.encode(payload, "attacker-key-attacker-key-attacker-key!!", algorithm="HS256")
assert_error(client.get("/api/v1/users/me", headers=bearer(forged)), 401, "unauthorized")
unsigned = jwt.encode(payload, None, algorithm="none")
assert_error(client.get("/api/v1/users/me", headers=bearer(unsigned)), 401, "unauthorized")
def test_logout_revokes_only_current_token(client, alice):
second = login(client, "alice")["token"]
response = client.delete("/api/v1/auth/sessions/current", headers=alice["auth"])
assert response.status_code == 204
assert response.content == b""
assert_error(client.get("/api/v1/users/me", headers=alice["auth"]), 401, "unauthorized")
assert_error(client.delete("/api/v1/auth/sessions/current", headers=alice["auth"]), 401, "unauthorized")
# Другая сессия того же пользователя продолжает работать.
assert client.get("/api/v1/users/me", headers=bearer(second)).status_code == 200
def test_session_expires(client, alice, monkeypatch):
monkeypatch.setattr(settings.jwt, "session_ttl_seconds", 1)
token = login(client, "alice")["token"]
assert client.get("/api/v1/users/me", headers=bearer(token)).status_code == 200
time.sleep(2.1)
response = client.get("/api/v1/users/me", headers=bearer(token))
assert_error(response, 401, "unauthorized")
assert_challenge(response, "Bearer")
+54
View File
@@ -0,0 +1,54 @@
import uuid
from sqlalchemy import text
from conftest import assert_error, with_key
from core.db import engine
def count_rows(table):
with engine.connect() as connection:
return connection.scalar(text(f"SELECT count(*) FROM {table}"))
def test_unknown_member_returns_400_and_nothing_is_saved(client, alice):
response = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "С призраком", "member_ids": [alice["id"], str(uuid.uuid4())]})
assert_error(response, 400, "invalid_request")
assert count_rows("chats") == 0
assert count_rows("chat_members") == 0
def test_created_chat_is_stored_with_members(client, chat, alice, bob):
assert sorted(chat["member_ids"]) == sorted([alice["id"], bob["id"]])
assert count_rows("chats") == 1
assert count_rows("chat_members") == 2
again = client.get("/api/v1/chats/" + chat["id"], headers=bob["auth"]).json()
assert again == chat
def test_foreign_chat_returns_404(client, chat, eve):
headers = eve["auth"]
path = "/api/v1/chats/" + chat["id"]
assert_error(client.get(path, headers=headers), 404, "not_found")
assert_error(client.get(path + "/messages", headers=headers), 404, "not_found")
assert_error(client.post(path + "/messages", headers=with_key(headers), json={"text": "чужое"}), 404, "not_found")
assert client.get("/api/v1/chats", headers=headers).json()["items"] == []
def test_member_sees_chat(client, chat, bob):
response = client.get("/api/v1/chats", headers=bob["auth"])
assert [c["id"] for c in response.json()["items"]] == [chat["id"]]
def test_creator_must_be_member(client, alice, bob):
response = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "Без меня", "member_ids": [bob["id"]]})
assert_error(response, 400, "invalid_request")
def test_duplicate_members_return_400(client, alice):
response = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "Дубли", "member_ids": [alice["id"], alice["id"]]})
assert_error(response, 400, "invalid_request")
+162
View File
@@ -0,0 +1,162 @@
import datetime as dt
from concurrent.futures import ThreadPoolExecutor
from fastapi.testclient import TestClient
from sqlalchemy import text
from conftest import assert_error, with_key
from core.config import settings
from core.db import engine
from main import app
from utils import lifecycle
def messages_path(chat):
return "/api/v1/chats/" + chat["id"] + "/messages"
def count_messages():
with engine.connect() as connection:
return connection.scalar(text("SELECT count(*) FROM messages"))
def test_missing_or_invalid_key_returns_400(client, chat, alice):
path = messages_path(chat)
assert_error(client.post(path, headers=alice["auth"], json={"text": "без ключа"}), 400, "invalid_request")
# Только ASCII: HTTP-заголовок с кириллицей тестовый клиент отправить не может.
for key in ("", "a b", "x" * 129, "bad/key", "bad,key"):
response = client.post(path, headers={**alice["auth"], "Idempotency-Key": key}, json={"text": "плохой ключ"})
assert_error(response, 400, "invalid_request")
assert count_messages() == 0
def test_valid_key_alphabet_and_max_length(client, chat, alice):
path = messages_path(chat)
for key in ("A-z_0.9:x", "k" * 128):
assert client.post(path, headers=with_key(alice["auth"], key), json={"text": key[:5]}).status_code == 201
def test_replay_returns_same_message_without_duplicate(client, chat, alice):
path = messages_path(chat)
headers = with_key(alice["auth"], "replay-1")
first = client.post(path, headers=headers, json={"text": "один раз"})
second = client.post(path, headers=headers, json={"text": "один раз"})
assert first.status_code == second.status_code == 201
assert first.json() == second.json()
assert count_messages() == 1
def test_json_key_order_and_whitespace_do_not_matter(client, chat, alice):
path = messages_path(chat)
headers = {**with_key(alice["auth"], "order-1"), "Content-Type": "application/json"}
first = client.post(path, headers=headers, content='{"text": "тот же текст"}')
second = client.post(path, headers=headers, content='{ "text" :"тот же текст" }')
assert first.status_code == second.status_code == 201
assert first.json() == second.json()
assert count_messages() == 1
def test_same_key_with_other_body_returns_409(client, chat, alice):
path = messages_path(chat)
headers = with_key(alice["auth"], "conflict-1")
assert client.post(path, headers=headers, json={"text": "первое"}).status_code == 201
assert_error(client.post(path, headers=headers, json={"text": "другое"}), 409, "conflict")
assert count_messages() == 1
def test_key_scope_is_user_and_chat(client, chat, alice, bob):
path = messages_path(chat)
a = client.post(path, headers=with_key(alice["auth"], "shared"), json={"text": "alice"})
b = client.post(path, headers=with_key(bob["auth"], "shared"), json={"text": "bob"})
assert a.status_code == b.status_code == 201
assert a.json()["id"] != b.json()["id"]
other = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "Другой", "member_ids": [alice["id"]]}).json()
c = client.post(messages_path(other), headers=with_key(alice["auth"], "shared"), json={"text": "alice"})
assert c.status_code == 201
assert c.json()["id"] != a.json()["id"]
assert count_messages() == 3
def test_replay_still_checks_session_and_membership(client, chat, alice, eve):
path = messages_path(chat)
assert client.post(path, headers=with_key(alice["auth"], "k1"), json={"text": "секрет"}).status_code == 201
# Посторонний с тем же ключом не получает чужое сообщение.
assert_error(client.post(path, headers=with_key(eve["auth"], "k1"), json={"text": "секрет"}), 404, "not_found")
# Без токена повтор тоже отклоняется.
assert_error(client.post(path, headers={"Idempotency-Key": "k1"}, json={"text": "секрет"}), 401, "unauthorized")
def test_failed_request_does_not_consume_key(client, chat, alice):
path = messages_path(chat)
headers = with_key(alice["auth"], "retry-after-error")
assert_error(client.post(path, headers=headers, json={"text": ""}), 400, "invalid_request")
# Тот же ключ после ошибки валидации можно использовать для корректного запроса.
assert client.post(path, headers=headers, json={"text": "теперь верно"}).status_code == 201
def test_expired_key_is_reusable(client, chat, alice):
path = messages_path(chat)
headers = with_key(alice["auth"], "ttl-1")
first = client.post(path, headers=headers, json={"text": "старое"}).json()
old = dt.datetime.now(dt.timezone.utc) - dt.timedelta(seconds=settings.idempotency.ttl_seconds + 60)
with engine.begin() as connection:
connection.execute(text("UPDATE idempotency_keys SET created_at = :old"), {"old": old})
# Спустя TTL тот же ключ может описывать уже другое сообщение.
second = client.post(path, headers=headers, json={"text": "новое"})
assert second.status_code == 201
assert second.json()["id"] != first["id"]
assert client.post(path, headers=headers, json={"text": "новое"}).json() == second.json()
def test_concurrent_requests_with_one_key_create_one_message(chat, alice):
path = messages_path(chat)
headers = with_key(alice["auth"], "parallel-1")
def send(_):
# Отдельный клиент на поток (без `with`: lifespan закрыл бы общий пул соединений).
return TestClient(app).post(path, headers=headers, json={"text": "гонка"})
with ThreadPoolExecutor(max_workers=16) as pool:
responses = list(pool.map(send, range(16)))
assert {r.status_code for r in responses} == {201}
assert len({r.json()["id"] for r in responses}) == 1
assert count_messages() == 1
def test_concurrent_different_bodies_one_key_only_one_wins(chat, alice):
path = messages_path(chat)
headers = with_key(alice["auth"], "parallel-2")
def send(i):
return TestClient(app).post(path, headers=headers, json={"text": f"вариант {i % 2}"})
with ThreadPoolExecutor(max_workers=8) as pool:
responses = list(pool.map(send, range(8)))
statuses = sorted(r.status_code for r in responses)
assert set(statuses) <= {201, 409} and 201 in statuses
assert count_messages() == 1
def test_instance_id_header_is_present_and_stable(client, alice):
first = client.get("/health/live")
second = client.get("/api/v1/users/me", headers=alice["auth"])
error = client.get("/api/v1/users/me")
assert first.headers["X-Instance-Id"] == settings.run.instance_id
assert second.headers["X-Instance-Id"] == error.headers["X-Instance-Id"] == first.headers["X-Instance-Id"]
assert error.status_code == 401
def test_ready_returns_503_while_draining(client):
assert client.get("/health/ready").status_code == 200
lifecycle._draining.set()
try:
ready = client.get("/health/ready")
assert_error(ready, 503, "unavailable")
assert client.get("/health/live").status_code == 200 # процесс жив и обслуживает запросы
finally:
lifecycle._draining.clear()
assert client.get("/health/ready").status_code == 200
+66
View File
@@ -0,0 +1,66 @@
from conftest import assert_error, with_key
def test_empty_message_returns_400(client, chat, alice):
path = "/api/v1/chats/" + chat["id"] + "/messages"
headers = with_key(alice["auth"])
assert_error(client.post(path, headers=headers, json={"text": ""}), 400, "invalid_request")
assert_error(client.post(path, headers=headers, json={"text": " \n\t"}), 400, "invalid_request")
def test_sender_is_taken_from_token(client, chat, alice, bob):
path = "/api/v1/chats/" + chat["id"] + "/messages"
response = client.post(path, headers=with_key(bob["auth"]), json={"text": "Привет 👋"})
assert response.status_code == 201
assert response.json()["sender_id"] == bob["id"]
assert response.json()["text"] == "Привет 👋"
spoof = client.post(path, headers=with_key(bob["auth"]), json={"text": "x", "sender_id": alice["id"]})
assert_error(spoof, 400, "invalid_request")
def test_pagination_over_several_pages(client, chat, alice):
path = "/api/v1/chats/" + chat["id"] + "/messages"
headers = alice["auth"]
sent = [client.post(path, headers=with_key(headers), json={"text": f"сообщение {i}"}).json() for i in range(7)]
received = []
pages = 0
cursor = None
while True:
params = {"limit": 3}
if cursor:
params["cursor"] = cursor
page = client.get(path, headers=headers, params=params).json()
received += page["items"]
pages += 1
cursor = page["next_cursor"]
if cursor is None:
break
assert pages == 3 # 3 + 3 + 1
assert received == sent # тот же порядок, ничего не потеряно
assert len({m["id"] for m in received}) == 7 # без повторов
def test_cursor_from_another_chat_returns_400(client, chat, alice):
headers = alice["auth"]
path = "/api/v1/chats/" + chat["id"] + "/messages"
for i in range(2):
client.post(path, headers=with_key(headers), json={"text": f"m{i}"})
cursor = client.get(path, headers=headers, params={"limit": 1}).json()["next_cursor"]
other = client.post("/api/v1/chats", headers=headers, json={"title": "Другой", "member_ids": [alice["id"]]}).json()
response = client.get("/api/v1/chats/" + other["id"] + "/messages", headers=headers, params={"cursor": cursor})
assert_error(response, 400, "invalid_request")
response = client.get(path, headers=headers, params={"cursor": "мусор"})
assert_error(response, 400, "invalid_request")
def test_invalid_limit_returns_400(client, chat, alice):
path = "/api/v1/chats/" + chat["id"] + "/messages"
for limit in (0, 101, "abc"):
response = client.get(path, headers=alice["auth"], params={"limit": limit})
assert_error(response, 400, "invalid_request")
+69
View File
@@ -0,0 +1,69 @@
import uuid
from sqlalchemy import text
from conftest import PASSWORD, assert_error
from core.db import engine
def test_invalid_json_returns_400(client):
response = client.post("/api/v1/users", content=b'{"username": "bob",',
headers={"Content-Type": "application/json"})
assert_error(response, 400, "invalid_request")
def test_extra_field_and_wrong_type_return_400(client):
response = client.post("/api/v1/users", json={"username": "bob", "display_name": "Bob", "password": PASSWORD,
"admin": True})
assert_error(response, 400, "invalid_request")
response = client.post("/api/v1/users", json={"username": "bob", "display_name": 123, "password": PASSWORD})
assert_error(response, 400, "invalid_request")
def test_duplicate_username_returns_409(client, alice):
response = client.post("/api/v1/users", json={"username": "alice", "display_name": "Другая Алиса",
"password": PASSWORD})
assert_error(response, 409, "conflict")
def test_unicode_display_name_is_kept(client):
response = client.post("/api/v1/users", json={"username": "uni", "display_name": "Алиса 👋",
"password": PASSWORD})
assert response.status_code == 201
assert response.json()["display_name"] == "Алиса 👋"
def test_password_is_required_and_length_checked(client):
for password in (None, "short", "x" * 129):
body = {"username": "pwd", "display_name": "P"}
if password is not None:
body["password"] = password
assert_error(client.post("/api/v1/users", json=body), 400, "invalid_request")
# 12 символов (не байт) — допустимо.
response = client.post("/api/v1/users", json={"username": "pwd", "display_name": "P", "password": "пароль123456"})
assert response.status_code == 201
def test_password_is_hashed_and_never_returned(client, alice):
assert "password" not in alice and "password_hash" not in alice
with engine.connect() as connection:
stored = connection.scalar(text("SELECT password_hash FROM users WHERE username = 'alice'"))
assert stored.startswith("$argon2id$")
assert PASSWORD not in stored
def test_me_returns_current_user(client, alice):
response = client.get("/api/v1/users/me", headers=alice["auth"])
assert response.status_code == 200
assert response.json() == {key: alice[key] for key in ("id", "username", "display_name", "created_at")}
def test_x_user_id_no_longer_authenticates(client, alice):
assert_error(client.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]}), 401, "unauthorized")
assert_error(client.get("/api/v1/users/me", headers={"X-User-Id": str(uuid.uuid4())}), 401, "unauthorized")
def test_every_response_has_request_id(client):
assert client.get("/health/live").headers["X-Request-Id"]
assert client.get("/health/ready").headers["X-Request-Id"]
assert_error(client.get("/no/such/path"), 404, "not_found")