forked from mtusi2026/mtusi2026lab3
Keep the message and idempotency receipt in one Core CTE statement with chat-first locking. Preserve rollback, bounded dependency failures, and domain ports. Replace the SQL runner with Alembic. Adopt legacy databases only after validating their journal and PostgreSQL schema, retain all data, and verify migrations on fresh and populated databases.
200 lines
8.7 KiB
Python
200 lines
8.7 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, register, resolve, running_app
|
|
from messenger.identity.domain.models import Session
|
|
from messenger.identity.infrastructure.postgres import (
|
|
PostgresIdentityUnitOfWork,
|
|
PostgresSessionDirectory,
|
|
)
|
|
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_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)
|
|
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
|