Files
mtusi2026lab2/student-tests/api/test_pool.py
T
Artyom 12db77133f Forward the lab 5 foundation while preserving lab 6 telemetry
Source: immutable lab5 snapshot f88e9ba43cdfd7eb6a5a7ae5feb4247b4e820071; forward the allowed diff from 64d5c67. Carry SQLAlchemy, Alembic, reliability fixes, versioned jobs, infrastructure and student tests without changing protected coursework files.

Validation: make check, validate, lint; 515 student tests passed with one Linux-only skip; public smoke with telemetry enabled and repeat migration passed. Stop the owned stack and retain volumes. Preserve the existing OTel work in progress; grade implementation remains a separate phase.
2026-11-06 12:29:35 +03:00

233 lines
9.8 KiB
Python

import time
from dataclasses import replace
from datetime import UTC, datetime, timedelta
from uuid import UUID, uuid4
import pytest
from sqlalchemy import func, select
from sqlalchemy.exc import DBAPIError, IntegrityError
from conftest import (
actor,
keyed,
make_chat,
new_user,
register,
resolve,
running_app,
sql_connection,
)
from messenger.identity.domain.models import Session
from messenger.identity.infrastructure.postgres import (
PostgresIdentityUnitOfWork,
PostgresSessionDirectory,
UserRow,
)
from messenger.messaging.application.ports import AttachmentStates
from messenger.messaging.domain.models import Message
from messenger.messaging.domain.values import MessageText
from messenger.messaging.infrastructure.postgres import (
ChatRow,
IdempotencyKeyRow,
PostgresMessageLog,
)
from messenger.shared.application.errors import Unavailable
from messenger.shared.domain.events import DomainEvent
from messenger.shared.infrastructure.postgres import Database
async def test_exhausted_pool_answers_503_in_bounded_time() -> None:
async with running_app(db_pool_max_size=1, db_acquire_timeout_seconds=0.3) as http:
alice = await register(http, "alice")
database = await resolve(http, Database)
async with database.session() as session:
await session.execute(select(1))
started = time.perf_counter()
starved = await http.get("/api/v1/users/me", headers=actor(alice))
elapsed = time.perf_counter() - started
recovered = await http.get("/api/v1/users/me", headers=actor(alice))
assert starved.status_code == 503
assert starved.json()["error"]["code"] == "unavailable"
assert 0.25 < elapsed < 1
assert recovered.json() == alice
async def test_statement_timeout_is_set_on_connections() -> None:
async with running_app(db_command_timeout_seconds=1.5) as http:
database = await resolve(http, Database)
async with database.session() as session:
statement_timeout = await session.scalar(
select(func.current_setting("statement_timeout"))
)
lock_timeout = await session.scalar(select(func.current_setting("lock_timeout")))
idle_timeout = await session.scalar(
select(func.current_setting("idle_in_transaction_session_timeout"))
)
assert statement_timeout == "1500ms"
assert lock_timeout == "1500ms"
assert idle_timeout == "10s"
async def test_idle_session_does_not_acquire_connection() -> None:
async with running_app(db_pool_max_size=1) as http:
database = await resolve(http, Database)
async with database.session(), database.session() as active:
assert await active.scalar(select(1)) == 1
await database.ping()
async def test_closed_idle_connection_is_replaced_before_registration() -> None:
async with running_app(db_pool_max_size=1) as http:
database = await resolve(http, Database)
async with database.session() as session:
pid = await session.scalar(select(func.pg_backend_pid()))
async with sql_connection() as connection:
assert await connection.scalar(select(func.pg_terminate_backend(pid, 1000)))
body = new_user("reconnect")
response = await http.post("/api/v1/users", json=body)
assert response.status_code == 201
assert response.headers["X-Instance-Id"] and response.headers["X-Request-Id"]
async with database.session() as session:
assert (
await session.scalar(
select(func.count())
.select_from(UserRow)
.where(UserRow.username == body["username"])
)
== 1
)
async def test_readiness_timeout_releases_waiter() -> None:
async with running_app(db_pool_max_size=1, db_acquire_timeout_seconds=2) as http:
database = await resolve(http, Database)
async with database.session() as session:
await session.execute(select(1))
started = time.perf_counter()
response = await http.get("/health/ready")
elapsed = time.perf_counter() - started
assert response.status_code == 503
assert response.json()["error"]["code"] == "unavailable"
assert 0.3 < elapsed < 1
assert (await http.get("/health/ready")).status_code == 200
async def test_server_statement_timeout_returns_connection() -> None:
async with running_app(db_pool_max_size=1, db_command_timeout_seconds=1.5) as http:
database = await resolve(http, Database)
with pytest.raises(Unavailable) as failure:
async with database.session() as session:
await session.execute(select(func.set_config("statement_timeout", "100ms", True)))
await session.execute(select(func.pg_sleep(2)))
assert isinstance(failure.value.__cause__, DBAPIError)
assert getattr(failure.value.__cause__.orig, "sqlstate", None) == "57014"
await database.ping()
@pytest.mark.parametrize("commit", [False, True])
async def test_unit_of_work_persists_sessions_and_events_only_on_commit(commit: bool) -> None:
async with running_app(db_pool_max_size=1) as http:
alice = await register(http, "alice")
database = await resolve(http, Database)
uow = PostgresIdentityUnitOfWork(database)
now = datetime.now(UTC)
_, session = Session.issue(user_id=UUID(alice["id"]), issued_at=now, ttl=timedelta(hours=1))
event = DomainEvent()
async with uow.transaction():
await uow.sessions.add(session)
uow.record(event)
if commit:
await uow.commit()
stored = await PostgresSessionDirectory(database).find(session.token_hash, now)
assert stored == (session if commit else None)
assert uow.collect_new_events() == ([event] if commit else [])
assert uow.collect_new_events() == []
with pytest.raises(RuntimeError, match="вне транзакции"):
_ = uow.session
async def test_integrity_failure_rolls_back_and_keeps_pool_usable() -> None:
async with running_app(db_pool_max_size=1) as http:
database = await resolve(http, Database)
uow = PostgresIdentityUnitOfWork(database)
_, session = Session.issue(
user_id=uuid4(), issued_at=datetime.now(UTC), ttl=timedelta(hours=1)
)
with pytest.raises(IntegrityError) as failure:
async with uow.transaction():
uow.record(DomainEvent())
await uow.sessions.add(session)
await uow.commit()
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
assert uow.collect_new_events() == []
assert uow.seen == []
await database.ping()
@pytest.mark.parametrize(
("command_timeout", "request_timeout"), [(0.15, 5), (1.5, 0.3)], ids=["database", "request"]
)
async def test_blocked_message_times_out_without_taking_key(
command_timeout: float, request_timeout: float
) -> None:
async with running_app(
db_command_timeout_seconds=command_timeout, request_timeout_seconds=request_timeout
) as http:
alice = await register(http, "alice")
chat = await make_chat(http, alice)
database = await resolve(http, Database)
headers = keyed(alice)
path = f"/api/v1/chats/{chat['id']}/messages"
async with database.session() as session:
await session.execute(
select(ChatRow.id).where(ChatRow.id == UUID(chat["id"])).with_for_update()
)
started = time.perf_counter()
blocked = await http.post(path, json={"text": "повтор"}, headers=headers)
assert time.perf_counter() - started < 2
assert blocked.status_code == 503
assert blocked.json()["error"]["code"] == "unavailable"
recovered = await http.post(path, json={"text": "повтор"}, headers=headers)
replay = await http.post(path, json={"text": "повтор"}, headers=headers)
history = await http.get(path, headers=actor(alice))
assert recovered.status_code == replay.status_code == 201
assert replay.json() == recovered.json()
assert history.json()["items"] == [recovered.json()]
async def test_message_integrity_failure_rolls_back_receipt_and_timestamp() -> None:
async with running_app() as http:
alice = await register(http, "alice")
chat = await make_chat(http, alice)
database = await resolve(http, Database)
log = PostgresMessageLog(database, await resolve(http, AttachmentStates))
now = datetime.now(UTC)
since = now - timedelta(days=1)
message = Message(uuid4(), UUID(chat["id"]), UUID(alice["id"]), MessageText("текст"), now)
fingerprint = b"x" * 32
first = await log.post(message, "first", fingerprint, since)
assert first is not None
with pytest.raises(IntegrityError):
await log.post(message, "retry", fingerprint, since)
async with database.session() as session:
assert (
await session.scalar(
select(ChatRow.last_message_at).where(ChatRow.id == message.chat_id)
)
== first.message.created_at
)
assert (
await session.scalar(
select(func.count())
.select_from(IdempotencyKeyRow)
.where(
IdempotencyKeyRow.chat_id == message.chat_id,
IdempotencyKeyRow.key == "retry",
)
)
== 0
)
retry = await log.post(replace(message, id=uuid4()), "retry", fingerprint, since)
assert retry is not None
assert retry.message.created_at > first.message.created_at