Forward the lab 4 foundation and migrate the lab 5 pipeline to SQLAlchemy

This commit is contained in:
Artyom
2026-11-06 09:12:25 +03:00
parent ae9f60fe1f
commit 1217da5f5e
134 changed files with 8243 additions and 1409 deletions
+2 -2
View File
@@ -17,7 +17,7 @@ from dishka import Provider, Scope, make_async_container, provide
from dishka_faststream import setup_dishka
from faststream.rabbit import Channel, RabbitBroker
from conftest import ROOT, STARTUP_SECONDS, container, image, published
from conftest import ROOT, STARTUP_SECONDS, container, free_port, image, published
from fakes import NullLogger
from messenger.attachments.application.bus import AttachmentsCommandBus
from messenger.attachments.application.commands import ProcessJob
@@ -90,7 +90,7 @@ def rabbitmq() -> Iterator[dict[str, Any]]:
"100:101",
*volumes,
"-p",
"127.0.0.1::5672",
f"127.0.0.1:{free_port()}:5672",
image(RABBITMQ_IMAGE),
)
try:
+28 -3
View File
@@ -9,7 +9,7 @@ from uuid import uuid4
import httpx
import pytest
from conftest import STARTUP_SECONDS, container, image, published
from conftest import STARTUP_SECONDS, container, free_port, image, published
from messenger.attachments.application.errors import ObjectMissingError
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
from messenger.shared.application.errors import Unavailable
@@ -23,7 +23,7 @@ BUCKET = "messenger-attachments"
def rustfs() -> Iterator[str]:
name = f"mtusi-lab5-test-rustfs-{uuid4().hex[:8]}"
keys = ["-e", f"RUSTFS_ACCESS_KEY={ROOT_KEY}", "-e", f"RUSTFS_SECRET_KEY={ROOT_SECRET}"]
container(name, *keys, "-p", "127.0.0.1::9000", image(RUSTFS_IMAGE))
container(name, *keys, "-p", f"127.0.0.1:{free_port()}:9000", image(RUSTFS_IMAGE))
try:
endpoint = f"http://127.0.0.1:{published(name, 9000)}"
deadline = time.monotonic() + STARTUP_SECONDS
@@ -71,6 +71,27 @@ async def test_round_trip_of_the_largest_object(rustfs: str) -> None:
await objects.delete(key)
async def test_listing_is_paged_in_byte_order_and_stat_reads_size(rustfs: str) -> None:
prefix = f"reconcile-{uuid4().hex}/"
keys = [f"{prefix}{name}" for name in ("b", "a", "Z", "a-1", "é")]
async with storage(rustfs) as objects:
for size, key in enumerate(keys, start=1):
await objects.put(key, b"x" * size, "image/png")
pages = [page async for page in objects.listing(prefix, 2)]
assert [len(page) for page in pages] == [2, 2, 1]
listed = [item.key for page in pages for item in page]
assert listed == sorted(keys, key=str.encode)
sizes = {item.key: item.size for page in pages for item in page}
assert sizes == {key: size for size, key in enumerate(keys, start=1)}
found = await objects.stat(keys[0])
assert found is not None
assert found.size == 1
assert await objects.stat(f"{prefix}absent") is None
for key in keys:
await objects.delete(key)
assert not [item async for page in objects.listing(prefix, 2) for item in page]
async def test_unreachable_endpoint_is_unavailable_in_bounded_time() -> None:
started = time.monotonic()
async with storage_without_bucket("http://127.0.0.1:1") as objects:
@@ -78,7 +99,11 @@ async def test_unreachable_endpoint_is_unavailable_in_bounded_time() -> None:
await objects.put("attachments/x", b"x", "image/png")
with pytest.raises(Unavailable):
await objects.open("attachments/x")
assert time.monotonic() - started < 8
with pytest.raises(Unavailable):
await objects.stat("attachments/x")
with pytest.raises(Unavailable):
await anext(aiter(objects.listing("attachments/", 10)))
assert time.monotonic() - started < 12
@asynccontextmanager
+38 -2
View File
@@ -1,8 +1,11 @@
from uuid import uuid4
import time
from uuid import UUID, uuid4
from httpx import AsyncClient
from sqlalchemy import select
from conftest import actor, keyed, make_chat, register
from conftest import actor, keyed, make_chat, register, sql_connection
from messenger.messaging.infrastructure.postgres import ChatRow
async def test_outsider_gets_404_on_chat(client: AsyncClient) -> None:
@@ -82,3 +85,36 @@ async def test_403_is_never_used(client: AsyncClient) -> None:
]
for path in paths:
assert (await client.get(path, headers=actor(eve))).status_code != 403
async def test_request_shape_is_checked_before_access(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
for chat_id in (chat["id"], uuid4()):
path = f"/api/v1/chats/{chat_id}/messages"
unkeyed = await client.post(path, json={"text": "чужое"}, headers=actor(eve))
extra = await client.post(path, json={"text": "x", "a": 1}, headers=keyed(eve))
assert unkeyed.status_code == extra.status_code == 400
assert unkeyed.json()["error"]["code"] == extra.json()["error"]["code"] == "invalid_request"
blank = await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": " "}, headers=keyed(eve)
)
assert blank.status_code == 404
async def test_outsider_does_not_wait_for_members_lock(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
async with sql_connection() as holder:
await holder.execute(
select(ChatRow.id).where(ChatRow.id == UUID(chat["id"])).with_for_update()
)
started = time.perf_counter()
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "чужое"}, headers=keyed(eve)
)
elapsed = time.perf_counter() - started
assert response.status_code == 404
assert elapsed < 0.5
+13 -1
View File
@@ -9,7 +9,7 @@ import pytest
from httpx import AsyncClient, Response
from PIL import Image
from conftest import actor, make_chat, register, resolve, scalar
from conftest import actor, make_chat, register, resolve, running_app, scalar
from fakes import MemoryObjectStorage
from messenger.attachments.application.ports import ObjectStorage
from pictures import GIF, JPEG, SAMPLE, WEBP, png
@@ -140,6 +140,18 @@ async def test_access_is_checked_before_content(client: AsyncClient) -> None:
assert anonymous.headers["www-authenticate"] == 'Bearer realm="messenger"'
async def test_token_is_checked_before_the_declared_size() -> None:
async with running_app(max_upload_bytes=4096) as http:
alice, _, _, chat = await trio(http)
oversized = png(16, 16, size=8192)
anonymous = await http.post(
f"/api/v1/chats/{chat['id']}/attachments?filename=a.png", content=oversized, headers=PNG
)
assert anonymous.status_code == 401
assert anonymous.headers["www-authenticate"] == 'Bearer realm="messenger"'
assert (await upload(http, alice, chat, oversized)).status_code == 413
async def test_exact_limit_is_accepted(client: AsyncClient) -> None:
alice, _, _, chat = await trio(client)
response = await upload(client, alice, chat, png(16, 16, size=LIMIT))
+19 -14
View File
@@ -33,20 +33,6 @@ def test_identity_does_not_know_about_messaging() -> None:
assert not {k: v for k, v in offenders.items() if v}
def test_messaging_touches_identity_only_through_events() -> None:
allowed = f"{IDENTITY}.domain.events"
offenders: dict[str, list[str]] = {}
for path in modules_under("messaging"):
borrowed = [
module
for module in imports_of(path)
if module.startswith(IDENTITY) and module != allowed
]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders
def test_attachments_and_other_zones_do_not_import_each_other() -> None:
offenders: dict[str, list[str]] = {}
for zone, foreign in (
@@ -125,6 +111,7 @@ def test_shared_core_holds_only_platform() -> None:
"ids.py",
"logging.py",
"postgres.py",
"readiness.py",
}
@@ -267,6 +254,16 @@ def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
for node in ast.walk(tree):
if isinstance(node, ast.Constant) and isinstance(node.value, str):
words.update(re.findall(r"\b(?:FROM|JOIN|INTO|UPDATE)\s+(\w+)", node.value))
if (
isinstance(node, ast.Assign)
and any(
isinstance(target, ast.Name) and target.id == "__tablename__"
for target in node.targets
)
and isinstance(node.value, ast.Constant)
and isinstance(node.value.value, str)
):
words.add(node.value.value)
return words & set(tables)
@@ -287,3 +284,11 @@ def test_messaging_does_not_import_identity_at_all() -> None:
for path in modules_under("messaging")
}
assert not {key: value for key, value in borrowed.items() if value}
def test_sqlalchemy_stays_in_infrastructure_and_asyncpg_is_only_a_driver() -> None:
for path in SOURCE.rglob("*.py"):
modules = {module.split(".")[0] for module in imports_of(path)}
assert "asyncpg" not in modules
if "infrastructure" not in path.parts:
assert "sqlalchemy" not in modules
+37 -6
View File
@@ -2,13 +2,18 @@ import asyncio
import time
from datetime import datetime
from hashlib import sha256
from uuid import UUID
import pytest
from redis.asyncio import Redis
from sqlalchemy import select
from conftest import actor, bearer, register, resolve, running_app, scalar
from conftest import actor, bearer, keyed, make_chat, register, resolve, running_app, scalar
from messenger.identity.application.ports import SessionDirectory
from messenger.identity.domain.models import Session
from messenger.identity.infrastructure.postgres import PostgresSessionRepository, SessionRow
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
from messenger.shared.application.errors import Unavailable
BEARER = 'Bearer realm="messenger"'
@@ -31,8 +36,9 @@ async def test_second_check_is_served_from_cache(valkey: dict[str, str]) -> None
assert (await cache.info("stats"))["keyspace_hits"] == hits + 1
key = key_of(token_of(alice))
stored = str(await cache.get(key))
sql = "SELECT expires_at FROM sessions WHERE user_id = $1::uuid"
expires_at: datetime = await scalar(sql, alice["id"])
expires_at: datetime = await scalar(
select(SessionRow.expires_at).where(SessionRow.user_id == UUID(alice["id"]))
)
assert alice["id"] in stored and token_of(alice) not in stored
assert await cache.pexpiretime(key) <= int(expires_at.timestamp() * 1000)
await cache.aclose()
@@ -53,6 +59,29 @@ async def test_logout_writes_tombstone_before_database(valkey: dict[str, str]) -
await cache.aclose()
async def test_logout_rejected_by_database_changes_nothing(
valkey: dict[str, str], monkeypatch: pytest.MonkeyPatch
) -> None:
async def broken(self: PostgresSessionRepository, token_hash: bytes) -> None:
raise Unavailable("PostgreSQL недоступен")
cache = Redis.from_url(valkey["url"])
logout = "/api/v1/auth/sessions/current"
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
with monkeypatch.context() as patch:
patch.setattr(PostgresSessionRepository, "remove", broken)
failed = await http.delete(logout, headers=actor(alice))
assert failed.status_code == 503
assert failed.json()["error"]["code"] == "unavailable"
assert await cache.get(key_of(token_of(alice))) is None
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
assert (await http.delete(logout, headers=actor(alice))).status_code == 204
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
await cache.aclose()
async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, str]) -> None:
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
@@ -69,9 +98,6 @@ async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, s
await released.wait()
return stale[-1]
async def invalidate(self, session: Session) -> None:
await origin.invalidate(session)
directory._origin = SlowOrigin()
reader = asyncio.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
await entered.wait()
@@ -106,6 +132,10 @@ async def test_unreachable_cache_is_bypassed_without_anonymous_access() -> None:
stranger = await http.get("/api/v1/users/me", headers=bearer("x" * 43))
elapsed = time.perf_counter() - started
ready = await http.get("/health/ready")
chat = await make_chat(http, alice)
posted = await http.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "без кэша"}, headers=keyed(alice)
)
logout = await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
still = await http.get("/api/v1/users/me", headers=actor(alice))
assert me.json() == alice
@@ -113,6 +143,7 @@ async def test_unreachable_cache_is_bypassed_without_anonymous_access() -> None:
assert stranger.headers["WWW-Authenticate"] == BEARER
assert elapsed < 1
assert ready.status_code == 200
assert posted.status_code == 201
assert logout.status_code == 503
assert logout.json()["error"]["code"] == "unavailable"
assert still.status_code == 200
+19
View File
@@ -1,10 +1,13 @@
import asyncio
from datetime import UTC, datetime, timedelta
from urllib.parse import quote
from uuid import uuid4
import pytest
from httpx import AsyncClient
from conftest import PASSWORD, actor, keyed, make_chat, register
from messenger.shared.infrastructure.clock import MonotonicUtcClock
CLIENTS = 10
PER_CLIENT = 10
@@ -60,6 +63,22 @@ async def test_hundred_messages_from_ten_clients(client: AsyncClient) -> None:
assert len(set(stamps)) == TOTAL, "created_at внутри чата обязан строго возрастать"
async def test_history_follows_the_clock_but_never_moves_back(
monkeypatch: pytest.MonkeyPatch, client: AsyncClient
) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
base = datetime.now(UTC) + timedelta(minutes=10)
stamps = []
for moment in (base, base - timedelta(minutes=5), base + timedelta(seconds=5)):
monkeypatch.setattr(MonotonicUtcClock, "now", lambda _self, moment=moment: moment)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "часы"}, headers=keyed(alice)
)
stamps.append(datetime.fromisoformat(response.json()["created_at"]))
assert stamps == [base, base + timedelta(microseconds=1), base + timedelta(seconds=5)]
async def test_parallel_registration_keeps_username_unique(client: AsyncClient) -> None:
body = {"username": f"race_{uuid4().hex[:12]}", "display_name": "Гонка", "password": PASSWORD}
responses = await asyncio.gather(*(client.post("/api/v1/users", json=body) for _ in range(20)))
+15 -6
View File
@@ -1,10 +1,13 @@
import asyncio
from urllib.parse import quote
from uuid import uuid4
from uuid import UUID, uuid4
from httpx import AsyncClient
from sqlalchemy import func, select
from conftest import PASSWORD, actor, keyed, make_chat, new_user, register, running_app, scalar
from messenger.identity.infrastructure.postgres import UserRow
from messenger.messaging.infrastructure.postgres import ChatMemberRow, ChatRow
REGISTRATIONS = 25
@@ -65,8 +68,8 @@ async def test_rejected_registration_leaves_no_trace() -> None:
"/api/v1/users", json={"username": "AB", "display_name": "", "password": PASSWORD}
)
assert invalid.status_code == 400
sql = "SELECT count(*) FROM users WHERE username = $1"
assert await scalar(sql, alice["username"]) == 1
sql = select(func.count()).select_from(UserRow).where(UserRow.username == alice["username"])
assert await scalar(sql) == 1
async def test_failed_chat_creation_rolls_back_both_tables() -> None:
@@ -83,9 +86,15 @@ async def test_failed_chat_creation_rolls_back_both_tables() -> None:
assert rejected.json()["error"]["code"] == "invalid_request"
after = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json()
assert after["items"] == before["items"]
assert await scalar("SELECT count(*) FROM chats WHERE title = $1", title) == 0
members = "SELECT count(*) FROM chat_members WHERE user_id = $1::uuid"
assert await scalar(members, alice["id"]) == 0
assert (
await scalar(select(func.count()).select_from(ChatRow).where(ChatRow.title == title)) == 0
)
members = (
select(func.count())
.select_from(ChatMemberRow)
.where(ChatMemberRow.user_id == UUID(alice["id"]))
)
assert await scalar(members) == 0
async def test_rejected_message_does_not_enter_history() -> None:
+35 -15
View File
@@ -5,14 +5,15 @@ import socket
import subprocess
import sys
import time
from pathlib import Path
import httpx
from conftest import DATABASE, new_user
from messenger.shared.entrypoints.health import DRAINING
from conftest import DATABASE, free_port, new_user
from messenger.shared.infrastructure.readiness import DRAINING
DRAIN = 1.5
SHUTDOWN = 4
DRAIN = 1.0
SHUTDOWN = 3
GUNICORN = (
"-m",
"gunicorn",
@@ -36,19 +37,24 @@ async def test_draining_replica_is_not_ready_but_alive(client: httpx.AsyncClient
assert (await client.get("/health/ready")).status_code == 200
def free_port() -> int:
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
return probe.getsockname()[1]
def status(port: int, path: str) -> int:
try:
return httpx.get(f"http://127.0.0.1:{port}{path}", timeout=1).status_code
return httpx.get(f"http://127.0.0.1:{port}{path}", timeout=1, trust_env=False).status_code
except httpx.TransportError:
return 0
def answer_of(connection: socket.socket) -> tuple[str, dict[str, str], dict]:
data = b""
while chunk := connection.recv(4096):
data += chunk
connection.close()
head, _, body = data.partition(b"\r\n\r\n")
status, *lines = head.decode("latin-1").split("\r\n")
headers = dict(line.lower().split(": ", 1) for line in lines)
return status, headers, json.loads(body) if body else {}
def begin_registration(port: int) -> tuple[socket.socket, bytes]:
body = json.dumps(new_user("drain")).encode()
head = (
@@ -60,7 +66,7 @@ def begin_registration(port: int) -> tuple[socket.socket, bytes]:
return connection, body[8:]
def test_sigterm_leaves_rotation_then_closes_and_exits() -> None:
def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests(tmp_path: Path) -> None:
port = free_port()
settings = {
"HOST": "127.0.0.1",
@@ -74,23 +80,27 @@ def test_sigterm_leaves_rotation_then_closes_and_exits() -> None:
"DRAIN_SECONDS": str(DRAIN),
"SHUTDOWN_TIMEOUT_SECONDS": str(SHUTDOWN),
}
log_path = tmp_path / "gunicorn.log"
log = log_path.open("w")
server = subprocess.Popen(
[sys.executable, *GUNICORN],
env={**os.environ, **settings},
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
stdout=log,
stderr=log,
)
try:
deadline = time.monotonic() + 30
while status(port, "/health/ready") != 200:
assert time.monotonic() < deadline, "gunicorn не стал готов"
assert server.poll() is None and time.monotonic() < deadline, log_path.read_text()
time.sleep(0.2)
pending, rest = begin_registration(port)
stuck, _ = begin_registration(port)
sent = time.monotonic()
server.send_signal(signal.SIGTERM)
time.sleep(0.3)
during = status(port, "/health/ready"), status(port, "/health/live")
while status(port, "/health/live") == 200:
assert time.monotonic() - sent < SHUTDOWN + 2, log_path.read_text()
time.sleep(0.05)
closed = time.monotonic() - sent
pending.sendall(rest)
@@ -98,13 +108,23 @@ def test_sigterm_leaves_rotation_then_closes_and_exits() -> None:
pending.close()
code = server.wait(timeout=SHUTDOWN + 2)
exited = time.monotonic() - sent
cancelled, headers, error = answer_of(stuck)
finally:
if server.poll() is None:
server.kill()
server.wait(timeout=5)
log.close()
print(f"окно: ready/live {during}, порт закрыт через {closed:.2f} с, выход {exited:.2f} с")
print(f"запрос, принятый до SIGTERM и дописанный после закрытия порта: {answer}")
print(f"запрос, тело которого так и не пришло: {cancelled or 'соединение закрыто без ответа'}")
print(f" content-type {headers.get('content-type')}, тело {error}")
assert during == (503, 200)
assert answer == "HTTP/1.1 201 Created"
assert cancelled == "HTTP/1.1 503 Service Unavailable"
assert headers["content-type"] == "application/json"
assert headers["x-instance-id"]
assert error["error"]["code"] == "unavailable"
assert error["error"]["request_id"] == headers["x-request-id"]
assert DRAIN - 0.2 <= closed < SHUTDOWN
assert exited < SHUTDOWN
assert code == 0
-12
View File
@@ -77,18 +77,6 @@ async def test_queue_overflow_drops_events_without_raising() -> None:
assert bus.pending <= 16
async def test_projection_runs_before_publish_returns() -> None:
bus = EventBus(NullLogger())
seen: list[str] = []
async def projection(_event: MessagePosted) -> None:
seen.append("projected")
bus.project(MessagePosted, projection)
await InMemoryEventPublisher(bus).publish([posted()])
assert seen == ["projected"]
async def test_publication_does_not_delay_response() -> None:
app = create_app(**split_settings(log_level="CRITICAL"))
async with (
+23 -6
View File
@@ -4,8 +4,10 @@ from uuid import uuid4
import pytest
from httpx import AsyncClient, Response
from sqlalchemy import func, select
from conftest import actor, keyed, make_chat, register, running_app, scalar
from messenger.messaging.infrastructure.postgres import IdempotencyKeyRow
INVALID_KEYS = ["", "k" * 129, "два слова", "a b", "a/b", "ключ"]
@@ -93,12 +95,22 @@ async def test_key_is_scoped_by_user_and_chat(client: AsyncClient) -> None:
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
other = await make_chat(client, alice)
ids = {
(await send(client, chat, alice, "алиса", "shared-1")).json()["id"],
(await send(client, chat, bob, "боб", "shared-1")).json()["id"],
(await send(client, other, alice, "другой чат", "shared-1")).json()["id"],
}
cases = [(chat, alice, "алиса"), (chat, bob, "боб"), (other, alice, "другой чат")]
messages = []
for target, user, text in cases:
response = await send(client, target, user, text, "shared-1")
assert response.status_code == 201
message = response.json()
assert (message["chat_id"], message["sender_id"], message["text"]) == (
target["id"],
user["id"],
text,
)
messages.append(message)
ids = {message["id"] for message in messages}
assert len(ids) == 3
for (target, user, text), message in zip(cases, messages, strict=True):
assert (await send(client, target, user, text, "shared-1")).json() == message
async def test_replay_checks_session_and_access_again(client: AsyncClient) -> None:
@@ -142,4 +154,9 @@ async def test_concurrent_retries_through_two_replicas_store_one_message() -> No
}
assert all(response.json() == responses[0].json() for response in responses)
assert [item["text"] for item in await history(second, chat, alice)] == [text]
assert await scalar("SELECT count(*) FROM idempotency_keys WHERE key = $1", key) == 1
assert (
await scalar(
select(func.count()).select_from(IdempotencyKeyRow).where(IdempotencyKeyRow.key == key)
)
== 1
)
+501 -199
View File
@@ -1,240 +1,542 @@
import asyncio
import hashlib
import os
import shutil
import sys
from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
from pathlib import Path
from uuid import uuid4
import asyncpg
import pytest
from alembic import command
from alembic.autogenerate import compare_metadata
from alembic.migration import MigrationContext
from alembic.script import ScriptDirectory
from alembic.util import CommandError
from sqlalchemy import MetaData, Table, case, func, insert, inspect, literal, make_url, select, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.pool import NullPool
from conftest import DATABASE, scalar
from messenger.migrate import MigrationChangedError, migrate, migrations
from conftest import DATABASE, ROOT, migration_config, sql_connection, upgrade
from messenger.attachments.infrastructure.postgres import (
AttachmentRow,
JobEventRow,
JobRow,
OutboxRow,
VariantRow,
)
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
from messenger.messaging.infrastructure.postgres import (
ChatMemberRow,
ChatRow,
IdempotencyKeyRow,
MessageAttachmentRow,
MessageRow,
)
from messenger.shared.infrastructure.postgres import Base
COUNTS = """
SELECT (SELECT count(*) FROM users), (SELECT count(*) FROM sessions),
(SELECT count(*) FROM chats), (SELECT count(*) FROM chat_members),
(SELECT count(*) FROM messages), (SELECT count(*) FROM idempotency_keys),
(SELECT count(*) FROM attachments), (SELECT count(*) FROM message_attachments),
(SELECT count(*) FROM attachment_variants), (SELECT count(*) FROM jobs),
(SELECT count(*) FROM outbox), (SELECT count(*) FROM job_events)
"""
PIPELINE_COLUMNS = {
"attachments": {
"id",
"status",
"published_version",
"error_code",
"staging_key",
"original_key",
},
"attachment_variants": {
"attachment_id",
"pipeline_version",
"name",
"sha256",
"size_bytes",
"object_key",
},
"jobs": {"job_id", "attachment_id", "pipeline_version", "status", "attempt"},
"outbox": {"job_id", "payload", "published_at"},
"job_events": {"job_id", "attachment_id", "kind", "attempt"},
}
VERSIONS = [
"0001_init",
"0002_idempotency_keys",
"0003_attachments",
"0004_jobs",
"0005_failed_registry",
"0006_attachment_quarantine",
]
TABLES = [
UserRow,
SessionRow,
ChatRow,
ChatMemberRow,
MessageRow,
IdempotencyKeyRow,
AttachmentRow,
JobRow,
OutboxRow,
JobEventRow,
VariantRow,
MessageAttachmentRow,
]
async def counts() -> list[int]:
connection = await asyncpg.connect(DATABASE["url"])
@pytest.fixture
async def empty_database(database: str) -> AsyncIterator[str]:
name = f"migration_test_{uuid4().hex}"
url = make_url(database).set(drivername="postgresql+asyncpg")
engine = create_async_engine(url, isolation_level="AUTOCOMMIT", poolclass=NullPool)
try:
return list(await connection.fetchrow(COUNTS))
async with engine.connect() as connection:
await connection.exec_driver_sql(f"CREATE DATABASE {name}")
yield url.set(database=name).render_as_string(hide_password=False)
finally:
await connection.close()
async with engine.connect() as connection:
await connection.exec_driver_sql(f"DROP DATABASE {name} WITH (FORCE)")
await engine.dispose()
async def legacy(dsn: str, versions: int = 6) -> None:
async with sql_connection(dsn) as connection:
await connection.execute(
text(
"CREATE TABLE schema_migrations (version text PRIMARY KEY, checksum text NOT NULL, "
"applied_at timestamptz NOT NULL DEFAULT now())"
)
)
journal = await connection.run_sync(
lambda sync: Table("schema_migrations", MetaData(), autoload_with=sync)
)
for version in VERSIONS[:versions]:
sql = (ROOT / "student-tests" / "fixtures" / "legacy" / f"{version}.sql").read_text()
for statement in sql.split(";"):
if statement.strip():
await connection.execute(text(statement))
await connection.execute(
insert(journal).values(
version=version, checksum=hashlib.sha256(sql.encode()).hexdigest()
)
)
async def seed(dsn: str, versions: int = 6) -> None:
user, chat, message = uuid4(), uuid4(), uuid4()
stamp = datetime.now(UTC)
rows = [
(
UserRow,
{
"id": user,
"username": "legacy_user",
"display_name": "Старые данные",
"password_hash": "$argon2id$legacy",
"created_at": stamp,
},
),
(
SessionRow,
{
"token_hash": b"s" * 32,
"user_id": user,
"created_at": stamp,
"expires_at": stamp + timedelta(days=1),
},
),
(
ChatRow,
{
"id": chat,
"title": "Существующий чат",
"created_at": stamp,
"last_message_at": stamp,
},
),
(
ChatMemberRow,
{"chat_id": chat, "user_id": user, "position": 1, "chat_created_at": stamp},
),
(
MessageRow,
{
"id": message,
"chat_id": chat,
"sender_id": user,
"text": "Сохранить",
"created_at": stamp,
},
),
(
IdempotencyKeyRow,
{
"chat_id": chat,
"user_id": user,
"key": "legacy-key",
"fingerprint": b"f" * 32,
"message_id": message,
"created_at": stamp,
},
),
]
async with sql_connection(dsn) as connection:
for model, row in rows[: 5 if versions == 1 else 6]:
await connection.execute(insert(model).values(**row))
if versions >= 3:
attachment = uuid4()
row = {
"id": attachment,
"chat_id": chat,
"owner_id": user,
"filename": "legacy.png",
"content_type": "image/png",
"size_bytes": 17,
"sha256": "a" * 64,
"width": 1,
"height": 1,
"object_key": f"attachments/{attachment}",
"status": "ready",
"created_at": stamp,
"updated_at": stamp,
}
if versions >= 4:
row.update(original_key=row["object_key"], published_version=1)
if versions >= 6:
row.update(quarantine_reason="missing", quarantined_at=stamp)
table = await connection.run_sync(
lambda sync: Table("attachments", MetaData(), autoload_with=sync)
)
await connection.execute(insert(table).values(**row))
await connection.execute(
insert(MessageAttachmentRow).values(
message_id=message, position=0, chat_id=chat, attachment_id=attachment
)
)
if versions >= 4:
job = uuid4()
await connection.execute(
insert(JobRow).values(
job_id=job,
attachment_id=attachment,
pipeline_version=1,
status="processing",
attempt=2,
claims=3,
lease_token=uuid4(),
lease_until=stamp + timedelta(minutes=1),
created_at=stamp,
updated_at=stamp,
)
)
await connection.execute(
insert(OutboxRow).values(
job_id=job,
payload={"job_id": str(job)},
available_at=stamp,
)
)
await connection.execute(
insert(JobEventRow).values(
job_id=job,
attachment_id=attachment,
kind="claimed",
attempt=2,
)
)
await connection.execute(
insert(VariantRow).values(
attachment_id=attachment,
pipeline_version=1,
name="thumbnail",
object_key=f"variants/{attachment}/1/thumbnail.jpg",
content_type="image/jpeg",
size_bytes=17,
width=1,
height=1,
sha256="a" * 64,
created_at=stamp,
)
)
async def contents(dsn: str) -> dict:
async with sql_connection(dsn) as connection:
tables = await connection.run_sync(lambda sync: inspect(sync).get_table_names())
result = {}
for model in TABLES:
if model.__tablename__ not in tables:
continue
table = await connection.run_sync(
lambda sync, name=model.__tablename__: Table(name, MetaData(), autoload_with=sync)
)
missing = {}
if model is AttachmentRow and "published_version" not in table.c:
missing = {
"original_key": case((table.c.status == "ready", table.c.object_key)),
"staging_key": case((table.c.status == "pending", table.c.object_key)),
"published_version": case((table.c.status == "ready", 1), else_=0),
}
columns = [
table.c[col.name]
if col.name in table.c
else missing.get(col.name, literal(None)).label(col.name)
for col in model.__table__.columns
]
result[model.__tablename__] = (
await connection.execute(select(*columns).order_by(*table.primary_key))
).all()
return result
async def revision(dsn: str) -> str | None:
async with sql_connection(dsn) as connection:
return await connection.run_sync(
lambda sync: MigrationContext.configure(sync).get_current_revision()
)
async def test_migrations_are_ordered_and_versioned() -> None:
versions = [version for version, _ in migrations()]
assert versions == sorted(versions)
assert versions[:5] == [
"0001_init",
"0002_idempotency_keys",
"0003_attachments",
"0004_jobs",
"0005_failed_registry",
]
plan = await scalar("SELECT indexdef FROM pg_indexes WHERE indexname = 'jobs_failed_idx'")
assert "WHERE (status = 'failed'::text)" in plan
applied = await scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations")
assert applied == versions
scripts = ScriptDirectory.from_config(migration_config(DATABASE["url"]))
assert [script.revision for script in reversed(list(scripts.walk_revisions()))] == VERSIONS
assert await revision(DATABASE["url"]) == VERSIONS[-1]
async def test_rerun_changes_nothing() -> None:
before = await counts()
assert await migrate(DATABASE["url"]) == []
assert await counts() == before
async def test_fresh_schema_matches_models(empty_database: str) -> None:
await upgrade(empty_database)
async with sql_connection(empty_database) as connection:
assert (
await connection.run_sync(
lambda sync: compare_metadata(MigrationContext.configure(sync), Base.metadata)
)
== []
)
await asyncio.to_thread(command.check, migration_config(empty_database))
async def test_changed_migration_is_refused() -> None:
connection = await asyncpg.connect(DATABASE["url"])
async def test_rerun_changes_nothing(empty_database: str) -> None:
await upgrade(empty_database)
await seed(empty_database)
before = await contents(empty_database)
await upgrade(empty_database)
assert await contents(empty_database) == before
assert await revision(empty_database) == VERSIONS[-1]
@pytest.mark.parametrize("versions", [1, 2, 3, 4, 5, 6])
async def test_legacy_upgrade_preserves_every_row(empty_database: str, versions: int) -> None:
await legacy(empty_database, versions)
await seed(empty_database, versions)
before = await contents(empty_database)
async with sql_connection(empty_database) as connection:
journal = (
await connection.execute(text("SELECT * FROM schema_migrations ORDER BY version"))
).all()
await upgrade(empty_database)
after = await contents(empty_database)
assert {name: after[name] for name in before} == before
assert await revision(empty_database) == VERSIONS[-1]
async with sql_connection(empty_database) as connection:
assert (
await connection.execute(text("SELECT * FROM schema_migrations ORDER BY version"))
).all() == journal
assert (
await connection.scalar(
text("SELECT count(*) FROM pg_namespace WHERE nspname LIKE 'alembic_verify_%'")
)
== 0
)
await upgrade(empty_database)
assert await contents(empty_database) == after
@pytest.mark.parametrize(
"damage",
[
"DROP INDEX messages_history_idx",
"ALTER TABLE messages DROP CONSTRAINT messages_chat_id_sender_id_fkey",
"ALTER TABLE users DROP CONSTRAINT users_username_format",
"ALTER TABLE users ALTER COLUMN display_name TYPE varchar",
'ALTER TABLE users ALTER COLUMN username TYPE text COLLATE "C"',
"ALTER TABLE sessions SET UNLOGGED",
"ALTER TABLE sessions ALTER COLUMN expires_at DROP NOT NULL",
"UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0001_init'",
"DELETE FROM schema_migrations WHERE version = '0001_init'",
"UPDATE schema_migrations SET version = 'unknown' WHERE version = '0002_idempotency_keys'",
"DROP TABLE schema_migrations",
"ALTER TABLE attachments DROP CONSTRAINT attachments_owner_fkey",
"ALTER TABLE attachments DROP CONSTRAINT attachments_quarantine_check",
"ALTER TABLE message_attachments DROP CONSTRAINT message_attachments_attachment_fkey",
'ALTER TABLE attachments ALTER COLUMN object_key TYPE text COLLATE "default"',
"DROP INDEX attachments_pending_idx",
"UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0003_attachments'",
],
)
async def test_legacy_drift_is_refused_without_stamping(empty_database: str, damage: str) -> None:
await legacy(empty_database)
await seed(empty_database)
before = await contents(empty_database)
async with sql_connection(empty_database) as connection:
await connection.execute(text(damage))
with pytest.raises(RuntimeError, match=r"[Ll]egacy|[Ee]xisting|Unknown"):
await upgrade(empty_database)
assert await revision(empty_database) is None
assert await contents(empty_database) == before
async def test_unknown_revision_is_refused(empty_database: str) -> None:
await upgrade(empty_database)
await seed(empty_database)
before = await contents(empty_database)
async with sql_connection(empty_database) as connection:
await connection.execute(text("UPDATE alembic_version SET version_num = 'unknown'"))
with pytest.raises(CommandError, match="unknown"):
await upgrade(empty_database)
assert await contents(empty_database) == before
assert await revision(empty_database) == "unknown"
@pytest.mark.parametrize("existing", [False, True])
async def test_simultaneous_migration_processes_serialize(
empty_database: str, existing: bool
) -> None:
if existing:
await legacy(empty_database)
await seed(empty_database)
before = await contents(empty_database)
processes = []
try:
original = await connection.fetchval(
"SELECT checksum FROM schema_migrations WHERE version = '0001_init'"
)
await connection.execute(
"UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0001_init'"
)
with pytest.raises(MigrationChangedError):
await migrate(DATABASE["url"])
await connection.execute(
"UPDATE schema_migrations SET checksum = $1 WHERE version = '0001_init'", original
)
for _ in range(2):
processes.append(
await asyncio.create_subprocess_exec(
sys.executable,
"-m",
"alembic",
"upgrade",
"head",
cwd=ROOT,
env={**os.environ, "DATABASE_URL": empty_database},
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
)
async with asyncio.timeout(30):
output = await asyncio.gather(*(process.communicate() for process in processes))
assert [process.returncode for process in processes] == [0, 0], output
finally:
await connection.close()
for process in processes:
if process.returncode is None:
process.kill()
await process.wait()
after = await contents(empty_database)
assert {name: after[name] for name in before} == before
assert await revision(empty_database) == VERSIONS[-1]
async def test_sender_must_be_member_even_bypassing_api() -> None:
connection = await asyncpg.connect(DATABASE["url"])
try:
with pytest.raises(asyncpg.ForeignKeyViolationError):
with pytest.raises(IntegrityError) as failure:
async with sql_connection() as connection:
await connection.execute(
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
"VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'x', now())"
insert(MessageRow).values(
id=uuid4(), chat_id=uuid4(), sender_id=uuid4(), text="x", created_at=func.now()
)
)
finally:
await connection.close()
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
async def test_key_needs_a_member_and_a_message() -> None:
connection = await asyncpg.connect(DATABASE["url"])
try:
with pytest.raises(asyncpg.ForeignKeyViolationError):
with pytest.raises(IntegrityError) as failure:
async with sql_connection() as connection:
await connection.execute(
"INSERT INTO idempotency_keys "
"(chat_id, user_id, key, fingerprint, message_id, created_at) "
"VALUES (gen_random_uuid(), gen_random_uuid(), 'k-1', "
"sha256('x'), gen_random_uuid(), now())"
insert(IdempotencyKeyRow).values(
chat_id=uuid4(),
user_id=uuid4(),
key="k-1",
fingerprint=b"x" * 32,
message_id=uuid4(),
created_at=func.now(),
)
)
finally:
await connection.close()
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
async def test_failed_revision_rolls_back_ddl_and_version(
empty_database: str, tmp_path: Path
) -> None:
await upgrade(empty_database)
await seed(empty_database)
before = await contents(empty_database)
scripts = tmp_path / "alembic"
shutil.copytree(ROOT / "alembic", scripts, ignore=shutil.ignore_patterns("__pycache__"))
(scripts / "versions" / "0003_failure.py").write_text(
"from alembic import op\n"
"import sqlalchemy as sa\n"
"revision = '0003_failure'\n"
"down_revision = '0006_attachment_quarantine'\n"
"def upgrade():\n"
" op.create_table('must_rollback', sa.Column('id', sa.Integer, primary_key=True))\n"
" raise RuntimeError('migration failed')\n"
)
config = migration_config(empty_database)
config.set_main_option("script_location", str(scripts))
with pytest.raises(RuntimeError, match="migration failed"):
await asyncio.to_thread(command.upgrade, config, "head")
assert await revision(empty_database) == VERSIONS[-1]
assert await contents(empty_database) == before
async with sql_connection(empty_database) as connection:
assert not await connection.run_sync(lambda sync: inspect(sync).has_table("must_rollback"))
async def test_attachment_owner_must_be_member() -> None:
connection = await asyncpg.connect(DATABASE["url"])
try:
with pytest.raises(asyncpg.ForeignKeyViolationError, match="attachments_owner_fkey"):
with pytest.raises(IntegrityError, match="attachments_owner_fkey"):
async with sql_connection() as connection:
await connection.execute(
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, "
"size_bytes, sha256, width, height, object_key, status, created_at, updated_at) "
"VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'a.png', "
"'image/png', 1, repeat('0', 64), 1, 1, 'attachments/x', 'pending', now(), now())"
insert(AttachmentRow).values(
id=uuid4(),
chat_id=uuid4(),
owner_id=uuid4(),
filename="a.png",
content_type="image/png",
size_bytes=1,
sha256="0" * 64,
width=1,
height=1,
object_key="attachments/x",
status="pending",
created_at=func.now(),
updated_at=func.now(),
)
)
finally:
await connection.close()
async def test_message_links_only_attachments_of_its_chat() -> None:
user, chat_a, chat_b, attachment, message = (uuid4() for _ in range(5))
seed = [
(
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
"VALUES ($1, $2, 'A', '$argon2id$x', now())",
user,
f"u_{user.hex[:12]}",
),
("INSERT INTO chats (id, title, created_at) VALUES ($1, 'A', now())", chat_a),
("INSERT INTO chats (id, title, created_at) VALUES ($1, 'B', now())", chat_b),
(
"INSERT INTO chat_members (chat_id, user_id, position, chat_created_at) "
"VALUES ($1, $3, 1, now()), ($2, $3, 1, now())",
chat_a,
chat_b,
user,
),
(
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, "
"sha256, width, height, object_key, status, created_at, updated_at) VALUES ($1, $2, "
"$3, 'a.png', 'image/png', 1, repeat('0', 64), 1, 1, $4, 'ready', now(), now())",
attachment,
chat_a,
user,
f"attachments/{attachment}",
),
(
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
"VALUES ($1, $2, $3, '', now())",
message,
chat_b,
user,
),
]
connection = await asyncpg.connect(DATABASE["url"])
transaction = connection.transaction()
await transaction.start()
try:
for sql, *arguments in seed:
await connection.execute(sql, *arguments)
assert await connection.fetchval("SELECT text FROM messages WHERE id = $1", message) == ""
with pytest.raises(
asyncpg.ForeignKeyViolationError, match="message_attachments_attachment_fkey"
):
async def test_message_links_only_attachments_of_its_chat(empty_database: str) -> None:
await upgrade(empty_database)
await seed(empty_database)
with pytest.raises(IntegrityError, match="message_attachments_attachment_fkey"):
async with sql_connection(empty_database) as connection:
attachment = (await connection.execute(select(AttachmentRow.id))).scalar_one()
user = (await connection.execute(select(UserRow.id))).scalar_one()
chat, message = uuid4(), uuid4()
await connection.execute(
"INSERT INTO message_attachments (message_id, position, chat_id, attachment_id) "
"VALUES ($1, 0, $2, $3)",
message,
chat_b,
attachment,
insert(ChatRow).values(id=chat, title="Other", created_at=func.now())
)
await connection.execute(
insert(ChatMemberRow).values(
chat_id=chat, user_id=user, position=1, chat_created_at=func.now()
)
)
await connection.execute(
insert(MessageRow).values(
id=message, chat_id=chat, sender_id=user, text="", created_at=func.now()
)
)
assert (
await connection.scalar(select(MessageRow.text).where(MessageRow.id == message))
== ""
)
await connection.execute(
insert(MessageAttachmentRow).values(
message_id=message,
position=0,
chat_id=chat,
attachment_id=attachment,
)
)
finally:
await transaction.rollback()
await connection.close()
async def test_pipeline_tables_have_the_columns_the_suite_reads() -> None:
connection = await asyncpg.connect(DATABASE["url"])
try:
rows = await connection.fetch(
"SELECT table_name, column_name FROM information_schema.columns "
"WHERE table_schema = current_schema()"
)
finally:
await connection.close()
found: dict[str, set[str]] = {}
for row in rows:
found.setdefault(row["table_name"], set()).add(row["column_name"])
assert all(columns <= found.get(table, set()) for table, columns in PIPELINE_COLUMNS.items())
async def test_pipeline_tables_have_the_columns_the_suite_reads(empty_database: str) -> None:
await upgrade(empty_database)
async with sql_connection(empty_database) as connection:
for model in (JobRow, OutboxRow, VariantRow, JobEventRow):
columns = await connection.run_sync(
lambda sync, name=model.__tablename__: inspect(sync).get_columns(name)
)
assert {col["name"] for col in columns} == set(model.__table__.columns.keys())
async def test_one_variant_row_per_effect_key() -> None:
user, chat, attachment = uuid4(), uuid4(), uuid4()
variant = (
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, "
"content_type, size_bytes, width, height, sha256, created_at) "
"VALUES ($1, 1, 'thumbnail', $2, 'image/jpeg', 1, 1, 1, repeat('a', 64), now())"
)
connection = await asyncpg.connect(DATABASE["url"])
transaction = connection.transaction()
await transaction.start()
try:
await connection.execute(
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
"VALUES ($1, $2, 'A', '$argon2id$x', now())",
user,
f"u_{user.hex[:12]}",
)
await connection.execute(
"INSERT INTO chats (id, title, created_at) VALUES ($1, 'A', now())", chat
)
await connection.execute(
"INSERT INTO chat_members (chat_id, user_id, position, chat_created_at) "
"VALUES ($1, $2, 1, now())",
chat,
user,
)
await connection.execute(
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, "
"sha256, width, height, staging_key, status, created_at, updated_at) VALUES ($1, $2, "
"$3, 'a.png', 'image/png', 1, repeat('0', 64), 1, 1, $4, 'queued', now(), now())",
attachment,
chat,
user,
f"staging/{attachment}",
)
await connection.execute(variant, attachment, f"variants/{attachment}/1/a")
with pytest.raises(asyncpg.UniqueViolationError, match="attachment_variants_pkey"):
await connection.execute(variant, attachment, f"variants/{attachment}/1/b")
finally:
await transaction.rollback()
await connection.close()
async def test_one_variant_row_per_effect_key(empty_database: str) -> None:
await upgrade(empty_database)
await seed(empty_database)
async with sql_connection(empty_database) as connection:
row = (await connection.execute(select(VariantRow.__table__))).mappings().one()
duplicate = dict(row, object_key="variants/duplicate")
with pytest.raises(IntegrityError, match="attachment_variants_pkey"):
async with sql_connection(empty_database) as connection:
await connection.execute(insert(VariantRow).values(**duplicate))
+28 -1
View File
@@ -1,10 +1,20 @@
import json
import time
from collections.abc import AsyncIterator
from uuid import uuid4
from httpx import ASGITransport, AsyncClient
from conftest import PASSWORD, actor, keyed, make_chat, register, running_app, split_settings
from conftest import (
PASSWORD,
actor,
keyed,
make_chat,
new_user,
register,
running_app,
split_settings,
)
from messenger.main import create_app
MARKER_TEXT = "маркер-который-не-должен-попасть-в-логи-9f3a"
@@ -100,6 +110,23 @@ async def test_body_limit_returns_413() -> None:
assert response.json()["error"]["code"] == "payload_too_large"
async def test_chunked_body_is_limited_too() -> None:
async def chunks(body: bytes) -> AsyncIterator[bytes]:
for start in range(0, len(body), 1000):
yield body[start : start + 1000]
user = json.dumps(new_user("chunked")).encode()
async with running_app(max_body_bytes=4096) as http:
large = await http.post("/api/v1/users", content=chunks(b"x" * 5000))
small = await http.post(
"/api/v1/users", content=chunks(user), headers={"Content-Type": "application/json"}
)
assert "content-length" not in large.request.headers
assert large.status_code == 413
assert large.json()["error"]["code"] == "payload_too_large"
assert small.status_code == 201
async def test_ready_turns_unavailable_without_database() -> None:
async with running_app(database_url="postgresql://u:p@127.0.0.1:1/none") as http:
started = time.perf_counter()
+6 -5
View File
@@ -102,14 +102,15 @@ async def test_cursor_from_another_chat_is_rejected(client: AsyncClient) -> None
assert response.json()["error"]["code"] == "invalid_request"
@pytest.mark.parametrize("cursor", ["garbage", "1.2.3.4", "%20"])
@pytest.mark.parametrize("cursor", ["garbage", "1.2.3.4", "%20", ""])
async def test_broken_cursor_is_rejected(client: AsyncClient, cursor: str) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
response = await client.get(
f"/api/v1/chats/{chat['id']}/messages?cursor={cursor}", headers=actor(alice)
)
assert response.status_code == 400
await fill(client, chat, alice, 1)
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
response = await client.get(f"{path}?limit=1&cursor={cursor}", headers=actor(alice))
assert response.status_code == 400, f"{path}?cursor={cursor} → {response.status_code}"
assert response.json()["error"]["code"] == "invalid_request"
@pytest.mark.parametrize("limit", ["0", "-1", "101", "abc", "1.5", ""])
+4 -7
View File
@@ -4,12 +4,11 @@ import re
from typing import Any
from uuid import uuid4
import asyncpg
import pytest
from httpx import AsyncClient
from test_attachments import storage, trio, upload
from conftest import DATABASE, actor
from conftest import actor, sql_connection
from messenger.attachments.application.pipeline import TRANSIENT_ERROR
from messenger.attachments.application.ports import Rendition
from messenger.attachments.domain.errors import ImageTooDemanding
@@ -21,11 +20,9 @@ from pipeline import pipeline_of
async def rows(sql: str, *args: Any) -> list[dict[str, Any]]:
connection = await asyncpg.connect(DATABASE["url"])
try:
return [dict(row) for row in await connection.fetch(sql, *args)]
finally:
await connection.close()
async with sql_connection() as connection:
result = await connection.exec_driver_sql(sql, args)
return [dict(row) for row in result.mappings()] if result.returns_rows else []
async def accepted(http: AsyncClient) -> tuple[dict[str, Any], dict[str, Any], str]:
+210 -5
View File
@@ -1,6 +1,38 @@
import time
from dataclasses import replace
from datetime import UTC, datetime, timedelta
from uuid import UUID, uuid4
from conftest import actor, register, resolve, running_app
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
@@ -8,7 +40,8 @@ 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.connection():
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
@@ -22,6 +55,178 @@ async def test_exhausted_pool_answers_503_in_bounded_time() -> None:
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.connection() as connection:
assert await connection.fetchval("SHOW statement_timeout") == "1500ms"
assert await connection.fetchval("SHOW lock_timeout") == "1500ms"
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
+432
View File
@@ -0,0 +1,432 @@
import asyncio
import hashlib
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Any
from uuid import UUID, uuid4
import pytest
from httpx import AsyncClient
from sqlalchemy import make_url
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.pool import NullPool
from test_attachments import storage, trio, upload
from conftest import actor, keyed, running_app, upgrade
from fakes import MemoryObjectStorage, NullLogger, RecordingPublisher
from messenger.attachments.application.commands import ReconcileStorage
from messenger.attachments.application.reconcile import Reconciliation, StorageReconciler
from messenger.attachments.domain.events import AttachmentDiscarded
from messenger.attachments.entrypoints import reconcile as entrypoint
from messenger.attachments.entrypoints.reconcile import LOCK_KEY
from messenger.attachments.infrastructure.postgres import (
PostgresAttachmentsUnitOfWork,
PostgresSingleRun,
)
from messenger.shared.application.errors import Unavailable
from messenger.shared.infrastructure.clock import MonotonicUtcClock
from messenger.shared.infrastructure.postgres import Database
from pictures import SAMPLE
from pipeline import settle
GRACE = timedelta(seconds=60)
OLD = timedelta(hours=2)
AGED_PENDING = """UPDATE attachments SET status = 'pending', staging_key = object_key,
original_key = NULL, updated_at = created_at,
created_at = created_at - interval '2 hours' WHERE id = $1"""
LATE_ROW = """INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes,
sha256, width, height, object_key, staging_key, status, created_at, updated_at)
SELECT gen_random_uuid(), chat_id, owner_id, 'late.png', content_type, size_bytes, sha256,
width, height, $2, $2, 'pending', now(), now()
FROM attachments WHERE id = $1"""
@pytest.fixture
def dsn(database: str) -> str:
name = f"reconcile_{uuid4().hex[:12]}"
async def create() -> None:
engine = create_async_engine(
make_url(database).set(drivername="postgresql+asyncpg"),
isolation_level="AUTOCOMMIT",
poolclass=NullPool,
)
try:
async with engine.connect() as connection:
await connection.exec_driver_sql(f"CREATE DATABASE {name}")
finally:
await engine.dispose()
await upgrade(target)
target = f"{database.rsplit('/', 1)[0]}/{name}"
asyncio.run(create())
return target
@dataclass(slots=True)
class Stand:
http: AsyncClient
store: MemoryObjectStorage
database: Database
users: tuple[dict[str, Any], ...]
published: RecordingPublisher
async def run(self, *, apply: bool = False, deep: bool = False) -> Reconciliation:
reconciler = StorageReconciler(
lambda: PostgresAttachmentsUnitOfWork(self.database),
self.store,
PostgresSingleRun(self.database, LOCK_KEY),
MonotonicUtcClock(),
logger=NullLogger(),
publisher=self.published,
)
command = ReconcileStorage(
apply=apply, grace=GRACE, skew=timedelta(0), deep=deep, page_size=2
)
return await reconciler(command)
async def sql(self, query: str, *args: Any) -> Any:
async with self.database.session() as session:
connection = await session.connection()
result = await connection.exec_driver_sql(query, args)
rows = result.mappings().all() if result.returns_rows else []
await session.commit()
return rows
async def upload(self) -> dict[str, Any]:
alice, _, _, chat = self.users
response = await upload(self.http, alice, chat)
assert response.status_code == 202, response.text
attachment = response.json()
legacy_key = key(attachment)
staging_key = f"staging/{attachment['id']}"
self.store.objects[legacy_key] = self.store.objects.pop(staging_key)
self.store.modified[legacy_key] = self.store.modified.pop(staging_key)
await self.sql(
"DELETE FROM outbox WHERE job_id IN (SELECT job_id FROM jobs WHERE attachment_id = $1)",
attachment["id"],
)
await self.sql("DELETE FROM jobs WHERE attachment_id = $1", attachment["id"])
await self.sql(
"UPDATE attachments SET status = 'ready', object_key = $2, original_key = $2, "
"staging_key = NULL, published_version = 1 WHERE id = $1",
attachment["id"],
legacy_key,
)
return attachment
def age(self, key: str) -> None:
self.store.modified[key] = datetime.now(UTC) - OLD
def state(self) -> dict[str, bytes]:
return {key: data for key, (data, _) in self.store.objects.items()}
@asynccontextmanager
async def stand(dsn: str) -> AsyncIterator[Stand]:
async with running_app(database_url=dsn) as http:
database = Database(
dsn, max_size=12, connect_timeout=2, acquire_timeout=2, command_timeout=5
)
await database.open()
try:
yield Stand(http, await storage(http), database, await trio(http), RecordingPublisher())
finally:
await database.close()
def key(attachment: dict[str, Any]) -> str:
return f"attachments/{attachment['id']}"
async def damage(s: Stand) -> dict[str, Any]:
alice, _, _, chat = s.users
healthy, missing, sized, flipped, stale, fresh = [await s.upload() for _ in range(6)]
posted = await s.http.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "", "attachment_ids": [missing["id"]]},
headers=keyed(alice),
)
assert posted.status_code == 201, posted.text
del s.store.objects[key(missing)]
s.store.objects[key(sized)] = (SAMPLE[:100], "image/png")
s.store.objects[key(flipped)] = (SAMPLE[::-1], "image/png")
await s.sql(AGED_PENDING, stale["id"])
await s.sql(
"UPDATE attachments SET status = 'pending', staging_key = object_key, "
"original_key = NULL WHERE id = $1",
fresh["id"],
)
orphan, newborn = f"attachments/{uuid4()}", f"attachments/{uuid4()}"
s.store.objects[orphan] = s.store.objects[newborn] = (SAMPLE, "image/png")
s.store.modified[newborn] = datetime.now(UTC)
s.age(orphan)
return {
"healthy": healthy,
"missing": missing,
"sized": sized,
"flipped": flipped,
"stale": stale,
"fresh": fresh,
"orphan": orphan,
"newborn": newborn,
"message": posted.json(),
}
EVERY_CLASS = {
"orphan_stale": 1,
"orphan_fresh": 1,
"missing": 1,
"size_mismatch": 1,
"sha_mismatch": 1,
"pending_stale": 1,
"pending_fresh": 1,
}
async def test_dry_run_reports_every_class_and_changes_nothing(dsn: str) -> None:
async with stand(dsn) as s:
await damage(s)
objects = s.state()
rows = await s.sql("SELECT id, status, quarantine_reason FROM attachments ORDER BY id")
shallow = await s.run()
deep = await s.run(deep=True)
assert s.state() == objects
assert (
await s.sql("SELECT id, status, quarantine_reason FROM attachments ORDER BY id") == rows
)
assert dict(deep.found) == EVERY_CLASS
assert dict(shallow.found) == {k: v for k, v in EVERY_CLASS.items() if k != "sha_mismatch"}
assert not deep.fixed
assert not shallow.fixed
assert shallow.requests == {"s3_list": 4, "sql": 3}
assert deep.requests["s3_get"] == 2
async def test_apply_fixes_what_it_found_and_repeats_as_noop(dsn: str) -> None:
async with stand(dsn) as s:
damaged = await damage(s)
alice, bob, _, chat = s.users
first = await s.run(apply=True, deep=True)
second = await s.run(apply=True, deep=True)
reasons = {
str(row["id"]): row["quarantine_reason"]
for row in await s.sql("SELECT id, quarantine_reason FROM attachments")
}
history = await s.http.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(bob))
meta = await s.http.get(
f"/api/v1/attachments/{damaged['flipped']['id']}", headers=actor(bob)
)
broken = await s.http.get(
f"/api/v1/attachments/{damaged['flipped']['id']}/content", headers=actor(bob)
)
intact = await s.http.get(
f"/api/v1/attachments/{damaged['healthy']['id']}/content", headers=actor(alice)
)
objects = s.state()
assert {name: first.fixed[name] for name in EVERY_CLASS} == {
**EVERY_CLASS,
"orphan_fresh": 0,
"pending_fresh": 0,
}
assert not second.fixed
assert dict(second.found) == {"orphan_fresh": 1, "pending_fresh": 1, "quarantined": 3}
assert reasons[damaged["missing"]["id"]] == "missing"
assert reasons[damaged["sized"]["id"]] == "size_mismatch"
assert reasons[damaged["flipped"]["id"]] == "sha_mismatch"
assert reasons[damaged["healthy"]["id"]] is None
assert [
(event.attachment_id, event.reason)
for event in s.published.events
if isinstance(event, AttachmentDiscarded)
] == [(UUID(damaged["stale"]["id"]), "reconcile")]
assert reasons[damaged["fresh"]["id"]] is None
assert damaged["stale"]["id"] not in reasons
assert key(damaged["stale"]) not in objects
assert damaged["orphan"] not in objects
assert damaged["newborn"] in objects
assert key(damaged["flipped"]) in objects
assert history.json()["items"][0]["attachment_ids"] == [damaged["missing"]["id"]]
assert meta.status_code == 200
assert meta.json()["sha256"] == damaged["flipped"]["sha256"]
assert broken.status_code == 404
assert broken.json()["error"]["code"] == "not_found"
assert intact.status_code == 200
assert intact.content == SAMPLE
async def test_restored_object_leaves_quarantine(dsn: str) -> None:
async with stand(dsn) as s:
_, bob, _, _ = s.users
lost, flipped = await s.upload(), await s.upload()
del s.store.objects[key(lost)]
s.store.objects[key(flipped)] = (SAMPLE[::-1], "image/png")
isolated = await s.run(apply=True, deep=True)
s.store.objects[key(lost)] = s.store.objects[key(flipped)] = (SAMPLE, "image/png")
s.store.modified[key(lost)] = s.store.modified[key(flipped)]
shallow = await s.run(apply=True)
again = await s.run(apply=True)
content = await s.http.get(f"/api/v1/attachments/{lost['id']}/content", headers=actor(bob))
assert isolated.fixed["missing"] == isolated.fixed["sha_mismatch"] == 1
assert shallow.fixed["healed"] == 2
assert shallow.requests["s3_get"] == 2
assert not again.fixed
assert again.requests["s3_get"] == 0
assert hashlib.sha256(content.content).hexdigest() == lost["sha256"]
async def test_other_bytes_of_the_same_length_keep_the_quarantine(dsn: str) -> None:
async with stand(dsn) as s:
_, bob, _, _ = s.users
lost = await s.upload()
del s.store.objects[key(lost)]
isolated = await s.run(apply=True)
s.store.objects[key(lost)] = (bytes(len(SAMPLE)), "image/png")
s.age(key(lost))
shallow = await s.run(apply=True)
content = await s.http.get(f"/api/v1/attachments/{lost['id']}/content", headers=actor(bob))
reason = await s.sql("SELECT quarantine_reason FROM attachments WHERE id = $1", lost["id"])
assert isolated.fixed["missing"] == 1
assert not shallow.fixed
assert shallow.found["quarantined"] == 1
assert shallow.requests["s3_get"] == 1
assert content.status_code == 404
assert reason[0]["quarantine_reason"] == "missing"
async def test_pages_of_rows_are_not_followed_by_an_empty_one(dsn: str) -> None:
async with stand(dsn) as s:
empty = await s.run()
for _ in range(4):
await s.upload()
full = await s.run()
assert (empty.rows, empty.requests["sql"]) == (0, 1)
assert (full.rows, full.requests["sql"]) == (4, 2)
def test_any_pass_failure_ends_as_reconcile_failed(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
async def broken(*_args: Any) -> Reconciliation:
cancelled = TimeoutError("statement timeout")
raise ExceptionGroup("pass", [cancelled])
monkeypatch.setattr(entrypoint, "reconcile", broken)
for name, value in {
"DATABASE_URL": "postgresql://unused@127.0.0.1:1/unused",
"S3_ACCESS_KEY_ID": "reconciler",
"S3_SECRET_ACCESS_KEY": "reconciler-secret",
}.items():
monkeypatch.setenv(name, value)
with pytest.raises(SystemExit) as stopped:
entrypoint.main(["--apply"])
captured = capsys.readouterr()
assert stopped.value.code == 1
assert captured.out == ""
assert "reconcile.failed" in captured.err
assert "TimeoutError" in captured.err
assert "Traceback" not in captured.err
async def test_row_written_after_listing_keeps_the_object(dsn: str) -> None:
async with stand(dsn) as s:
first, last = await s.upload(), await s.upload()
fresh, late = f"{key(first)}-a", f"{key(first)}-b"
for name in (fresh, late):
s.store.objects[name] = (SAMPLE, "image/png")
s.store.modified[name] = datetime.now(UTC)
s.age(late)
async def row_appears() -> None:
s.store.after_page = None
await s.sql(LATE_ROW, first["id"], late)
s.store.after_page = row_appears
report = await s.run(apply=True)
objects = s.state()
assert key(first) < fresh < late < key(last)
assert report.found["orphan_stale"] == 1
assert report.rechecked["orphan_stale"] == 1
assert not report.fixed
assert late in objects
async def test_second_pass_is_skipped_while_one_runs(dsn: str) -> None:
async with stand(dsn) as s:
orphan = f"attachments/{uuid4()}"
s.store.objects[orphan] = (SAMPLE, "image/png")
s.age(orphan)
async with PostgresSingleRun(s.database, LOCK_KEY).hold() as held:
busy = await s.run(apply=True)
free = await s.run(apply=True)
assert held
assert busy.skipped
assert not busy.found
assert not free.skipped
assert free.fixed["orphan_stale"] == 1
async def test_storage_failure_mid_pass_ends_it_as_unavailable(dsn: str) -> None:
async with stand(dsn) as s:
await damage(s)
async def broken() -> None:
raise Unavailable("S3 недоступно") from TimeoutError()
s.store.after_page = broken
with pytest.raises(Unavailable) as failed:
await s.run(apply=True, deep=True)
assert isinstance(failed.value.__cause__, TimeoutError)
async def test_cancelled_pass_releases_its_autocommit_lock(dsn: str) -> None:
async with stand(dsn) as s:
entered = asyncio.Event()
async def hold() -> None:
async with PostgresSingleRun(s.database, LOCK_KEY).hold() as held:
assert held
entered.set()
await asyncio.Event().wait()
task = asyncio.create_task(hold())
try:
await asyncio.wait_for(entered.wait(), 2)
states = await s.sql(
"SELECT a.state FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid "
"WHERE l.locktype = 'advisory' AND l.objid = $1",
LOCK_KEY,
)
assert [row["state"] for row in states] == ["idle"]
finally:
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
locks = await s.sql(
"SELECT count(*) AS total FROM pg_locks WHERE locktype = 'advisory' AND objid = $1",
LOCK_KEY,
)
assert locks[0]["total"] == 0
async def test_legacy_reconciler_does_not_touch_pipeline_objects(dsn: str) -> None:
async with stand(dsn) as s:
alice, _, _, chat = s.users
response = await upload(s.http, alice, chat)
assert response.status_code == 202
await settle(s.http)
before = s.state()
assert {key.split("/", 1)[0] for key in before} == {"staging", "originals", "variants"}
for object_key in before:
s.age(object_key)
report = await s.run(apply=True, deep=True)
assert report.rows == report.objects == 0
assert not report.fixed and not report.errors
assert s.state() == before
content = await s.http.get(
f"/api/v1/attachments/{response.json()['id']}/content", headers=actor(alice)
)
assert content.status_code == 200 and content.content == SAMPLE
+10 -7
View File
@@ -1,8 +1,11 @@
import asyncio
from datetime import datetime, timedelta
from hashlib import sha256
from uuid import UUID
import pytest
from httpx import AsyncClient
from sqlalchemy import func, select
from conftest import (
PASSWORD,
@@ -16,6 +19,7 @@ from conftest import (
running_app,
scalar,
)
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
BASIC = 'Basic realm="messenger", charset="UTF-8"'
BEARER = 'Bearer realm="messenger"'
@@ -52,7 +56,7 @@ async def test_registration_response_hides_password(client: AsyncClient) -> None
async def test_password_is_stored_as_argon2id(client: AsyncClient) -> None:
alice = await register(client, "alice")
stored = await scalar("SELECT password_hash FROM users WHERE id = $1::uuid", alice["id"])
stored = await scalar(select(UserRow.password_hash).where(UserRow.id == UUID(alice["id"])))
assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
assert PASSWORD not in stored
@@ -60,10 +64,9 @@ async def test_password_is_stored_as_argon2id(client: AsyncClient) -> None:
async def test_session_stores_only_token_digest(client: AsyncClient) -> None:
alice = await register(client, "alice")
token = actor(alice)["Authorization"].split()[1]
sql = "SELECT count(*) FROM sessions WHERE token_hash = sha256(convert_to($1, 'UTF8'))"
assert await scalar(sql, token) == 1
raw = "SELECT count(*) FROM sessions WHERE encode(token_hash, 'escape') = $1"
assert await scalar(raw, token) == 0
rows = select(func.count()).select_from(SessionRow)
assert await scalar(rows.where(SessionRow.token_hash == sha256(token.encode()).digest())) == 1
assert await scalar(rows.where(SessionRow.token_hash == token.encode())) == 0
async def test_wrong_password_and_unknown_user_look_the_same(client: AsyncClient) -> None:
@@ -154,8 +157,8 @@ async def test_expired_sessions_are_purged_on_next_login() -> None:
await login(client, body["username"])
await asyncio.sleep(1.2)
await login(client, body["username"])
sql = "SELECT count(*) FROM sessions WHERE user_id = $1::uuid"
assert await scalar(sql, user["id"]) == 1
sql = select(func.count()).select_from(SessionRow).where(SessionRow.user_id == UUID(user["id"]))
assert await scalar(sql) == 1
async def test_chat_routes_require_bearer(client: AsyncClient) -> None:
+52 -1
View File
@@ -4,10 +4,14 @@ from contextlib import asynccontextmanager
from httpx import AsyncClient
from conftest import keyed, make_chat, register, resolve, running_app
from conftest import actor, keyed, make_chat, register, resolve, running_app, scalar
from fakes import MemoryObjectStorage
from messenger.attachments.application.ports import ObjectStorage
from messenger.messaging.application import handlers
from messenger.messaging.domain.events import MessagePosted
from messenger.shared.application.messagebus import EventBus
from pictures import SAMPLE, png
from pipeline import settle
MARKER = "текст-который-не-должен-утечь-при-таймауте"
@@ -95,3 +99,50 @@ async def test_healthcheck_stays_fast(client: AsyncClient) -> None:
started = loop.time()
assert (await client.get("/health/live")).status_code == 200
assert loop.time() - started < 1.0
async def trickled(data: bytes, size: int, delay: float) -> AsyncIterator[bytes]:
for start in range(0, len(data), size):
await asyncio.sleep(delay)
yield data[start : start + size]
async def upload(client: AsyncClient, user: dict, chat: dict, body: AsyncIterator[bytes]):
return await client.post(
f"/api/v1/chats/{chat['id']}/attachments?filename=slow.png",
content=body,
headers={**actor(user), "Content-Type": "image/png"},
)
async def test_steady_slow_transfer_outlives_the_request_timeout() -> None:
picture = png(16, 16, size=1 << 20)
async with running_app(request_timeout_seconds=0.4, min_transfer_rate_bytes=16_384) as client:
alice, chat = await prepared(client)
loop = asyncio.get_running_loop()
started = loop.time()
uploaded = await upload(client, alice, chat, trickled(picture, 65_536, 0.1))
assert uploaded.status_code == 202, uploaded.text
assert loop.time() - started > 1.0
await settle(client)
store = await resolve(client, ObjectStorage)
assert isinstance(store, MemoryObjectStorage)
store.delay = 0.1
started = loop.time()
content = await client.get(
f"/api/v1/attachments/{uploaded.json()['id']}/content", headers=actor(alice)
)
assert (content.status_code, content.content) == (200, picture)
assert loop.time() - started > 1.0
async def test_body_slower_than_the_minimal_rate_is_cut() -> None:
async with running_app(request_timeout_seconds=0.3, min_transfer_rate_bytes=1 << 20) as client:
alice, chat = await prepared(client)
before = await scalar("SELECT count(*) FROM attachments")
loop = asyncio.get_running_loop()
started = loop.time()
response = await upload(client, alice, chat, trickled(SAMPLE, 4_096, 0.1))
assert (response.status_code, response.json()["error"]["code"]) == (503, "unavailable")
assert loop.time() - started < 1.0
assert await scalar("SELECT count(*) FROM attachments") == before
+21 -20
View File
@@ -3,12 +3,11 @@ from collections.abc import AsyncIterator
from typing import Any
from uuid import uuid4
import asyncpg
from httpx import AsyncClient
from starlette.types import Message
from test_attachments import storage, trio, upload
from conftest import APPS, DATABASE, actor, keyed, resolve, running_app, scalar
from conftest import APPS, actor, keyed, resolve, running_app, scalar, sql_connection
from messenger.attachments.domain.events import AttachmentDiscarded
from messenger.attachments.entrypoints.sweeper import UploadSweeper
from messenger.shared.application.messagebus import EventBus
@@ -19,27 +18,27 @@ AGED = "UPDATE attachments SET created_at = created_at - interval '1 hour' WHERE
async def execute(sql: str, *args: Any) -> None:
connection = await asyncpg.connect(DATABASE["url"])
try:
await connection.execute(sql, *args)
finally:
await connection.close()
async with sql_connection() as connection:
await connection.exec_driver_sql(sql, args)
def sweeper(http: AsyncClient) -> UploadSweeper:
return APPS[id(http)].state.sweeper
async def discarded(http: AsyncClient) -> list[AttachmentDiscarded]:
seen: list[AttachmentDiscarded] = []
async def keep(event: AttachmentDiscarded) -> None:
seen.append(event)
(await resolve(http, EventBus)).project(AttachmentDiscarded, keep)
async def discarded(http: AsyncClient) -> asyncio.Queue[AttachmentDiscarded]:
seen: asyncio.Queue[AttachmentDiscarded] = asyncio.Queue()
(await resolve(http, EventBus)).subscribe(AttachmentDiscarded, seen.put)
return seen
async def delivered(seen: asyncio.Queue[AttachmentDiscarded], count: int) -> list[str]:
async with asyncio.timeout(2):
events = [await seen.get() for _ in range(count)]
assert seen.empty()
return sorted(f"{event.reason} {event.attachment_id}" for event in events)
async def intent(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
store = await storage(http)
store.failing = True
@@ -67,15 +66,18 @@ async def test_commit_failure_after_put_is_compensated(client: AsyncClient) -> N
trigger = f"lab4_fail_{uuid4().hex[:8]}"
await execute(
f"""CREATE FUNCTION {trigger}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'injected' USING ERRCODE = '55P03'; END $$;
CREATE TRIGGER {trigger} BEFORE UPDATE ON attachments FOR EACH ROW
BEGIN RAISE EXCEPTION 'injected' USING ERRCODE = '55P03'; END $$"""
)
await execute(
f"""CREATE TRIGGER {trigger} BEFORE UPDATE ON attachments FOR EACH ROW
WHEN (NEW.filename = '{name}' AND NEW.status = 'queued') EXECUTE FUNCTION {trigger}()"""
)
before, seen = set(store.objects), await discarded(client)
try:
response = await upload(client, alice, chat, filename=name)
finally:
await execute(f"DROP TRIGGER {trigger} ON attachments; DROP FUNCTION {trigger}()")
await execute(f"DROP TRIGGER {trigger} ON attachments")
await execute(f"DROP FUNCTION {trigger}()")
assert response.status_code == 503
assert response.json()["error"]["code"] == "unavailable"
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
@@ -88,7 +90,7 @@ async def test_commit_failure_after_put_is_compensated(client: AsyncClient) -> N
== 0
)
assert set(store.objects) == before
assert [event.reason for event in seen] == ["compensation"]
assert [event.split()[0] for event in await delivered(seen, 1)] == ["compensation"]
async def test_lost_intent_gives_503_and_no_object(client: AsyncClient) -> None:
@@ -152,8 +154,7 @@ async def test_parallel_sweeps_share_the_work(client: AsyncClient) -> None:
seen = await discarded(client)
first, second = await asyncio.gather(sweeper(client).sweep(), sweeper(client).sweep())
assert first + second == 5
assert sorted(str(event.attachment_id) for event in seen) == sorted(pending)
assert {event.reason for event in seen} == {"abandoned"}
assert await delivered(seen, 5) == sorted(f"abandoned {item}" for item in pending)
assert await sweeper(client).sweep() == 0
objects = (await storage(client)).objects
assert not any(f"staging/{attachment_id}" in objects for attachment_id in pending)
+57 -15
View File
@@ -1,5 +1,6 @@
import asyncio
import re
import socket
import subprocess
import time
from base64 import b64encode
@@ -9,19 +10,23 @@ from pathlib import Path
from typing import Any
from uuid import uuid4
import asyncpg
import pytest
from alembic import command
from alembic.config import Config
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
from sqlalchemy import make_url
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
from sqlalchemy.pool import NullPool
from fakes import MemoryStorageProvider
from messenger.attachments.config import AttachmentsSettings
from messenger.identity.config import IdentitySettings
from messenger.main import create_app
from messenger.messaging.config import MessagingSettings
from messenger.migrate import migrate
from messenger.shared.config import PlatformSettings
from messenger.shared.entrypoints.config import TransportSettings
from messenger.shared.infrastructure.postgres import unavailable
ROOT = Path(__file__).resolve().parents[1]
POSTGRES_IMAGE = re.compile(r"image: (postgres:\S+)")
@@ -38,18 +43,53 @@ def docker(*args: str) -> str:
return done.stdout.strip()
def migration_config(dsn: str) -> Config:
config = Config(str(ROOT / "alembic.ini"))
config.attributes["database_url"] = dsn
return config
async def upgrade(dsn: str, revision: str = "head") -> None:
await asyncio.to_thread(command.upgrade, migration_config(dsn), revision)
async def migrated(dsn: str) -> None:
deadline = time.monotonic() + STARTUP_SECONDS
while True:
try:
await migrate(dsn)
await upgrade(dsn)
return
except OSError, asyncpg.PostgresError, asyncpg.InterfaceError:
if time.monotonic() > deadline:
except Exception as error:
if not unavailable(error) or time.monotonic() > deadline:
raise
await asyncio.sleep(0.5)
@asynccontextmanager
async def sql_connection(dsn: str | None = None) -> AsyncIterator[AsyncConnection]:
engine = create_async_engine(
make_url(dsn or DATABASE["url"]).set(drivername="postgresql+asyncpg"),
poolclass=NullPool,
hide_parameters=True,
)
try:
async with engine.begin() as connection:
yield connection
finally:
await engine.dispose()
def free_port() -> int:
for port in range(25000, 26000):
with socket.socket() as probe:
try:
probe.bind(("127.0.0.1", port))
return port
except OSError:
continue
raise RuntimeError("No free test port in 25000–25999")
@pytest.fixture(autouse=True)
def database_for_api(request: pytest.FixtureRequest) -> None:
if "api" in request.node.path.parts:
@@ -78,7 +118,7 @@ def answering(name: str, *probe: str) -> bool:
@pytest.fixture(scope="session")
def valkey() -> Iterator[dict[str, str]]:
name = f"mtusi-lab5-test-valkey-{uuid4().hex[:8]}"
container(name, "-p", "127.0.0.1::6379", image(VALKEY_IMAGE))
container(name, "-p", f"127.0.0.1:{free_port()}:6379", image(VALKEY_IMAGE))
try:
deadline = time.monotonic() + STARTUP_SECONDS
while not answering(name, "valkey-cli", "ping"):
@@ -86,7 +126,7 @@ def valkey() -> Iterator[dict[str, str]]:
time.sleep(0.2)
yield {"name": name, "url": f"redis://127.0.0.1:{published(name, 6379)}/0"}
finally:
subprocess.run(["docker", "rm", "-f", name], capture_output=True, check=False)
subprocess.run(["docker", "rm", "-fv", name], capture_output=True, check=False)
@pytest.fixture(scope="session")
@@ -94,14 +134,16 @@ def database() -> Iterator[str]:
name = f"mtusi-lab5-test-{uuid4().hex[:8]}"
tuning = ["-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off"]
environment = ["-e", "POSTGRES_PASSWORD=test", "-e", "POSTGRES_DB=messenger"]
container(name, *environment, "-p", "127.0.0.1::5432", image(POSTGRES_IMAGE), *tuning)
container(
name, *environment, "-p", f"127.0.0.1:{free_port()}:5432", image(POSTGRES_IMAGE), *tuning
)
try:
dsn = f"postgresql://postgres:test@127.0.0.1:{published(name, 5432)}/messenger"
asyncio.run(migrated(dsn))
DATABASE["url"] = dsn
yield dsn
finally:
subprocess.run(["docker", "rm", "-f", name], capture_output=True, check=False)
subprocess.run(["docker", "rm", "-fv", name], capture_output=True, check=False)
def split_settings(**overrides: Any) -> dict[str, Any]:
@@ -152,12 +194,12 @@ async def client() -> AsyncIterator[AsyncClient]:
yield http
async def scalar(sql: str, *args: Any) -> Any:
connection = await asyncpg.connect(DATABASE["url"])
try:
return await connection.fetchval(sql, *args)
finally:
await connection.close()
async def scalar(statement: Any, *args: Any) -> Any:
async with sql_connection() as connection:
if isinstance(statement, str):
result = await connection.exec_driver_sql(statement, args)
return result.scalar() if result.returns_rows else None
return await connection.scalar(statement)
def basic(username: str, password: str) -> dict[str, str]:
+38 -6
View File
@@ -1,11 +1,12 @@
from collections.abc import AsyncIterator, Awaitable, Callable
from datetime import datetime, timedelta
import asyncio
from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
from datetime import UTC, datetime, timedelta
from typing import Any
from dishka import Provider, Scope, provide
from messenger.attachments.application.errors import ObjectMissingError
from messenger.attachments.application.ports import ObjectContent, ObjectStorage
from messenger.attachments.application.ports import ObjectContent, ObjectStorage, StoredObject
from messenger.shared.application.errors import Unavailable
@@ -30,33 +31,53 @@ class FrozenClock:
return self._current
async def pieces(data: bytes, size: int = 65_536) -> AsyncIterator[bytes]:
async def pieces(data: bytes, size: int = 65_536, delay: float = 0.0) -> AsyncIterator[bytes]:
for start in range(0, len(data), size):
await asyncio.sleep(delay)
yield data[start : start + size]
class MemoryObjectStorage:
__slots__ = ("after_put", "failing", "objects")
__slots__ = ("after_page", "after_put", "delay", "failing", "modified", "objects")
def __init__(self) -> None:
self.objects: dict[str, tuple[bytes, str]] = {}
self.modified: dict[str, datetime] = {}
self.failing = False
self.delay = 0.0
self.after_put: Callable[[str], Awaitable[None]] | None = None
self.after_page: Callable[[], Awaitable[None]] | None = None
async def put(self, key: str, data: bytes, content_type: str) -> None:
if self.failing:
raise Unavailable("S3 недоступно")
self.objects[key] = (bytes(data), content_type)
self.modified[key] = datetime.now(UTC)
if self.after_put is not None:
await self.after_put(key)
async def listing(self, prefix: str, page_size: int) -> AsyncIterator[Sequence[StoredObject]]:
if self.failing:
raise Unavailable("S3 недоступно")
keys = sorted(key for key in self.objects if key.startswith(prefix))
for start in range(0, len(keys), page_size):
yield [self._stored(key) for key in keys[start : start + page_size]]
if self.after_page is not None:
await self.after_page()
async def stat(self, key: str) -> StoredObject | None:
return self._stored(key) if key in self.objects else None
def _stored(self, key: str) -> StoredObject:
return StoredObject(key, len(self.objects[key][0]), self.modified[key])
async def open(self, key: str) -> ObjectContent:
if self.failing:
raise Unavailable("S3 недоступно")
if key not in self.objects:
raise ObjectMissingError(key)
data = self.objects[key][0]
return ObjectContent(size=len(data), chunks=pieces(data))
return ObjectContent(size=len(data), chunks=pieces(data, delay=self.delay))
async def read(self, key: str) -> bytes:
content = await self.open(key)
@@ -73,9 +94,20 @@ class MemoryObjectStorage:
if self.failing:
raise Unavailable("S3 недоступно")
self.objects.pop(key, None)
self.modified.pop(key, None)
class MemoryStorageProvider(Provider):
@provide(scope=Scope.APP)
def storage(self) -> ObjectStorage:
return MemoryObjectStorage()
class RecordingPublisher:
__slots__ = ("events",)
def __init__(self) -> None:
self.events: list[Any] = []
async def publish(self, events: Sequence[Any]) -> None:
self.events.extend(events)
@@ -0,0 +1,46 @@
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL CONSTRAINT users_username_key UNIQUE
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
password_hash text NOT NULL CHECK (password_hash LIKE '$argon2id$%'),
created_at timestamptz NOT NULL
);
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32),
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
created_at timestamptz NOT NULL,
expires_at timestamptz NOT NULL,
CHECK (expires_at > created_at)
);
CREATE INDEX sessions_user_idx ON sessions (user_id);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
created_at timestamptz NOT NULL,
last_message_at timestamptz
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id),
position smallint NOT NULL CHECK (position BETWEEN 1 AND 100),
chat_created_at timestamptz NOT NULL,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_created_at, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
created_at timestamptz NOT NULL,
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
);
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
@@ -0,0 +1,10 @@
CREATE TABLE idempotency_keys (
chat_id uuid NOT NULL,
user_id uuid NOT NULL,
key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
fingerprint bytea NOT NULL CHECK (octet_length(fingerprint) = 32),
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
created_at timestamptz NOT NULL,
PRIMARY KEY (chat_id, user_id, key),
FOREIGN KEY (chat_id, user_id) REFERENCES chat_members (chat_id, user_id)
);
@@ -0,0 +1,37 @@
ALTER TABLE messages
DROP CONSTRAINT messages_text_check,
ADD CONSTRAINT messages_text_check CHECK (char_length(text) <= 4000);
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
owner_id uuid NOT NULL,
filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
width integer NOT NULL CHECK (width > 0),
height integer NOT NULL CHECK (height > 0),
object_key text COLLATE "C" NOT NULL CONSTRAINT attachments_object_key_key UNIQUE,
status text NOT NULL CHECK (status IN ('pending', 'ready')),
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT attachments_chat_key UNIQUE (id, chat_id),
CONSTRAINT attachments_owner_fkey FOREIGN KEY (chat_id, owner_id)
REFERENCES chat_members (chat_id, user_id)
);
CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE status = 'pending';
CREATE TABLE message_attachments (
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
position smallint NOT NULL CHECK (position BETWEEN 0 AND 9),
chat_id uuid NOT NULL,
attachment_id uuid NOT NULL,
PRIMARY KEY (message_id, position),
UNIQUE (message_id, attachment_id),
CONSTRAINT message_attachments_attachment_fkey FOREIGN KEY (attachment_id, chat_id)
REFERENCES attachments (id, chat_id) ON DELETE RESTRICT
);
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);
@@ -0,0 +1,70 @@
ALTER TABLE attachments
DROP CONSTRAINT attachments_status_check,
ADD CONSTRAINT attachments_status_check
CHECK (status IN ('pending', 'queued', 'processing', 'ready', 'failed')),
ADD COLUMN staging_key text COLLATE "C" CONSTRAINT attachments_staging_key_key UNIQUE,
ADD COLUMN original_key text COLLATE "C" CONSTRAINT attachments_original_key_key UNIQUE,
ADD COLUMN published_version integer NOT NULL DEFAULT 0 CHECK (published_version >= 0),
ADD COLUMN error_code text
CHECK (error_code IN ('invalid_image', 'processing_failed', 'retry_exhausted')),
ALTER COLUMN object_key DROP NOT NULL;
UPDATE attachments SET original_key = object_key, published_version = 1 WHERE status = 'ready';
UPDATE attachments SET staging_key = object_key WHERE status = 'pending';
CREATE INDEX attachments_staged_idx ON attachments (updated_at) WHERE staging_key IS NOT NULL;
CREATE TABLE attachment_variants (
attachment_id uuid NOT NULL REFERENCES attachments (id),
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
object_key text COLLATE "C" NOT NULL CONSTRAINT attachment_variants_object_key_key UNIQUE,
content_type text NOT NULL CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')),
size_bytes bigint NOT NULL CHECK (size_bytes >= 1),
width integer NOT NULL CHECK (width >= 1),
height integer NOT NULL CHECK (height >= 1),
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
created_at timestamptz NOT NULL,
PRIMARY KEY (attachment_id, pipeline_version, name)
);
CREATE TABLE jobs (
job_id uuid PRIMARY KEY,
attachment_id uuid NOT NULL REFERENCES attachments (id),
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
status text NOT NULL CHECK (status IN ('queued', 'processing', 'done', 'failed', 'superseded')),
attempt integer NOT NULL CHECK (attempt >= 1),
claims integer NOT NULL DEFAULT 0 CHECK (claims >= 0),
lease_token uuid,
lease_until timestamptz,
next_attempt_at timestamptz,
last_error text,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT jobs_effect_key UNIQUE (attachment_id, pipeline_version)
);
CREATE INDEX jobs_lease_idx ON jobs (lease_until) WHERE status = 'processing';
CREATE TABLE outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
job_id uuid NOT NULL REFERENCES jobs (job_id),
payload jsonb NOT NULL,
available_at timestamptz NOT NULL,
published_at timestamptz
);
CREATE INDEX outbox_pending_idx ON outbox (available_at, id) WHERE published_at IS NULL;
CREATE INDEX outbox_job_idx ON outbox (job_id);
CREATE TABLE job_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
job_id uuid NOT NULL,
attachment_id uuid NOT NULL,
kind text NOT NULL,
attempt integer,
detail jsonb NOT NULL DEFAULT '{}',
at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX job_events_attachment_idx ON job_events (attachment_id, id);
@@ -0,0 +1 @@
CREATE INDEX jobs_failed_idx ON jobs (updated_at DESC) WHERE status = 'failed';
@@ -0,0 +1,6 @@
ALTER TABLE attachments
ADD COLUMN quarantine_reason text
CHECK (quarantine_reason IN ('missing', 'size_mismatch', 'sha_mismatch')),
ADD COLUMN quarantined_at timestamptz,
ADD CONSTRAINT attachments_quarantine_check
CHECK ((quarantine_reason IS NULL) = (quarantined_at IS NULL));
+107 -2
View File
@@ -137,14 +137,23 @@ def replica_at(address: str) -> str:
def raw(
path: str, headers: dict[str, str], body: bytes, *, hang_up: bool
path: str,
headers: dict[str, str],
body: bytes,
*,
hang_up: bool,
piece: int = 0,
delay: float = 0.0,
) -> tuple[int, dict[str, Any], float]:
parts = urlsplit(BASE_URL)
head = f"POST {path} HTTP/1.1\r\nHost: {parts.netloc}\r\nConnection: close\r\n"
head += "".join(f"{name}: {value}\r\n" for name, value in headers.items()) + "\r\n"
started = time.perf_counter()
with socket.create_connection((parts.hostname, parts.port or 80), timeout=30) as sock:
sock.sendall(head.encode("latin-1") + body)
sock.sendall(head.encode("latin-1"))
for start in range(0, len(body), piece or max(len(body), 1)):
sock.sendall(body[start : start + (piece or len(body))])
time.sleep(delay)
if hang_up:
return 0, {}, 0.0
response = HTTPResponse(sock)
@@ -152,6 +161,56 @@ def raw(
return response.status, json.loads(response.read()), time.perf_counter() - started
READER = """
import hashlib, http.client, sys, time
path, token, request_id, piece, delay = sys.argv[1:6]
connection = http.client.HTTPConnection("lb", 8080, timeout=30)
headers = {"Authorization": "Bearer " + token, "X-Request-Id": request_id}
connection.request("GET", path, headers=headers)
response, digest, started = connection.getresponse(), hashlib.sha256(), time.monotonic()
while chunk := response.read(int(piece)):
digest.update(chunk)
time.sleep(float(delay))
print(response.status, digest.hexdigest(), round(time.monotonic() - started, 2))
"""
def slow_read(path: str, token: str, request_id: str, piece: int, delay: float) -> list[str]:
template = "{{range $name, $_ := .NetworkSettings.Networks}}{{$name}} {{end}}"
networks = subprocess.run(
["docker", "inspect", "-f", template, compose("ps", "-q", "lb")],
check=True,
capture_output=True,
text=True,
).stdout.split()
image = subprocess.run(
["docker", "inspect", "-f", "{{.Config.Image}}", compose("ps", "-q", "api").split()[0]],
check=True,
capture_output=True,
text=True,
).stdout.strip()
command = [
"docker",
"run",
"--rm",
"--network",
next(name for name in networks if name.endswith("_edge")),
"--sysctl",
"net.ipv4.tcp_rmem=4096 16384 65536",
"--entrypoint",
"python",
image,
"-c",
READER,
path,
token,
request_id,
str(piece),
str(delay),
]
return subprocess.run(command, check=True, capture_output=True, text=True).stdout.split()
@pytest.fixture
async def http() -> AsyncIterator[AsyncClient]:
async with AsyncClient(base_url=BASE_URL, timeout=30, trust_env=False) as client:
@@ -470,3 +529,49 @@ async def test_stalled_upload_is_cut_and_leaves_nothing(http: AsyncClient, fault
assert elapsed <= REQUEST_TIMEOUT + 2
assert seen(name) is None
assert (await upload(http, s["alice"], s["chats"][0])).status_code == 202
async def test_token_is_checked_before_the_declared_size(http: AsyncClient) -> None:
s = await scene(http)
headers = {"Content-Type": "image/png", "Content-Length": str(LIMIT + 1)}
path = f"/api/v1/chats/{s['chats'][0]}/attachments?filename=a.png"
status, body, _ = await asyncio.to_thread(raw, path, headers, SAMPLE[:1024], hang_up=False)
print(f"без токена, Content-Length {LIMIT + 1}: {status} {body['error']['code']}")
assert (status, body["error"]["code"]) == (401, "unauthorized")
async def test_slow_but_steady_transfers_outlive_the_request_timeout(http: AsyncClient) -> None:
since = moment()
s = await scene(http)
picture = png(16, 16, size=3 << 20)
sent, read = f"slow-upload-{uuid4().hex}", f"slow-download-{uuid4().hex}"
headers = {
**bearer(s["alice"]),
"Content-Type": "image/png",
"Content-Length": str(len(picture)),
"X-Request-Id": sent,
}
path = f"/api/v1/chats/{s['chats'][0]}/attachments?filename=slow.png"
status, body, up = await asyncio.to_thread(
raw, path, headers, picture, hang_up=False, piece=64 << 10, delay=0.25
)
assert status == 202, body
assert body["sha256"] == sha256(picture).hexdigest()
await waited(lambda: status_of(body["id"]) == "ready", 60)
content = f"/api/v1/attachments/{body['id']}/content"
code, digest, down = await asyncio.to_thread(slow_read, content, s["bob"], read, 64 << 10, 0.33)
assert (code, digest) == ("200", body["sha256"])
def handled() -> dict[str, tuple[int, float]]:
return {
e["request_id"]: (e["status"], e["duration_ms"] / 1000)
for e in logs(since)
if e.get("event") == "request.handled" and e.get("request_id") in (sent, read)
}
await waited(lambda: len(handled()) == 2, 15)
replica = handled()
print(f"upload 3 MiB ≈ 256 KiB/s: клиент {up:.1f} с, реплика {replica[sent]}")
print(f"скачивание 3 MiB ≈ 192 KiB/s из сети edge: клиент {down} с, реплика {replica[read]}")
assert replica[sent][0] == 202 and replica[sent][1] > REQUEST_TIMEOUT
assert replica[read][0] == 200 and replica[read][1] > REQUEST_TIMEOUT
+51 -1
View File
@@ -1,4 +1,5 @@
import asyncio
import time
from collections.abc import AsyncIterator
from uuid import uuid4
@@ -18,6 +19,7 @@ from stand import (
new_user,
psql,
report,
restart_stack,
started_at,
timed,
valkey,
@@ -55,7 +57,8 @@ async def test_chat_creation_rolls_back_on_unknown_member(http: AsyncClient) ->
json={"title": title, "member_ids": [alice["id"], str(uuid4())]},
headers=bearer(token),
)
print(f"чат с несуществующим участником: {response.status_code}")
code = response.json()["error"]["code"]
print(f"чат с несуществующим участником: {response.status_code} {code}")
assert response.status_code == 400
assert response.json()["error"]["code"] == "invalid_request"
assert psql("SELECT count(*) FROM chats WHERE title = :'title'", title=title) == "0"
@@ -208,6 +211,13 @@ async def test_postgres_stopped_gives_bounded_503_and_recovers(http: AsyncClient
me = await http.get("/api/v1/users/me", headers=bearer(token))
print(f"postgres запущен: готовность через {recovered:.1f} с, прежний токен {me.status_code}")
assert me.json() == user
instances = set()
for _ in range(40):
response = await http.post("/api/v1/users", json=new_user("recovered"))
assert response.status_code == 201
instances.add(response.headers["X-Instance-Id"])
print(f"postgres запущен: 40 регистраций 201 через {len(instances)} реплики без рестарта API")
assert len(instances) >= 2
assert started_at("api") == api_started
@@ -227,3 +237,43 @@ async def test_api_restart_keeps_session_without_extending_it(http: AsyncClient)
print(f"expires_at при входе {session['expires_at']}, в БД после рестарта {stored}")
assert me.status_code == 200
assert stored.rstrip("Z").rstrip("0") == session["expires_at"].rstrip("Z").rstrip("0")
async def test_full_restart_keeps_session_until_logout(http: AsyncClient) -> None:
user, token = await enroll(http, "fullrestart")
restart_stack()
recovered = await wait_ready(http)
me = await http.get("/api/v1/users/me", headers=bearer(token))
logout = await http.delete("/api/v1/auth/sessions/current", headers=bearer(token))
after = await http.get("/api/v1/users/me", headers=bearer(token))
print(
f"restart.sh: готовность через {recovered:.1f} с, прежний токен {me.status_code}, "
f"выход {logout.status_code}, затем {after.status_code}"
)
assert me.json() == user
assert logout.status_code == 204
assert after.status_code == 401
async def test_session_expires_after_restart_at_original_time(http: AsyncClient) -> None:
user, token = await enroll(http, "shortrestart")
expires_at = float(
psql(
"UPDATE sessions s SET expires_at = now() + interval '20 seconds' FROM users u "
"WHERE u.id = s.user_id AND u.username = :'name' "
"RETURNING extract(epoch FROM s.expires_at)",
name=user["username"],
).splitlines()[0]
)
compose("restart", "api")
recovered = await wait_ready(http)
fresh = await http.get("/api/v1/users/me", headers=bearer(token))
await asyncio.sleep(max(0.0, expires_at - time.time()) + 0.5)
stale = await http.get("/api/v1/users/me", headers=bearer(token))
print(
f"срок сессии сокращён до 20 с, рестарт api: готовность через {recovered:.1f} с, "
f"до срока {fresh.status_code}, после срока {stale.status_code}"
)
assert fresh.status_code == 200
assert stale.status_code == 401
assert stale.headers["WWW-Authenticate"] == BEARER
+4
View File
@@ -32,6 +32,10 @@ def compose(*args: str, stdin: str | None = None) -> str:
return done.stdout.strip()
def restart_stack() -> None:
subprocess.run(["sh", "scripts/restart.sh"], cwd=ROOT, check=True, capture_output=True)
def psql(sql: str, **variables: str) -> str:
assigned = [item for name, value in variables.items() for item in ("-v", f"{name}={value}")]
command = ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tA"]
+139
View File
@@ -0,0 +1,139 @@
import argparse
import asyncio
import hashlib
import json
import time
from datetime import UTC, datetime, timedelta
from io import BytesIO
from uuid import uuid4
from PIL import Image
from sqlalchemy import func, insert, make_url, select
from sqlalchemy.ext.asyncio import create_async_engine
from messenger.attachments.config import AttachmentsSettings
from messenger.attachments.infrastructure.postgres import AttachmentRow
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
from messenger.identity.infrastructure.postgres import UserRow
from messenger.messaging.infrastructure.postgres import ChatMemberRow
from messenger.shared.config import PlatformSettings
MODELS = (UserRow, ChatMemberRow, AttachmentRow)
COLUMNS = (
"id",
"chat_id",
"owner_id",
"filename",
"content_type",
"size_bytes",
"sha256",
"width",
"height",
"object_key",
"status",
"created_at",
"updated_at",
)
def picture() -> bytes:
buffer = BytesIO()
Image.effect_noise((8, 8), 64).convert("RGB").save(buffer, "PNG")
return buffer.getvalue()
async def seed(count: int, concurrency: int) -> dict[str, object]:
platform, settings = PlatformSettings(), AttachmentsSettings()
body = picture()
digest = hashlib.sha256(body).hexdigest()
engine = create_async_engine(
make_url(platform.database_url.get_secret_value()).set(drivername="postgresql+asyncpg"),
hide_parameters=True,
)
try:
async with engine.connect() as connection:
member = (
(
await connection.execute(
select(ChatMemberRow.chat_id, ChatMemberRow.user_id).limit(1)
)
)
.mappings()
.first()
)
if member is None:
raise SystemExit("нет ни одного чата: сначала make test")
ids = [uuid4() for _ in range(count)]
pending = iter(ids)
completed = 0
started = time.monotonic()
async with s3_client(
endpoint=settings.s3_endpoint,
region=settings.s3_region,
access_key_id=settings.s3_access_key_id.get_secret_value(),
secret_access_key=settings.s3_secret_access_key.get_secret_value(),
connect_timeout=settings.s3_connect_timeout_seconds,
read_timeout=settings.s3_read_timeout_seconds,
max_attempts=3,
) as client:
storage = S3ObjectStorage(client, settings.s3_bucket)
async def worker() -> None:
nonlocal completed
for attachment_id in pending:
await storage.put(f"attachments/{attachment_id}", body, "image/png")
completed += 1
if completed % 10000 == 0 or completed == count:
print(json.dumps({"progress": completed, "target": count}), flush=True)
await asyncio.gather(*(worker() for _ in range(concurrency)))
stored = time.monotonic()
stamp = datetime.now(UTC) - timedelta(hours=2)
records = [
(
attachment_id,
member["chat_id"],
member["user_id"],
f"seed-{number}.png",
"image/png",
len(body),
digest,
8,
8,
f"attachments/{attachment_id}",
"ready",
stamp,
stamp,
)
for number, attachment_id in enumerate(ids)
]
async with engine.begin() as connection:
for start in range(0, count, 1000):
await connection.execute(
insert(AttachmentRow),
[dict(zip(COLUMNS, row, strict=True)) for row in records[start : start + 1000]],
)
total = await connection.scalar(select(func.count()).select_from(AttachmentRow))
finally:
await engine.dispose()
return {
"added": count,
"rows_total": total,
"object_bytes": len(body),
"seconds": {
"s3_put": round(stored - started, 3),
"pg_insert": round(time.monotonic() - stored, 3),
},
}
def main() -> None:
parser = argparse.ArgumentParser(description="Наполнить bucket и attachments N вложениями")
parser.add_argument("--count", type=int, required=True)
parser.add_argument("--concurrency", type=int, default=32)
args = parser.parse_args()
print(json.dumps(asyncio.run(seed(args.count, args.concurrency))))
if __name__ == "__main__":
main()
+16 -77
View File
@@ -9,13 +9,12 @@ from messenger.identity.domain.errors import InvalidUserData
from messenger.identity.domain.models import Session, User, token_digest
from messenger.identity.domain.values import DisplayName, Password, Username
from messenger.messaging.domain.errors import (
ChatNotFound,
IdempotencyConflict,
InvalidAttachmentList,
InvalidChatData,
InvalidMessageText,
)
from messenger.messaging.domain.models import Chat, Receipt
from messenger.messaging.domain.models import Chat, Message, Receipt, attachment_list
from messenger.messaging.domain.values import MessageText
from messenger.shared.infrastructure.clock import MonotonicUtcClock
@@ -90,17 +89,6 @@ def test_message_text_rejects_whitespace() -> None:
assert MessageText("").value == ""
def make_chat(*members: object) -> Chat:
ids = [uuid4() for _ in members] if members else [uuid4()]
return Chat.create(
chat_id=uuid4(),
title="Чат",
member_ids=ids,
creator_id=ids[0],
created_at=MOMENT,
)
def test_chat_requires_creator_in_members() -> None:
members = [uuid4(), uuid4()]
with pytest.raises(InvalidChatData):
@@ -137,87 +125,38 @@ def test_chat_rejects_more_than_hundred_members() -> None:
)
def test_outsider_cannot_post() -> None:
chat = make_chat(1)
with pytest.raises(ChatNotFound):
chat.post(message_id=uuid4(), sender_id=uuid4(), text="привет", now=MOMENT)
def test_post_never_moves_history_back() -> None:
chat = make_chat(1)
sender = chat.member_ids[0]
first = chat.post(
message_id=uuid4(), sender_id=sender, text="первое", now=MOMENT + timedelta(seconds=1)
)
second = chat.post(message_id=uuid4(), sender_id=sender, text="второе", now=MOMENT)
assert second.created_at == first.created_at + timedelta(microseconds=1)
assert chat.last_message_at == second.created_at
def test_post_keeps_clock_when_it_is_ahead() -> None:
chat = make_chat(1)
sender = chat.member_ids[0]
first = chat.post(message_id=uuid4(), sender_id=sender, text="первое", now=MOMENT)
later = MOMENT + timedelta(seconds=5)
second = chat.post(message_id=uuid4(), sender_id=sender, text="второе", now=later)
assert first.created_at == MOMENT
assert second.created_at == later
def test_post_validates_membership_before_text() -> None:
chat = make_chat(1)
with pytest.raises(ChatNotFound):
chat.post(message_id=uuid4(), sender_id=uuid4(), text="", now=MOMENT)
def test_empty_text_needs_an_attachment() -> None:
chat = make_chat(1)
sender = chat.member_ids[0]
with pytest.raises(InvalidMessageText):
chat.post(message_id=uuid4(), sender_id=sender, text="", now=MOMENT)
ids = (uuid4(), uuid4())
message = chat.post(
message_id=uuid4(), sender_id=sender, text="", now=MOMENT, attachment_ids=ids
)
assert message.attachment_ids == ids
with pytest.raises(InvalidMessageText):
chat.post(message_id=uuid4(), sender_id=sender, text=" ", now=MOMENT, attachment_ids=ids)
attachment_list(MessageText(""), ())
assert attachment_list(MessageText(""), ids) == ids
@pytest.mark.parametrize("ids", [[uuid4() for _ in range(11)], [UUID_TWICE, UUID_TWICE]])
def test_attachment_list_is_bounded_and_unique(ids: list[UUID]) -> None:
chat = make_chat(1)
with pytest.raises(InvalidAttachmentList):
chat.post(
message_id=uuid4(),
sender_id=chat.member_ids[0],
text="x",
now=MOMENT,
attachment_ids=ids,
)
def test_membership_is_checked_before_attachments() -> None:
chat = make_chat(1)
with pytest.raises(ChatNotFound):
chat.post(
message_id=uuid4(),
sender_id=uuid4(),
text="",
now=MOMENT,
attachment_ids=[uuid4() for _ in range(11)],
)
attachment_list(MessageText("x"), ids)
def test_receipt_replays_only_the_same_request() -> None:
chat = make_chat(1)
message = chat.post(message_id=uuid4(), sender_id=chat.member_ids[0], text="раз", now=MOMENT)
message = Message(uuid4(), uuid4(), uuid4(), MessageText("раз"), MOMENT)
receipt = Receipt("key-1", b"a" * 32, message)
assert receipt.replay(b"a" * 32) is message
with pytest.raises(IdempotencyConflict):
receipt.replay(b"b" * 32)
def test_posted_message_describes_itself() -> None:
message = Message(uuid4(), uuid4(), uuid4(), MessageText("пять"), MOMENT)
event = message.posted()
assert (event.message_id, event.chat_id, event.sender_id) == (
message.id,
message.chat_id,
message.sender_id,
)
assert (event.text_length, event.created_at, event.name) == (4, MOMENT, "message.posted")
def test_user_registration_emits_event() -> None:
user, event = User.register(
user_id=uuid4(),
+83
View File
@@ -0,0 +1,83 @@
import importlib.util
from pathlib import Path
from types import SimpleNamespace
import pytest
SPEC = importlib.util.spec_from_file_location(
"grade4_probe", Path(__file__).resolve().parents[2] / "scripts/probe.py"
)
assert SPEC is not None and SPEC.loader is not None
probe = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(probe)
ARGS = SimpleNamespace(
label="old", command=[], expect="replace", max_failed_ratio=0.01, max_recovery=10
)
def result_of(probes: list[tuple]) -> dict:
result = probe.summarize(
ARGS, probes, [(99, 2), (101, 2)], {"start": 100, "end": 101, "exit": 0, "load_end": 120}, 2
)
result["k6"] = {"exit": 0, "failed_ratio": 0, "requests": 100, "dropped_iterations": 0}
result["history"] = {"exact_match": True, "unique": True}
return result
@pytest.mark.parametrize(
("attempts", "recovery", "passed"),
[
([(100, 503, 20, "old")], None, False),
([(100, 503, 20, "old"), (109, 201, 2000, "new")], 11, False),
([(100, 503, 20, "old"), (101, 201, 500, "new")], 1.5, True),
([(101, 201, 500, "new")], 0, True),
([], 0, False),
],
)
def test_recovery_requires_completed_success(attempts: list, recovery: float, passed: bool) -> None:
result = result_of([(99, 201, 1, "old"), *attempts])
assert result["probe"]["recovery_s"] == recovery
assert probe.verdict(ARGS, result)["write_recovery_ok"] is passed
@pytest.mark.parametrize(
("field", "value", "check"),
[("requests", 0, "load_delivered"), ("dropped_iterations", 1, "load_delivered")],
)
def test_incomplete_load_fails(field: str, value: int, check: str) -> None:
result = result_of([(99, 201, 1, "old"), (102, 201, 1, "new")])
result["k6"][field] = value
assert not probe.verdict(ARGS, result)[check]
def test_missing_lb_sample_fails() -> None:
result = result_of([(99, 201, 1, "old"), (102, 201, 1, "new")])
result["lb_samples_missing"] = 1
assert not probe.verdict(ARGS, result)["lb_observed"]
@pytest.mark.parametrize("corruption", ["none", "missing", "duplicate", "changed", "http", "cycle"])
def test_full_history_matches_confirmed_bodies(
monkeypatch: pytest.MonkeyPatch, corruption: str
) -> None:
messages = [{"id": str(n), "text": "original"} for n in range(101)]
stored = list(reversed(messages))
if corruption == "missing":
stored.pop()
if corruption == "duplicate":
stored.append(stored[0])
if corruption == "changed":
stored[0] = dict(stored[0], text="changed")
pages = iter(
[
(200, "", {"items": stored[:100], "next_cursor": "next"}),
(
503 if corruption == "http" else 200,
"",
{"items": stored[100:], "next_cursor": "next" if corruption == "cycle" else None},
),
]
)
monkeypatch.setattr(probe, "call", lambda *_a, **_kw: next(pages))
result = probe.history_check({"auth": {}}, "chat", messages)
assert (result["exact_match"] and result["unique"]) is (corruption == "none")
@@ -0,0 +1,69 @@
import importlib.util
from pathlib import Path
from types import ModuleType, SimpleNamespace
from unittest.mock import Mock
import pytest
@pytest.fixture
def track(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
script = Path(__file__).resolve().parents[2] / "scripts/reconcile_track.py"
spec = importlib.util.spec_from_file_location("reconcile_measurements", script)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.parametrize(
("disturbed", "quiet", "accepted", "discarded"),
[
([False], True, True, 0),
([True, False], True, True, 1),
([True, True], True, False, 2),
([True], False, False, 1),
],
)
def test_only_clean_measurements_are_accepted(
track: ModuleType,
monkeypatch: pytest.MonkeyPatch,
*,
disturbed: list[bool],
quiet: bool,
accepted: bool,
discarded: int,
) -> None:
reports = [{"cost": {"cpu_seconds": 1}, "attempt": i} for i in range(len(disturbed))]
monkeypatch.setattr(track, "sample", lambda: None)
monkeypatch.setattr(track, "reconcile", Mock(side_effect=reports))
monkeypatch.setattr(track, "screen", Mock(side_effect=[{"disturbed": d} for d in disturbed]))
monkeypatch.setattr(track, "wait_quiet", lambda *_: quiet)
chosen, rejected = track.measure([], {}, SimpleNamespace(retries=1), set())
assert (chosen is not None) == accepted
assert len(rejected) == discarded
assert all(r["screen"]["disturbed"] for r in rejected)
if chosen is not None:
assert not chosen["screen"]["disturbed"]
assert chosen not in rejected
def test_existing_series_is_preserved_before_docker_access(
track: ModuleType, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
monkeypatch.setenv("RECONCILE_EVIDENCE_DIR", str(tmp_path))
folder = tmp_path / "cost"
folder.mkdir()
raw = folder / "n1000-shallow-1.json"
raw.write_text("previous evidence")
query = Mock(side_effect=AssertionError("must not access the stand"))
monkeypatch.setattr(track, "psql", query)
with pytest.raises(FileExistsError):
track.cost(SimpleNamespace(sizes=[1000]))
assert raw.read_text() == "previous evidence"
query.assert_not_called()
def test_quiet_deadline_is_not_success(track: ModuleType, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(track.time, "monotonic", lambda: 10)
assert not track.wait_quiet(SimpleNamespace(quiet_timeout=0), set())
+80
View File
@@ -0,0 +1,80 @@
import importlib.util
from pathlib import Path
from types import ModuleType, SimpleNamespace
from unittest.mock import Mock
import pytest
@pytest.fixture
def scaling(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
scripts = Path(__file__).resolve().parents[2] / "scripts"
monkeypatch.syspath_prepend(str(scripts))
spec = importlib.util.spec_from_file_location("scaling", scripts / "scaling.py")
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_retry_preserves_previous_raw_data(scaling: ModuleType, tmp_path: Path) -> None:
base = {"variant": "base", "config": "1x1"}
first = scaling.attempt_folder(tmp_path, base, 100, 1)
(first / "k6.txt").write_text("failed attempt")
second = scaling.attempt_folder(tmp_path, base, 100, 1)
assert first != second
assert (first / "k6.txt").read_text() == "failed attempt"
@pytest.mark.parametrize("recover", [False, True])
def test_disturbed_runs_never_enter_summary(
scaling: ModuleType, monkeypatch: pytest.MonkeyPatch, recover: bool
) -> None:
args = SimpleNamespace(
base_env={}, out="unused", retries=1, pause=0, rates="100", rejected=Mock()
)
rejected = {"raw_dir": "attempt1", "disturbed": True, "saturated": False}
accepted = {"raw_dir": "attempt2", "disturbed": False, "saturated": False}
monkeypatch.setattr(scaling, "layout", lambda *_: ({}, {}))
monkeypatch.setattr(scaling, "apply", lambda *_: {})
monkeypatch.setattr(scaling, "deployment", lambda *_: [])
monkeypatch.setattr(scaling, "wait_quiet", lambda *_: None)
monkeypatch.setattr(
scaling, "step", Mock(side_effect=[rejected, accepted if recover else rejected])
)
output = Mock()
if recover:
scaling.block(args, output, "1x1", "base", [1])
output.writerows.assert_called_once_with([accepted])
args.rejected.writerow.assert_called_once_with(rejected)
else:
with pytest.raises(SystemExit, match="exhausted retries"):
scaling.block(args, output, "1x1", "base", [1])
output.writerows.assert_not_called()
assert args.rejected.writerow.call_count == 2
@pytest.mark.parametrize(
("fixed", "expected"),
[
(True, [("4x1", [2]), ("8x0.5", [2]), ("4x1", [3]), ("8x0.5", [3])]),
(False, [("4x1", [2, 3]), ("8x0.5", [2, 3])]),
],
)
def test_series_order(
scaling: ModuleType,
monkeypatch: pytest.MonkeyPatch,
fixed: bool,
expected: list[tuple[str, list[int]]],
) -> None:
args = SimpleNamespace(
first_repeat=2,
repeats=2,
configs="4x1,8x0.5",
variants=["pinned"],
rates="3040,4560" if fixed else None,
)
block = Mock()
monkeypatch.setattr(scaling, "block", block)
scaling.series(args, Mock())
assert [(call.args[2], list(call.args[4])) for call in block.call_args_list] == expected
+4 -3
View File
@@ -46,15 +46,16 @@ def test_timeouts_shrink_inwards_and_shutdown_fits_the_stop_budget() -> None:
database = api["DB_ACQUIRE_TIMEOUT_SECONDS"] + api["DB_COMMAND_TIMEOUT_SECONDS"]
drain, shutdown = api["DRAIN_SECONDS"], api["SHUTDOWN_TIMEOUT_SECONDS"]
print(
f"обнаружение {detection} с (зависание {hung} с), окно {drain} с, остановка {shutdown} с,"
f" хук {hook} с, stop_grace_period {grace} с; LB server {lb['timeout server']} с >"
f"обнаружение {detection} с (зависание {hung} с), окно {drain} с,"
f" дообработка {shutdown - drain - 1} с, остановка {shutdown} с, хук {hook} с,"
f" stop_grace_period {grace} с; LB server {lb['timeout server']} с >"
f" запрос {api['REQUEST_TIMEOUT_SECONDS']} с > БД {database} с;"
f" readiness {2 * PING_TIMEOUT_SECONDS} с < check {lb['timeout check']} с"
)
assert lb["timeout server"] > api["REQUEST_TIMEOUT_SECONDS"] > database
assert lb["timeout check"] > 2 * PING_TIMEOUT_SECONDS
assert drain > detection
assert shutdown - drain >= database
assert shutdown - drain - 1 >= database
assert shutdown < hook < grace < 10
assert lb["hard-stop-after"] < seconds(stand["lb"]["stop_grace_period"])
assert (detection, hung) == (1.5, 3.5)