Implement lab 7 transport security and worker containment

This commit is contained in:
Artyom
2026-11-13 23:58:00 +03:00
parent 20afc2c790
commit 170a76a6ce
543 changed files with 96442 additions and 65 deletions
+120
View File
@@ -0,0 +1,120 @@
import time
from uuid import UUID, uuid4
from httpx import AsyncClient
from sqlalchemy import select
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:
alice = await register(client, "alice")
bob = await register(client, "bob")
eve = await register(client, "eve")
chat = await make_chat(client, alice, bob)
response = await client.get(f"/api/v1/chats/{chat['id']}", headers=actor(eve))
assert response.status_code == 404
assert response.json()["error"]["code"] == "not_found"
async def test_unknown_chat_is_indistinguishable_from_foreign(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
foreign = await client.get(f"/api/v1/chats/{chat['id']}", headers=actor(eve))
missing = await client.get(f"/api/v1/chats/{uuid4()}", headers=actor(eve))
assert foreign.status_code == missing.status_code == 404
assert foreign.json()["error"]["code"] == missing.json()["error"]["code"]
assert foreign.json()["error"]["message"] == missing.json()["error"]["message"]
async def test_outsider_cannot_write(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "чужое"},
headers=keyed(eve),
)
assert response.status_code == 404
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))
assert history.json()["items"] == []
async def test_outsider_cannot_read_history(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
response = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(eve))
assert response.status_code == 404
async def test_access_checked_before_body(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": ""},
headers=keyed(eve),
)
assert response.status_code == 404
async def test_chat_list_hides_foreign_chats(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
eve = await register(client, "eve")
chat = await make_chat(client, alice, bob)
for member in (alice, bob):
listed = await client.get("/api/v1/chats?limit=100", headers=actor(member))
assert any(item["id"] == chat["id"] for item in listed.json()["items"])
hidden = await client.get("/api/v1/chats?limit=100", headers=actor(eve))
assert hidden.json()["items"] == []
async def test_403_is_never_used(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
paths = [
f"/api/v1/chats/{chat['id']}",
f"/api/v1/chats/{chat['id']}/messages",
]
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
+342
View File
@@ -0,0 +1,342 @@
from collections.abc import AsyncIterator
from hashlib import sha256
from io import BytesIO
from typing import Any
from urllib.parse import quote
from uuid import UUID, uuid4
import pytest
from httpx import AsyncClient, Response
from PIL import Image
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 BROKEN_PNG, DUPLICATE_IHDR_PNG, GIF, JPEG, SAMPLE, WEBP, png
from pipeline import settle
LIMIT = 10_485_760
PNG = {"Content-Type": "image/png"}
async def upload(
http: AsyncClient,
user: dict[str, Any],
chat: dict[str, Any],
content: bytes | AsyncIterator[bytes] = SAMPLE,
*,
filename: str | None = "sample.png",
headers: dict[str, str] | None = None,
) -> Response:
query = "" if filename is None else f"?filename={quote(filename, safe='')}"
return await http.post(
f"/api/v1/chats/{chat['id']}/attachments{query}",
content=content,
headers={**actor(user), **(PNG if headers is None else headers)},
)
async def storage(http: AsyncClient) -> MemoryObjectStorage:
found = await resolve(http, ObjectStorage)
assert isinstance(found, MemoryObjectStorage)
return found
async def trio(http: AsyncClient) -> tuple[dict[str, Any], ...]:
alice, bob, eve = [await register(http, label) for label in ("alice", "bob", "eve")]
return alice, bob, eve, await make_chat(http, alice, bob)
async def test_member_uploads_and_another_member_downloads(client: AsyncClient) -> None:
alice, bob, eve, chat = await trio(client)
response = await upload(client, alice, chat)
assert response.status_code == 202, response.text
attachment = response.json()
assert set(attachment) == {
"id",
"chat_id",
"owner_id",
"filename",
"content_type",
"size_bytes",
"sha256",
"status",
"variants",
"error_code",
"created_at",
"updated_at",
}
assert attachment["chat_id"] == chat["id"]
assert attachment["owner_id"] == alice["id"]
assert attachment["filename"] == "sample.png"
assert attachment["content_type"] == "image/png"
assert attachment["size_bytes"] == len(SAMPLE) == 111817
assert attachment["sha256"] == sha256(SAMPLE).hexdigest()
assert (attachment["status"], attachment["variants"], attachment["error_code"]) == (
"queued",
[],
None,
)
assert attachment["created_at"].endswith("Z")
path = f"/api/v1/attachments/{attachment['id']}"
assert (await client.get(path, headers=actor(bob))).json() == attachment
await settle(client)
ready = (await client.get(path, headers=actor(bob))).json()
assert (ready["status"], ready["error_code"], ready["sha256"]) == (
"ready",
None,
attachment["sha256"],
)
assert [variant["name"] for variant in ready["variants"]] == ["crop", "optimized", "thumbnail"]
content = await client.get(
f"{path}/content", headers={**actor(bob), "Accept": "application/json"}
)
assert content.status_code == 200
assert content.content == SAMPLE
assert content.headers["content-type"] == "image/png"
assert content.headers["content-length"] == str(len(SAMPLE))
assert content.headers["x-content-type-options"] == "nosniff"
assert content.headers["x-request-id"]
assert content.headers["x-instance-id"]
for suffix in ("", "/content"):
stranger = await client.get(f"{path}{suffix}", headers=actor(eve))
assert stranger.status_code == 404
assert stranger.json()["error"]["code"] == "not_found"
async def test_object_keys_are_assigned_by_server(client: AsyncClient) -> None:
alice, _, _, chat = await trio(client)
attachment = (await upload(client, alice, chat, filename="a.png")).json()
staging = await scalar("SELECT staging_key FROM attachments WHERE id = $1", attachment["id"])
assert staging == f"staging/{attachment['id']}"
assert set((await storage(client)).objects) >= {staging}
await settle(client)
original = await scalar("SELECT original_key FROM attachments WHERE id = $1", attachment["id"])
assert original == f"originals/{attachment['id']}"
assert (await storage(client)).objects[original][0] == SAMPLE
async def test_jpeg_is_accepted_by_content(client: AsyncClient) -> None:
alice, bob, _, chat = await trio(client)
response = await upload(client, alice, chat, JPEG, headers={"Content-Type": "IMAGE/JPEG"})
assert response.status_code == 202, response.text
assert response.json()["content_type"] == "image/jpeg"
await settle(client)
download = await client.get(
f"/api/v1/attachments/{response.json()['id']}/content", headers=actor(bob)
)
assert (download.content, download.headers["content-type"]) == (JPEG, "image/jpeg")
async def test_access_is_checked_before_content(client: AsyncClient) -> None:
alice, _, eve, chat = await trio(client)
assert (await upload(client, eve, chat, b"not an image", filename="../x")).status_code == 404
missing = {"id": str(uuid4())}
assert (await upload(client, alice, missing)).status_code == 404
anonymous = await client.post(
f"/api/v1/chats/{chat['id']}/attachments?filename=a.png", content=SAMPLE, headers=PNG
)
assert anonymous.status_code == 401
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))
assert response.status_code == 202, response.text
assert response.json()["size_bytes"] == LIMIT
async def test_one_byte_over_with_content_length(client: AsyncClient) -> None:
alice, _, _, chat = await trio(client)
response = await upload(client, alice, chat, png(16, 16, size=LIMIT + 1))
assert response.status_code == 413
assert response.json()["error"]["code"] == "payload_too_large"
async def test_one_byte_over_chunked(client: AsyncClient) -> None:
alice, _, _, chat = await trio(client)
body = png(16, 16, size=LIMIT + 1)
async def chunked() -> AsyncIterator[bytes]:
for start in range(0, len(body), 1 << 20):
yield body[start : start + (1 << 20)]
before = await scalar("SELECT count(*) FROM attachments")
response = await upload(client, alice, chat, chunked())
assert response.status_code == 413
assert await scalar("SELECT count(*) FROM attachments") == before
@pytest.mark.parametrize(
("width", "height", "status"),
[(8000, 5000, 202), (8001, 5000, 413), (100_000, 100_000, 413)],
)
async def test_pixel_limit_is_read_from_header(
client: AsyncClient, width: int, height: int, status: int
) -> None:
alice, _, _, chat = await trio(client)
body = png(width, height, rows=width * height <= 40_000_000)
assert len(body) < 64_000
response = await upload(client, alice, chat, body)
assert response.status_code == status, response.text
@pytest.mark.parametrize(
("content", "header"),
[
(BROKEN_PNG, "image/png"),
(DUPLICATE_IHDR_PNG, "image/png"),
(JPEG, "image/png"),
(GIF, "image/png"),
(WEBP, "image/png"),
(b"plain text, not an image", "image/png"),
(SAMPLE, "image/jpeg"),
(SAMPLE[: len(SAMPLE) // 2], "image/png"),
(JPEG[: len(JPEG) // 2], "image/jpeg"),
(b"", "image/png"),
(SAMPLE, "application/octet-stream"),
(SAMPLE, "image/gif"),
],
ids=[
"invalid-zlib",
"duplicate-ihdr",
"jpeg-as-png",
"gif-as-png",
"webp-as-png",
"text-as-png",
"png-as-jpeg",
"truncated-png",
"truncated-jpeg",
"empty",
"octet-stream",
"gif-type",
],
)
async def test_type_is_checked_by_content(client: AsyncClient, content: bytes, header: str) -> None:
alice, _, _, chat = await trio(client)
response = await upload(client, alice, chat, content, headers={"Content-Type": header})
assert response.status_code == 415, response.text
assert response.json()["error"]["code"] == "unsupported_media_type"
async def test_missing_content_type_is_unsupported(client: AsyncClient) -> None:
alice, _, _, chat = await trio(client)
response = await upload(client, alice, chat, headers={})
assert response.status_code == 415
@pytest.mark.parametrize(
"filename",
[
*("../a.png", "a/b.png", "a\\b.png", "a\x00.png", "a\x01.png", "a\x7f.png"),
*("", " ", "x" * 256, None),
],
)
async def test_dangerous_filename_is_rejected(client: AsyncClient, filename: str | None) -> None:
alice, _, _, chat = await trio(client)
response = await upload(client, alice, chat, filename=filename)
assert response.status_code == 400, response.text
assert response.json()["error"]["code"] == "invalid_request"
@pytest.mark.parametrize("filename", ["фото 1.png", "я" * 255, "%41.png"])
async def test_display_name_is_kept(client: AsyncClient, filename: str) -> None:
alice, _, _, chat = await trio(client)
response = await upload(client, alice, chat, filename=filename)
assert response.status_code == 202, response.text
assert response.json()["filename"] == filename
async def test_content_waits_for_ready_and_serves_every_variant(client: AsyncClient) -> None:
alice, bob, _, chat = await trio(client)
attachment = (await upload(client, alice, chat)).json()
path = f"/api/v1/attachments/{attachment['id']}/content"
for variant in ("original", "thumbnail", "crop", "optimized"):
early = await client.get(f"{path}?variant={variant}", headers=actor(bob))
assert early.status_code == 409, early.text
assert early.json()["error"]["code"] == "conflict"
await settle(client)
assert (await client.get(f"{path}?variant=original", headers=actor(alice))).status_code == 200
meta = (await client.get(path.removesuffix("/content"), headers=actor(bob))).json()
expected = {
"crop": ("image/jpeg", "JPEG", (128, 128)),
"optimized": ("image/webp", "WEBP", (320, 200)),
"thumbnail": ("image/jpeg", "JPEG", (256, 160)),
}
for variant in meta["variants"]:
served = await client.get(f"{path}?variant={variant['name']}", headers=actor(bob))
content_type, kind, size = expected[variant["name"]]
assert (served.headers["content-type"], variant["content_type"]) == (content_type,) * 2
assert len(served.content) == variant["size_bytes"]
assert sha256(served.content).hexdigest() == variant["sha256"]
image = Image.open(BytesIO(served.content))
assert (image.format, image.size, (variant["width"], variant["height"])) == (
kind,
size,
size,
)
await scalar(
"DELETE FROM attachment_variants WHERE attachment_id = $1 AND name = 'crop'",
UUID(attachment["id"]),
)
missing = await client.get(f"{path}?variant=crop", headers=actor(alice))
assert missing.status_code == 404
assert (await client.get(f"{path}?variant=preview", headers=actor(alice))).status_code == 400
assert (
await client.get("/api/v1/attachments/x/content", headers=actor(alice))
).status_code == 400
unknown = await client.get(f"/api/v1/attachments/{uuid4()}", headers=actor(alice))
assert unknown.status_code == 404
async def test_storage_failure_leaves_nothing_visible(client: AsyncClient) -> None:
alice, _, _, chat = await trio(client)
ready = await upload(client, alice, chat)
await settle(client)
store = await storage(client)
store.failing = True
try:
failed = await upload(client, alice, chat, filename="failed.png")
download = await client.get(
f"/api/v1/attachments/{ready.json()['id']}/content", headers=actor(alice)
)
metadata = await client.get(
f"/api/v1/attachments/{ready.json()['id']}", headers=actor(alice)
)
finally:
store.failing = False
assert failed.status_code == 503
assert failed.json()["error"]["code"] == "unavailable"
assert download.status_code == 503
assert metadata.status_code == 200
status = await scalar(
"SELECT string_agg(status, ',') FROM attachments WHERE chat_id = $1 AND filename = $2",
chat["id"],
"failed.png",
)
assert status == "pending"
async def test_lost_object_is_not_found(client: AsyncClient) -> None:
alice, _, _, chat = await trio(client)
attachment = (await upload(client, alice, chat)).json()
await settle(client)
(await storage(client)).objects.clear()
response = await client.get(
f"/api/v1/attachments/{attachment['id']}/content", headers=actor(alice)
)
assert response.status_code == 404
assert response.json()["error"]["code"] == "not_found"
+298
View File
@@ -0,0 +1,298 @@
import ast
import re
from pathlib import Path
SOURCE = Path(__file__).resolve().parents[2] / "src" / "messenger"
IDENTITY = "messenger.identity"
MESSAGING = "messenger.messaging"
ATTACHMENTS = "messenger.attachments"
ZONES = ("identity", "messaging", "attachments")
def imports_of(path: Path) -> list[str]:
tree = ast.parse(path.read_text(), filename=str(path))
found: list[str] = []
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.module:
found.append(node.module)
elif isinstance(node, ast.Import):
found.extend(alias.name for alias in node.names)
return found
def modules_under(*parts: str) -> list[Path]:
root = SOURCE.joinpath(*parts)
return [path for path in root.rglob("*.py") if path.name != "__init__.py"]
def test_identity_does_not_know_about_messaging() -> None:
offenders = {
str(path.relative_to(SOURCE)): [m for m in imports_of(path) if m.startswith(MESSAGING)]
for path in modules_under("identity")
}
assert not {k: v for k, v in offenders.items() if v}
def test_attachments_and_other_zones_do_not_import_each_other() -> None:
offenders: dict[str, list[str]] = {}
for zone, foreign in (
("attachments", (IDENTITY, MESSAGING)),
("identity", (ATTACHMENTS,)),
("messaging", (ATTACHMENTS,)),
):
for path in modules_under(zone):
borrowed = [m for m in imports_of(path) if m.startswith(foreign)]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders
def test_domains_do_not_import_infrastructure() -> None:
offenders: dict[str, list[str]] = {}
for zone in (*ZONES, "shared"):
for layer in ("domain", "application"):
for path in modules_under(zone, layer):
borrowed = [m for m in imports_of(path) if ".infrastructure" in m]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders
def test_core_layers_do_not_import_pydantic() -> None:
offenders: dict[str, list[str]] = {}
for zone in (*ZONES, "shared"):
for layer in ("domain", "application"):
for path in modules_under(zone, layer):
borrowed = [m for m in imports_of(path) if m.split(".")[0] == "pydantic"]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders, "схемы pydantic живут на границе: в entrypoints/ и config.py"
def test_shared_knows_nothing_about_zones() -> None:
offenders: dict[str, list[str]] = {}
for path in modules_under("shared"):
borrowed = [
module
for module in imports_of(path)
if module.startswith((IDENTITY, MESSAGING, ATTACHMENTS))
]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders
TRANSPORT = ("fastapi", "starlette", "uvicorn", "gunicorn")
def test_shared_core_is_free_of_transport() -> None:
offenders: dict[str, list[str]] = {}
for layer in ("domain", "application", "infrastructure"):
for path in modules_under("shared", layer):
borrowed = [module for module in imports_of(path) if module.split(".")[0] in TRANSPORT]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders, "ядро shared обязано жить без веб-фреймворка"
def test_shared_core_holds_only_platform() -> None:
names = {
path.name
for layer in ("domain", "application", "infrastructure")
for path in modules_under("shared", layer)
}
assert names == {
"errors.py",
"events.py",
"commands.py",
"messagebus.py",
"ports.py",
"clock.py",
"ids.py",
"logging.py",
"postgres.py",
"telemetry.py",
"trace_context.py",
"runtime_metrics.py",
"readiness.py",
}
def test_shared_entrypoints_hold_only_transport() -> None:
names = {path.name for path in modules_under("shared", "entrypoints")}
assert names == {
"actor.py",
"config.py",
"errors.py",
"health.py",
"ioc.py",
"pipeline.py",
"schemas.py",
"telemetry.py",
}
def test_every_zone_owns_its_errors_events_and_commands() -> None:
for zone in ZONES:
assert (SOURCE / zone / "domain" / "errors.py").is_file()
assert (SOURCE / zone / "domain" / "events.py").is_file()
assert (SOURCE / zone / "application" / "commands.py").is_file()
def test_every_zone_owns_its_http_layer() -> None:
for zone in ZONES:
for part in ("http.py", "ioc.py", "errors.py", "journal.py"):
assert (SOURCE / zone / "entrypoints" / part).is_file(), f"{zone}: нет {part}"
PROCESSES = {"relay.py": (ATTACHMENTS,), "worker.py": (ATTACHMENTS,), "admin.py": (ATTACHMENTS,)}
def test_only_main_knows_several_zones() -> None:
offenders: dict[str, list[str]] = {}
for path in SOURCE.rglob("*.py"):
relative = path.relative_to(SOURCE)
if path.name in {"__init__.py", "main.py"} or relative.parts[0] in ZONES:
continue
allowed = PROCESSES.get(str(relative), ())
borrowed = [
module
for module in imports_of(path)
if module.startswith((IDENTITY, MESSAGING, ATTACHMENTS))
and not module.startswith(allowed or ("-",))
]
if borrowed:
offenders[str(relative)] = borrowed
assert not offenders
def test_broker_framework_stays_out_of_shared_and_core_layers() -> None:
offenders: dict[str, list[str]] = {}
for path in [
*modules_under("shared"),
*(
p
for zone in ZONES
for layer in ("domain", "application")
for p in modules_under(zone, layer)
),
]:
borrowed = [
m for m in imports_of(path) if m.split(".")[0] in {"faststream", "aio_pika", "aiormq"}
]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders
def test_application_has_no_separate_entrypoints_root() -> None:
assert not (SOURCE / "entrypoints").exists()
assert (SOURCE / "main.py").is_file()
ZONE_WORDS = (
"username",
"display_name",
"chat",
"member",
"history",
"cursor",
"sender",
"message_id",
"message_text",
"attachment",
"filename",
)
def test_shared_source_mentions_no_domain_vocabulary() -> None:
offenders: dict[str, list[str]] = {}
for path in modules_under("shared"):
source = path.read_text().lower()
hits = sorted({word for word in ZONE_WORDS if word in source})
if hits:
offenders[str(path.relative_to(SOURCE))] = hits
assert not offenders
def test_shared_declares_no_concrete_commands_or_events() -> None:
for path in modules_under("shared"):
tree = ast.parse(path.read_text(), filename=str(path))
declared = [n.name for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]
concrete = [
name
for name in declared
if name not in {"Command", "DomainEvent", "DomainError"}
and (
name.endswith("Event")
or name in {"RegisterUser", "CreateChat", "PostMessage", "UploadAttachment"}
)
]
assert not concrete, f"{path.name}: {concrete}"
def test_shared_has_no_test_doubles() -> None:
for path in modules_under("shared"):
source = path.read_text()
for marker in ("Frozen", "Fake", "Stub", "Null", "Dummy"):
assert marker not in source, f"{path.name} содержит подделку {marker}"
def test_zone_errors_do_not_leak_transport_codes() -> None:
for zone in (*ZONES, "shared"):
source = (SOURCE / zone / "domain" / "errors.py").read_text()
assert "http_status" not in source
assert "invalid_request" not in source
assert "404" not in source
IDENTITY_TABLES = ("users", "sessions")
MESSAGING_TABLES = ("chats", "chat_members", "messages", "idempotency_keys", "message_attachments")
ATTACHMENT_TABLES = ("attachments", "attachment_variants", "jobs", "outbox", "job_events")
def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
words: set[str] = set()
for path in modules_under(zone):
tree = ast.parse(path.read_text(), filename=str(path))
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)
def test_sql_of_each_zone_reads_only_its_tables() -> None:
owned = {
"identity": IDENTITY_TABLES,
"messaging": MESSAGING_TABLES,
"attachments": ATTACHMENT_TABLES,
}
every = {table for tables in owned.values() for table in tables}
for zone, tables in owned.items():
assert sql_tables(zone, tuple(every)) == set(tables), zone
def test_messaging_does_not_import_identity_at_all() -> None:
borrowed = {
str(path.relative_to(SOURCE)): [m for m in imports_of(path) if m.startswith(IDENTITY)]
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
+226
View File
@@ -0,0 +1,226 @@
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, 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 (
PostgresIdentityUnitOfWork,
PostgresSessionDirectory,
PostgresSessionRepository,
SessionRow,
)
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
from messenger.shared.application.errors import Unavailable
BEARER = 'Bearer realm="messenger"'
def key_of(token: str) -> str:
return f"session:{sha256(token.encode()).hexdigest()}"
def token_of(user: dict) -> str:
return actor(user)["Authorization"].split()[1]
async def test_second_check_is_served_from_cache(valkey: dict[str, str]) -> None:
cache = Redis.from_url(valkey["url"])
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
hits = (await cache.info("stats"))["keyspace_hits"]
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
assert (await cache.info("stats"))["keyspace_hits"] == hits + 1
key = key_of(token_of(alice))
stored = str(await cache.get(key))
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()
async def test_logout_leaves_tombstone_after_commit(valkey: dict[str, str]) -> None:
cache = Redis.from_url(valkey["url"])
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
assert (
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
).status_code == 204
assert await cache.get(key_of(token_of(alice))) == b"-"
response = await http.get("/api/v1/users/me", headers=actor(alice))
assert response.status_code == 401
assert response.headers["WWW-Authenticate"] == BEARER
await cache.aclose()
@pytest.mark.parametrize("failure", ["remove", "commit"])
async def test_logout_rejected_by_database_changes_nothing(
valkey: dict[str, str], monkeypatch: pytest.MonkeyPatch, failure: str
) -> None:
async def broken(self: PostgresSessionRepository, token_hash: bytes) -> None:
raise Unavailable("PostgreSQL недоступен")
async def broken_commit(self: PostgresIdentityUnitOfWork) -> 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:
if failure == "remove":
patch.setattr(PostgresSessionRepository, "remove", broken)
else:
patch.setattr(PostgresIdentityUnitOfWork, "commit", broken_commit)
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()
@pytest.mark.parametrize("loss", ["none", "flushall", "evict", "replacement"])
async def test_fill_racing_with_logout_does_not_revive_token(
valkey: dict[str, str], loss: str
) -> None:
async with (
Redis.from_url(valkey["url"]) as cache,
running_app(cache_url=valkey["url"]) as http,
):
alice = await register(http, "alice")
directory = await resolve(http, SessionDirectory)
assert isinstance(directory, CachedSessionDirectory)
origin = directory._origin
stale: list[Session | None] = []
entered, released = asyncio.Event(), asyncio.Event()
class SlowOrigin:
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
stale.append(await origin.find(token_hash, now))
entered.set()
await released.wait()
return stale[-1]
directory._origin = SlowOrigin()
async with asyncio.TaskGroup() as group:
reader = group.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
try:
await asyncio.wait_for(entered.wait(), 5)
directory._origin = origin
assert (
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
).status_code == 204
key = key_of(token_of(alice))
assert await cache.get(f"{key}:fill") is None
if loss == "flushall":
await cache.flushall()
elif loss in {"evict", "replacement"}:
await cache.delete(key)
if loss == "replacement":
await cache.set(f"{key}:fill", "another-reader", px=1000)
finally:
released.set()
assert reader.result().status_code == 200
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
@pytest.mark.parametrize("loss", ["flushall", "evict"])
async def test_cache_loss_before_logout_commit_cannot_refill_deleted_session(
valkey: dict[str, str], monkeypatch: pytest.MonkeyPatch, loss: str
) -> None:
revoked, release_commit, reading = asyncio.Event(), asyncio.Event(), asyncio.Event()
revoke = CachedSessionDirectory.revoke
find = PostgresSessionDirectory.find
async def paused_revoke(self: CachedSessionDirectory, session: Session) -> None:
await revoke(self, session)
revoked.set()
await release_commit.wait()
async def observed_find(
self: PostgresSessionDirectory, token_hash: bytes, now: datetime
) -> Session | None:
reading.set()
return await find(self, token_hash, now)
async with (
Redis.from_url(valkey["url"]) as cache,
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
monkeypatch.setattr(CachedSessionDirectory, "revoke", paused_revoke)
async with asyncio.TaskGroup() as group:
logout = group.create_task(
http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
)
try:
await asyncio.wait_for(revoked.wait(), 5)
if loss == "flushall":
await cache.flushall()
else:
await cache.delete(key_of(token_of(alice)))
monkeypatch.setattr(PostgresSessionDirectory, "find", observed_find)
reader = group.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
await asyncio.wait_for(reading.wait(), 5)
done, _ = await asyncio.wait({reader}, timeout=0.1)
assert not done
finally:
release_commit.set()
assert logout.result().status_code == 204
assert reader.result().status_code == 401
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
async def test_flushall_loses_nothing(valkey: dict[str, str]) -> None:
cache = Redis.from_url(valkey["url"])
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
bob = await register(http, "bob")
assert (
await http.delete("/api/v1/auth/sessions/current", headers=actor(bob))
).status_code == 204
await cache.flushall()
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
assert (await http.get("/api/v1/users/me", headers=actor(bob))).status_code == 401
await cache.aclose()
async def test_unreachable_cache_is_bypassed_without_anonymous_access() -> None:
async with running_app(cache_url="redis://127.0.0.1:1/0") as http:
alice = await register(http, "alice")
started = time.perf_counter()
me = await http.get("/api/v1/users/me", headers=actor(alice))
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
assert stranger.status_code == 401
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
+107
View File
@@ -0,0 +1,107 @@
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
TOTAL = CLIENTS * PER_CLIENT
async def drain(client: AsyncClient, chat: dict, reader: dict) -> list[dict]:
collected: list[dict] = []
cursor: str | None = None
while True:
query = "?limit=100" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
page = (
await client.get(f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader))
).json()
collected.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return collected
async def flood(client: AsyncClient, chat: dict, sender: dict) -> list[int]:
async def writer(worker: int) -> list[int]:
codes = []
for index in range(PER_CLIENT):
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"нагрузка-{worker}-{index}"},
headers=keyed(sender),
)
codes.append(response.status_code)
return codes
batches = await asyncio.gather(*(writer(worker) for worker in range(CLIENTS)))
return [code for batch in batches for code in batch]
async def test_hundred_messages_from_ten_clients(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
codes = await flood(client, chat, alice)
assert codes.count(201) == TOTAL, f"неуспешные ответы: {set(codes) - {201}}"
history = await drain(client, chat, bob)
assert len(history) == TOTAL
assert len({item["id"] for item in history}) == TOTAL
assert len({item["text"] for item in history}) == TOTAL
keys = [(item["created_at"], item["id"]) for item in history]
assert keys == sorted(keys), "история не упорядочена по (created_at, id)"
stamps = [item["created_at"] for item in history]
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)))
codes = [response.status_code for response in responses]
assert codes.count(201) == 1
assert codes.count(409) == len(codes) - 1
async def test_parallel_chat_creation_is_atomic(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
responses = await asyncio.gather(
*(
client.post(
"/api/v1/chats",
json={"title": f"Чат {index}", "member_ids": [alice["id"], bob["id"]]},
headers=actor(alice),
)
for index in range(20)
)
)
assert all(response.status_code == 201 for response in responses)
listed = (await client.get("/api/v1/chats?limit=100", headers=actor(bob))).json()
assert len(listed["items"]) == 20
keys = [(item["created_at"], item["id"]) for item in listed["items"]]
assert keys == sorted(keys)
+197
View File
@@ -0,0 +1,197 @@
import asyncio
from urllib.parse import quote
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
async def drain_history(client: AsyncClient, chat: dict, reader: dict) -> list[dict]:
collected: list[dict] = []
cursor: str | None = None
while True:
query = "?limit=100" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
page = (
await client.get(f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader))
).json()
collected.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return collected
async def test_registration_is_visible_to_chats_immediately() -> None:
async with running_app() as client:
for _ in range(REGISTRATIONS):
user = await register(client, "race")
response = await client.post(
"/api/v1/chats",
json={"title": "Сразу после регистрации", "member_ids": [user["id"]]},
headers=actor(user),
)
assert response.status_code == 201, response.text
async def test_parallel_registrations_are_all_usable_as_members() -> None:
async with running_app() as client:
alice = await register(client, "alice")
bodies = [new_user(f"par{index}") for index in range(REGISTRATIONS)]
responses = await asyncio.gather(
*(client.post("/api/v1/users", json=body) for body in bodies)
)
assert all(response.status_code == 201 for response in responses)
created = [response.json()["id"] for response in responses]
chat = await client.post(
"/api/v1/chats",
json={"title": "Все параллельные", "member_ids": [alice["id"], *created]},
headers=actor(alice),
)
assert chat.status_code == 201, chat.text
assert len(chat.json()["member_ids"]) == REGISTRATIONS + 1
async def test_rejected_registration_leaves_no_trace() -> None:
async with running_app() as client:
alice = await register(client, "alice")
duplicate = await client.post(
"/api/v1/users",
json={"username": alice["username"], "display_name": "Двойник", "password": PASSWORD},
)
assert duplicate.status_code == 409
invalid = await client.post(
"/api/v1/users", json={"username": "AB", "display_name": "", "password": PASSWORD}
)
assert invalid.status_code == 400
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:
title = f"Откат {uuid4().hex}"
async with running_app() as client:
alice = await register(client, "alice")
before = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json()
rejected = await client.post(
"/api/v1/chats",
json={"title": title, "member_ids": [alice["id"], str(uuid4())]},
headers=actor(alice),
)
assert rejected.status_code == 400
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(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:
async with running_app() as client:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
assert (
await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": " "},
headers=keyed(alice),
)
).status_code == 400
assert (
await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "чужое"},
headers=keyed(eve),
)
).status_code == 404
assert await drain_history(client, chat, alice) == []
async def test_confirmed_write_is_visible_to_next_read() -> None:
async with running_app() as client:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
for index in range(30):
posted = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"подтверждение {index}"},
headers=keyed(alice),
)
assert posted.status_code == 201
history = await drain_history(client, chat, bob)
assert history[-1]["id"] == posted.json()["id"]
assert len(history) == index + 1
async def test_parallel_writes_across_zones_keep_counts_consistent() -> None:
async with running_app() as client:
alice = await register(client, "alice")
chats = [await make_chat(client, alice) for _ in range(4)]
async def writer(chat: dict, worker: int) -> None:
for index in range(10):
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"поток-{worker}-{index}"},
headers=keyed(alice),
)
assert response.status_code == 201
async def registrar(index: int) -> str:
return (await register(client, f"parallel{index}"))["id"]
results = await asyncio.gather(
*(writer(chat, number) for number, chat in enumerate(chats)),
*(registrar(index) for index in range(10)),
)
registered = [item for item in results if isinstance(item, str)]
assert len(set(registered)) == 10
for chat in chats:
history = await drain_history(client, chat, alice)
assert len(history) == 10
assert len({item["id"] for item in history}) == 10
keys = [(item["created_at"], item["id"]) for item in history]
assert keys == sorted(keys)
async def test_chat_membership_survives_parallel_reads_and_writes() -> None:
async with running_app() as client:
alice = await register(client, "alice")
bob = await register(client, "bob")
eve = await register(client, "eve")
chat = await make_chat(client, alice, bob)
async def write(index: int) -> None:
await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"параллельно {index}"},
headers=keyed(alice),
)
async def intruder() -> int:
response = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(eve))
return response.status_code
results = await asyncio.gather(
*(write(index) for index in range(20)),
*(intruder() for _ in range(20)),
)
assert {code for code in results if isinstance(code, int)} == {404}
assert len(await drain_history(client, chat, bob)) == 20
+26
View File
@@ -0,0 +1,26 @@
import pytest
from opentelemetry.sdk.trace.sampling import Decision
from opentelemetry.trace import SpanKind
from conftest import actor, register, running_app
from messenger.shared.infrastructure.telemetry import ServerRoots
@pytest.mark.parametrize("enabled", [False, True])
async def test_controlled_errors_are_opt_in(enabled: bool) -> None:
async with running_app(cost_experiment=enabled) as client:
user = await register(client, "cost")
result = await client.get(
"/api/v1/users/me", headers={**actor(user), "X-Lab-Cost": "error"}
)
assert result.status_code == (503 if enabled else 200)
assert (await client.get("/api/v1/users/me", headers=actor(user))).status_code == 200
def test_head_zero_drops_roots_and_full_keeps_them() -> None:
for kind in (SpanKind.SERVER, SpanKind.PRODUCER, SpanKind.CONSUMER):
assert ServerRoots(0).should_sample(None, 42, "root", kind).decision == Decision.DROP
assert (
ServerRoots(1).should_sample(None, 42, "root", kind).decision
== Decision.RECORD_AND_SAMPLE
)
+130
View File
@@ -0,0 +1,130 @@
import json
import os
import signal
import socket
import subprocess
import sys
import time
from pathlib import Path
import httpx
from conftest import DATABASE, free_port, new_user
from messenger.shared.infrastructure.readiness import DRAINING
DRAIN = 1.0
SHUTDOWN = 3
GUNICORN = (
"-m",
"gunicorn",
"--config",
"python:messenger.gunicorn_conf",
"messenger.main:create_app()",
)
async def test_draining_replica_is_not_ready_but_alive(client: httpx.AsyncClient) -> None:
DRAINING.set()
try:
ready = await client.get("/health/ready")
live = await client.get("/health/live")
finally:
DRAINING.clear()
assert ready.status_code == 503
assert ready.json()["error"]["code"] == "unavailable"
assert ready.headers["X-Instance-Id"]
assert live.status_code == 200
assert (await client.get("/health/ready")).status_code == 200
def status(port: int, path: str) -> int:
try:
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 = (
"POST /api/v1/users HTTP/1.1\r\nHost: replica\r\nContent-Type: application/json\r\n"
f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n"
)
connection = socket.create_connection(("127.0.0.1", port), timeout=5)
connection.sendall(head.encode() + body[:8])
return connection, body[8:]
def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests(tmp_path: Path) -> None:
port = free_port()
settings = {
"HOST": "127.0.0.1",
"PORT": str(port),
"WEB_CONCURRENCY": "2",
"DATABASE_URL": DATABASE["url"],
"CURSOR_SECRET": "test-secret-for-cursors",
"S3_ACCESS_KEY_ID": "test-key",
"S3_SECRET_ACCESS_KEY": "test-secret-key",
"LOG_LEVEL": "WARNING",
"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=log,
stderr=log,
)
try:
deadline = time.monotonic() + 30
while status(port, "/health/ready") != 200:
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)
answer = pending.recv(64).split(b"\r\n")[0].decode()
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
+112
View File
@@ -0,0 +1,112 @@
import asyncio
from dataclasses import fields
from datetime import UTC, datetime
from uuid import uuid4
from httpx import ASGITransport, AsyncClient
from conftest import keyed, make_chat, register, split_settings
from fakes import NullLogger
from messenger.identity.domain.events import UserRegistered
from messenger.main import create_app
from messenger.messaging.domain.events import MessagePosted
from messenger.shared.application.messagebus import EventBus, InMemoryEventPublisher
def posted() -> MessagePosted:
return MessagePosted(
message_id=uuid4(),
chat_id=uuid4(),
sender_id=uuid4(),
text_length=5,
created_at=datetime.now(UTC),
)
async def test_event_has_no_message_text() -> None:
names = {field.name for field in fields(posted())}
assert names == {"name", "message_id", "chat_id", "sender_id", "text_length", "created_at"}
async def test_every_subscriber_receives_event() -> None:
bus = EventBus(NullLogger())
seen: list[str] = []
async def first(_event: MessagePosted) -> None:
seen.append("first")
async def second(_event: MessagePosted) -> None:
seen.append("second")
bus.subscribe(MessagePosted, first)
bus.subscribe(MessagePosted, second)
bus.start()
await InMemoryEventPublisher(bus).publish([posted()])
await bus.stop()
assert sorted(seen) == ["first", "second"]
async def test_failing_subscriber_does_not_block_others() -> None:
bus = EventBus(NullLogger())
survived: list[str] = []
async def broken(_event: MessagePosted) -> None:
raise RuntimeError("обработчик упал")
async def healthy(_event: MessagePosted) -> None:
survived.append("ok")
bus.subscribe(MessagePosted, broken)
bus.subscribe(MessagePosted, healthy)
bus.start()
await InMemoryEventPublisher(bus).publish([posted()])
await bus.stop()
assert survived == ["ok"]
async def test_queue_overflow_drops_events_without_raising() -> None:
bus = EventBus(NullLogger(), max_queue=16)
async def never_called(_event: MessagePosted) -> None:
raise AssertionError("обработчик не должен вызываться без запущенной шины")
bus.subscribe(MessagePosted, never_called)
publisher = InMemoryEventPublisher(bus)
await publisher.publish([posted() for _ in range(64)])
assert bus.dropped > 0
assert bus.pending <= 16
async def test_publication_does_not_delay_response() -> None:
app = create_app(**split_settings(log_level="CRITICAL"))
async with (
app.router.lifespan_context(app),
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
):
alice = await register(http, "alice")
chat = await make_chat(http, alice)
bus = await app.state.dishka_container.get(EventBus)
slow = asyncio.Event()
async def blocker(_event: MessagePosted) -> None:
await slow.wait()
bus.subscribe(MessagePosted, blocker)
response = await asyncio.wait_for(
http.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "не ждём обработчик"},
headers=keyed(alice),
),
timeout=2,
)
assert response.status_code == 201
slow.set()
async def test_null_logger_hides_everything() -> None:
logger = NullLogger()
logger.info("x", route="/")
logger.warning("x")
logger.error("x")
assert isinstance(UserRegistered, type)
+64
View File
@@ -0,0 +1,64 @@
from uuid import uuid4
from httpx import ASGITransport, AsyncClient
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import HistogramDataPoint, InMemoryMetricReader
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import SpanKind
from conftest import new_user, split_settings
from fakes import MemoryStorageProvider
from messenger.main import create_app
from messenger.shared.entrypoints.telemetry import instrument_http
MARKER = "текст-маркер-телеметрии"
async def test_server_spans_and_duration_follow_the_route_template() -> None:
exporter = InMemorySpanExporter()
tracer = TracerProvider(shutdown_on_exit=False)
tracer.add_span_processor(SimpleSpanProcessor(exporter))
reader = InMemoryMetricReader()
app = create_app(**split_settings(), overrides=(MemoryStorageProvider(),))
instrument_http(app, tracer, MeterProvider(metric_readers=[reader], shutdown_on_exit=False))
chat = uuid4()
async with (
app.router.lifespan_context(app),
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
):
created = await http.post("/api/v1/users", json=new_user("otel"))
ready = await http.get("/health/ready")
denied = await http.post(
f"/api/v1/chats/{chat}/messages",
json={"text": MARKER},
headers={"Idempotency-Key": "otel-1", "Authorization": "Bearer not-a-token"},
)
assert (created.status_code, ready.status_code, denied.status_code) == (201, 200, 401)
spans = exporter.get_finished_spans()
servers = {span.name: span for span in spans if span.kind is SpanKind.SERVER}
assert set(servers) == {"POST /api/v1/users", "POST /api/v1/chats/{chat_id}/messages"}
users = servers["POST /api/v1/users"].attributes or {}
assert users["messenger.request_id"] == created.headers["X-Request-Id"]
assert users["http.route"] == "/api/v1/users"
assert users["http.response.status_code"] == 201
exported = repr([dict(span.attributes or {}) for span in spans])
assert MARKER not in exported
assert "not-a-token" not in exported
data = reader.get_metrics_data()
assert data is not None
points = [
point
for resource in data.resource_metrics
for scope in resource.scope_metrics
for metric in scope.metrics
if metric.name == "http.server.request.duration" and metric.unit == "s"
for point in metric.data.data_points
if isinstance(point, HistogramDataPoint)
]
routes = {(point.attributes or {}).get("http.route") for point in points}
assert routes == {"/api/v1/users", "/api/v1/chats/{chat_id}/messages"}
assert str(chat) not in repr([dict(point.attributes or {}) for point in points])
+162
View File
@@ -0,0 +1,162 @@
import asyncio
from typing import Any
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", "ключ"]
async def send(http: AsyncClient, chat: dict, user: dict, text: str, key: str) -> Response:
return await http.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=keyed(user, key)
)
async def history(http: AsyncClient, chat: dict, user: dict) -> list[dict[str, Any]]:
response = await http.get(f"/api/v1/chats/{chat['id']}/messages?limit=100", headers=actor(user))
return response.json()["items"]
async def test_replay_returns_the_same_message(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
first = await send(client, chat, alice, "один раз", "replay-1")
again = await send(client, chat, alice, "один раз", "replay-1")
assert first.status_code == again.status_code == 201
assert again.json() == first.json()
assert [item["id"] for item in await history(client, chat, alice)] == [first.json()["id"]]
async def test_same_json_in_other_layout_is_a_replay(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
first = await send(client, chat, alice, "форма", "layout-1")
again = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
content='{ "text" : "форма" }'.encode(),
headers={**keyed(alice, "layout-1"), "Content-Type": "application/json"},
)
assert again.status_code == 201
assert again.json() == first.json()
async def test_other_body_with_same_key_conflicts(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
await send(client, chat, alice, "первое", "conflict-1")
response = await send(client, chat, alice, "другое", "conflict-1")
assert response.status_code == 409
assert response.json()["error"]["code"] == "conflict"
assert len(await history(client, chat, alice)) == 1
async def test_missing_key_is_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "без ключа"}, headers=actor(alice)
)
assert response.status_code == 400
assert response.json()["error"]["code"] == "invalid_request"
assert await history(client, chat, alice) == []
@pytest.mark.parametrize("key", INVALID_KEYS, ids=range(len(INVALID_KEYS)))
async def test_malformed_key_is_rejected(client: AsyncClient, key: str) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
headers = {**actor(alice), "Idempotency-Key": key}
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "ключ плохой"},
headers={name.encode(): value.encode() for name, value in headers.items()},
)
assert response.status_code == 400
assert await history(client, chat, alice) == []
async def test_rejected_attempt_does_not_take_the_key(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
assert (await send(client, chat, alice, "", "spare-1")).status_code == 400
assert (await send(client, chat, eve, "чужое", "spare-1")).status_code == 404
assert (await send(client, chat, alice, "теперь можно", "spare-1")).status_code == 201
async def test_key_is_scoped_by_user_and_chat(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
other = await make_chat(client, alice)
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:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
assert (await send(client, chat, alice, "до выхода", "recheck-1")).status_code == 201
assert (await send(client, chat, eve, "до выхода", "recheck-1")).status_code == 404
logout = await client.delete("/api/v1/auth/sessions/current", headers=actor(alice))
assert logout.status_code == 204
assert (await send(client, chat, alice, "до выхода", "recheck-1")).status_code == 401
async def test_expired_key_starts_over() -> None:
async with running_app(idempotency_ttl_seconds=1) as http:
alice = await register(http, "alice")
chat = await make_chat(http, alice)
first = await send(http, chat, alice, "давно", "expire-1")
await asyncio.sleep(1.1)
later = await send(http, chat, alice, "заново", "expire-1")
assert later.status_code == 201
assert later.json()["id"] != first.json()["id"]
assert len(await history(http, chat, alice)) == 2
async def test_concurrent_retries_through_two_replicas_store_one_message() -> None:
async with (
running_app(instance_id="replica-a") as first,
running_app(instance_id="replica-b") as second,
):
alice = await register(first, "alice")
chat = await make_chat(first, alice)
key, text = uuid4().hex, "гонка ключа"
responses = await asyncio.gather(
*(send(http, chat, alice, text, key) for http in (first, second) * 4)
)
assert {response.status_code for response in responses} == {201}
assert {response.headers["X-Instance-Id"] for response in responses} == {
"replica-a",
"replica-b",
}
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(func.count()).select_from(IdempotencyKeyRow).where(IdempotencyKeyRow.key == key)
)
== 1
)
+64
View File
@@ -0,0 +1,64 @@
import socket
from uuid import uuid4
from httpx import ASGITransport, AsyncClient, Response
from conftest import actor, register, running_app, split_settings
from messenger.main import create_app
from messenger.shared.config import PlatformSettings
REPLICA = "replica-7f3a"
def stamped(response: Response) -> bool:
return bool(response.headers.get("X-Request-Id")) and (
response.headers.get("X-Instance-Id") == REPLICA
)
async def test_every_response_names_the_replica() -> None:
async with running_app(instance_id=REPLICA) as http:
alice = await register(http, "alice")
probes = [
await http.get("/health/live"),
await http.get("/health/ready"),
await http.get("/api/v1/users/me", headers=actor(alice)),
await http.get("/api/v1/users/me"),
await http.get(f"/api/v1/chats/{uuid4()}", headers=actor(alice)),
await http.get("/nothing-here"),
await http.delete("/health/live"),
await http.post("/api/v1/users", json={"username": "x"}),
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice)),
]
assert [probe.status_code for probe in probes] == [200, 200, 200, 401, 404, 404, 404, 400, 204]
assert all(stamped(probe) for probe in probes)
async def test_rejected_body_names_the_replica() -> None:
async with running_app(instance_id=REPLICA, max_body_bytes=4096) as http:
response = await http.post("/api/v1/users", content=b"x" * 5000)
assert response.status_code == 413
assert stamped(response)
async def test_unhandled_error_names_the_replica() -> None:
app = create_app(**split_settings(instance_id=REPLICA))
async def boom() -> None:
raise RuntimeError("сбой")
app.add_api_route("/health/boom", boom)
transport = ASGITransport(app=app, raise_app_exceptions=False)
async with (
app.router.lifespan_context(app),
AsyncClient(transport=transport, base_url="http://testserver") as http,
):
response = await http.get("/health/boom")
assert response.status_code == 500
assert response.json()["error"]["code"] == "internal_error"
assert stamped(response)
def test_replica_defaults_to_container_hostname() -> None:
settings = PlatformSettings.model_validate({"database_url": "postgresql://u@h/d"})
assert settings.instance_id == socket.gethostname()
+62
View File
@@ -0,0 +1,62 @@
import asyncio
import json
import os
import sys
from httpx import AsyncClient
from test_pipeline import accepted, job_of
from conftest import DATABASE
PROBE = """
import asyncio, os
from datetime import timedelta
from uuid import uuid4
from messenger.worker import create_worker
from messenger.attachments.infrastructure.postgres import PostgresAttachmentsUnitOfWork
from messenger.attachments.entrypoints.schemas import JobMessage
from messenger.shared.infrastructure.postgres import Database
async def main():
db = Database(os.environ['TEST_DATABASE_URL'], max_size=2, connect_timeout=2,
acquire_timeout=2, command_timeout=3)
job = JobMessage.model_validate_json(os.environ['TEST_JOB']).job()
async def claim():
uow = PostgresAttachmentsUnitOfWork(db)
async with uow.transaction():
claimed = await uow.jobs.claim(job, uuid4(), timedelta(seconds=5))
assert claimed is not None
assert claimed.lease.job.attempt == 1
assert claimed.lease.job.created_at == job.created_at
try:
await asyncio.gather(claim(), claim())
finally:
await db.close()
asyncio.run(main())
"""
async def test_cold_worker_claim_returning_is_stable(client: AsyncClient) -> None:
_, _, ident = await accepted(client)
job = await job_of(ident)
for seed in range(24):
child = await asyncio.create_subprocess_exec(
sys.executable,
"-c",
PROBE,
env={
**os.environ,
"PYTHONHASHSEED": str(seed),
"TEST_DATABASE_URL": DATABASE["url"],
"TEST_JOB": json.dumps(job.payload()),
},
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
try:
_, errors = await asyncio.wait_for(child.communicate(), 20)
finally:
if child.returncode is None:
child.kill()
await child.wait()
assert child.returncode == 0, f"seed={seed}: {errors.decode()}"
@@ -0,0 +1,149 @@
from typing import Any
from uuid import uuid4
import pytest
from httpx import AsyncClient
from conftest import actor, keyed, make_chat, register, resolve
from fakes import MemoryObjectStorage
from messenger.attachments.application.ports import ObjectStorage
from pictures import SAMPLE
from pipeline import settle
async def attach(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
response = await http.post(
f"/api/v1/chats/{chat['id']}/attachments?filename=a.png",
content=SAMPLE,
headers={**actor(user), "Content-Type": "image/png"},
)
assert response.status_code == 202, response.text
return response.json()["id"]
async def send(
http: AsyncClient, user: dict[str, Any], chat: dict[str, Any], body: Any, key: str | None = None
) -> Any:
return await http.post(
f"/api/v1/chats/{chat['id']}/messages", json=body, headers=keyed(user, key)
)
async def scene(http: AsyncClient) -> tuple[dict[str, Any], ...]:
alice, bob, eve = [await register(http, label) for label in ("alice", "bob", "eve")]
return alice, bob, eve, await make_chat(http, alice, bob), await make_chat(http, alice)
async def test_text_message_carries_empty_list(client: AsyncClient) -> None:
alice, _, _, chat, _ = await scene(client)
response = await send(client, alice, chat, {"text": "привет"})
assert response.status_code == 201
assert response.json()["attachment_ids"] == []
async def test_empty_text_with_attachment_keeps_order(client: AsyncClient) -> None:
alice, bob, _, chat, _ = await scene(client)
ids = [await attach(client, alice, chat) for _ in range(3)]
ordered = [ids[2], ids[0], ids[1]]
response = await send(client, bob, chat, {"text": "", "attachment_ids": ordered})
assert response.status_code == 201, response.text
message = response.json()
assert message["attachment_ids"] == ordered
again = await send(client, alice, chat, {"text": "ещё раз", "attachment_ids": [ids[0]]})
assert again.status_code == 201
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(bob))
assert history.json()["items"] == [message, again.json()]
async def test_replay_with_attachments_and_default_list(client: AsyncClient) -> None:
alice, _, _, chat, _ = await scene(client)
first_id, second_id = await attach(client, alice, chat), await attach(client, alice, chat)
body = {"text": "", "attachment_ids": [first_id, second_id]}
first = await send(client, alice, chat, body, "with-files")
assert (await send(client, alice, chat, body, "with-files")).json() == first.json()
swapped = {"text": "", "attachment_ids": [second_id, first_id]}
assert (await send(client, alice, chat, swapped, "with-files")).status_code == 409
plain = await send(client, alice, chat, {"text": "x"}, "plain")
explicit = await send(client, alice, chat, {"attachment_ids": [], "text": "x"}, "plain")
assert (explicit.status_code, explicit.json()) == (201, plain.json())
async def test_attachment_of_another_chat_or_unknown(client: AsyncClient) -> None:
alice, _, _, chat, solo = await scene(client)
foreign = await attach(client, alice, solo)
for ids in ([foreign], [str(uuid4())]):
response = await send(client, alice, chat, {"text": "x", "attachment_ids": ids})
assert response.status_code == 404
assert response.json()["error"]["code"] == "not_found"
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))
assert history.json()["items"] == []
@pytest.mark.parametrize("kind", ["eleven", "duplicate", "not-uuid", "empty", "blank"])
async def test_invalid_attachment_lists(client: AsyncClient, kind: str) -> None:
alice, _, _, chat, _ = await scene(client)
file = await attach(client, alice, chat)
body = {
"eleven": {"text": "x", "attachment_ids": [file] + [str(uuid4()) for _ in range(10)]},
"duplicate": {"text": "x", "attachment_ids": [file, file]},
"not-uuid": {"text": "x", "attachment_ids": ["not-a-uuid"]},
"empty": {"text": "", "attachment_ids": []},
"blank": {"text": " ", "attachment_ids": [file]},
}[kind]
response = await send(client, alice, chat, body)
assert response.status_code == 400, response.text
assert response.json()["error"]["code"] == "invalid_request"
async def test_outsider_gets_not_found_before_validation(client: AsyncClient) -> None:
alice, _, eve, chat, _ = await scene(client)
file = await attach(client, alice, chat)
for body in ({"text": "", "attachment_ids": []}, {"text": "x", "attachment_ids": [file] * 11}):
assert (await send(client, eve, chat, body)).status_code == 404
async def test_one_attachment_in_several_messages(client: AsyncClient) -> None:
alice, bob, _, chat, _ = await scene(client)
file = await attach(client, alice, chat)
for user in (alice, bob):
response = await send(client, user, chat, {"text": "", "attachment_ids": [file]})
assert response.status_code == 201
assert response.json()["attachment_ids"] == [file]
async def broken(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
attachment_id = await attach(http, user, chat)
store = await resolve(http, ObjectStorage)
assert isinstance(store, MemoryObjectStorage)
store.objects[f"staging/{attachment_id}"] = (b"\x89PNG\r\n\x1a\n broken", "image/png")
await settle(http)
return attachment_id
async def test_queued_attachment_is_sent_and_failed_is_conflict(client: AsyncClient) -> None:
alice, bob, _, chat, _ = await scene(client)
queued = await attach(client, alice, chat)
early = await send(client, alice, chat, {"text": "", "attachment_ids": [queued]})
assert early.status_code == 201, early.text
failed = await broken(client, bob, chat)
meta = (await client.get(f"/api/v1/attachments/{failed}", headers=actor(alice))).json()
assert (meta["status"], meta["error_code"]) == ("failed", "invalid_image")
refused = await send(client, alice, chat, {"text": "x", "attachment_ids": [queued, failed]})
assert refused.status_code == 409
assert refused.json()["error"]["code"] == "conflict"
content = await client.get(f"/api/v1/attachments/{failed}/content", headers=actor(bob))
assert content.status_code == 409
async def test_replay_survives_a_later_failure(client: AsyncClient) -> None:
alice, _, _, chat, _ = await scene(client)
attachment_id = await attach(client, alice, chat)
body = {"text": "", "attachment_ids": [attachment_id]}
first = await send(client, alice, chat, body, key="replay-after-failure")
store = await resolve(client, ObjectStorage)
assert isinstance(store, MemoryObjectStorage)
store.objects[f"staging/{attachment_id}"] = (b"garbage", "image/png")
await settle(client)
again = await send(client, alice, chat, body, key="replay-after-failure")
assert (first.status_code, again.status_code) == (201, 201)
assert again.json() == first.json()
+548
View File
@@ -0,0 +1,548 @@
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 typing import Any
from uuid import uuid4
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.dialects.postgresql import JSONB
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.pool import NullPool
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
VERSIONS = [
"0001_init",
"0002_idempotency_keys",
"0003_attachments",
"0004_jobs",
"0005_failed_registry",
"0006_attachment_quarantine",
"0007_trace_context",
"0008_login_budget",
]
TABLES = [
UserRow,
SessionRow,
ChatRow,
ChatMemberRow,
MessageRow,
IdempotencyKeyRow,
AttachmentRow,
JobRow,
OutboxRow,
JobEventRow,
VariantRow,
MessageAttachmentRow,
]
@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:
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:
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: dict[str, Any] = {}
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),
}
if model in (JobRow, OutboxRow):
missing["trace_context"] = literal({}, type_=JSONB)
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:
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_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_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:
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:
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:
with pytest.raises(IntegrityError) as failure:
async with sql_connection() as connection:
await connection.execute(
insert(MessageRow).values(
id=uuid4(), chat_id=uuid4(), sender_id=uuid4(), text="x", created_at=func.now()
)
)
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
async def test_key_needs_a_member_and_a_message() -> None:
with pytest.raises(IntegrityError) as failure:
async with sql_connection() as connection:
await connection.execute(
insert(IdempotencyKeyRow).values(
chat_id=uuid4(),
user_id=uuid4(),
key="k-1",
fingerprint=b"x" * 32,
message_id=uuid4(),
created_at=func.now(),
)
)
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 = '0008_login_budget'\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:
with pytest.raises(IntegrityError, match="attachments_owner_fkey"):
async with sql_connection() as connection:
await connection.execute(
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(),
)
)
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(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,
)
)
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(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))
+196
View File
@@ -0,0 +1,196 @@
from uuid import uuid4
import pytest
from httpx import AsyncClient
from conftest import PASSWORD, actor, keyed, make_chat, register
ERROR_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
}
def assert_error(response, expected_status: int) -> None:
assert response.status_code == expected_status, response.text
assert response.headers.get("content-type", "").startswith("application/json")
body = response.json()
assert set(body) == {"error"}
assert set(body["error"]) == {"code", "message", "request_id"}
assert body["error"]["code"] == ERROR_CODES[expected_status]
assert body["error"]["message"]
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
async def test_malformed_json(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/users",
content=b'{"username": ',
headers={"Content-Type": "application/json"},
)
assert_error(response, 400)
async def test_unexpected_field(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/users",
json={"username": "abc_def", "display_name": "X", "password": PASSWORD, "role": "admin"},
)
assert_error(response, 400)
async def test_wrong_types(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/users", json={"username": 1, "display_name": True, "password": 12345678901234}
)
assert_error(response, 400)
@pytest.mark.parametrize(
"body",
[
{"username": "Alice", "display_name": "X", "password": PASSWORD},
{"username": "ab", "display_name": "X", "password": PASSWORD},
{"username": "alice_01\n", "display_name": "X", "password": PASSWORD},
{"username": "abc_def", "display_name": "", "password": PASSWORD},
{"username": "abc_def", "display_name": " ", "password": PASSWORD},
{"username": "abc_def", "display_name": "x" * 101, "password": PASSWORD},
{"username": "abc_def", "display_name": "X", "password": "short"},
{"username": "abc_def", "display_name": "X", "password": "x" * 129},
{"username": "abc_def", "display_name": "X", "password": " " * 20},
{"username": "abc_def", "display_name": "X"},
{"username": "abc_def", "password": PASSWORD},
],
)
async def test_invalid_registration(client: AsyncClient, body: dict) -> None:
assert_error(await client.post("/api/v1/users", json=body), 400)
async def test_duplicate_username(client: AsyncClient) -> None:
alice = await register(client, "alice")
repeat = await client.post(
"/api/v1/users",
json={"username": alice["username"], "display_name": "Другая", "password": PASSWORD},
)
assert_error(repeat, 409)
async def test_missing_identity(client: AsyncClient) -> None:
assert_error(await client.get("/api/v1/users/me"), 401)
BAD_AUTHORIZATIONS = [
"",
"Bearer",
"Bearer ",
"Bearer not a token",
"Bearer " + "x" * 43,
"Token abcdef",
"11111111-1111-4111-8111-111111111111",
]
@pytest.mark.parametrize("raw", BAD_AUTHORIZATIONS)
async def test_invalid_bearer(client: AsyncClient, raw: str) -> None:
response = await client.get("/api/v1/users/me", headers={"Authorization": raw})
assert_error(response, 401)
assert response.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
async def test_user_id_header_alone_is_ignored(client: AsyncClient) -> None:
alice = await register(client, "alice")
response = await client.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]})
assert_error(response, 401)
async def test_identity_checked_before_body(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/chats",
content=b"{broken",
headers={"Content-Type": "application/json"},
)
assert_error(response, 401)
async def test_empty_message_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
for text in ("", " ", "\n\t"):
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": text},
headers=keyed(alice),
)
assert_error(response, 400)
async def test_long_message_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "я" * 4001},
headers=keyed(alice),
)
assert_error(response, 400)
async def test_sender_id_not_accepted(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "подмена", "sender_id": bob["id"]},
headers=keyed(alice),
)
assert_error(response, 400)
@pytest.mark.parametrize(
"body",
[
{"title": "Чат", "member_ids": []},
{"title": "", "member_ids": None},
{"title": " ", "member_ids": None},
{"title": "Чат", "member_ids": ["не-uuid"]},
{"title": "Чат", "member_ids": [1]},
{"title": "Чат", "member_ids": "не-список"},
],
)
async def test_invalid_chat_creation(client: AsyncClient, body: dict) -> None:
alice = await register(client, "alice")
payload = dict(body)
if payload["member_ids"] is None:
payload["member_ids"] = [alice["id"]]
response = await client.post("/api/v1/chats", json=payload, headers=actor(alice))
assert_error(response, 400)
async def test_creator_must_be_member(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
response = await client.post(
"/api/v1/chats",
json={"title": "Чат", "member_ids": [bob["id"]]},
headers=actor(alice),
)
assert_error(response, 400)
async def test_unknown_member_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
response = await client.post(
"/api/v1/chats",
json={"title": "Чат", "member_ids": [alice["id"], str(uuid4())]},
headers=actor(alice),
)
assert_error(response, 400)
async def test_bad_chat_id_in_path(client: AsyncClient) -> None:
alice = await register(client, "alice")
assert_error(await client.get("/api/v1/chats/не-uuid", headers=actor(alice)), 400)
+95
View File
@@ -0,0 +1,95 @@
from uuid import uuid4
import pytest
from httpx import AsyncClient, Response
from conftest import PASSWORD, actor, basic, keyed, make_chat, new_user, register
NUL_TEXTS = ["\x00", "\x00abc", "abc\x00def", "abc\x00"]
def rejected(response: Response, status: int, code: str) -> None:
assert response.status_code == status, response.text
assert response.headers["content-type"].startswith("application/json")
assert response.headers["X-Instance-Id"]
assert response.headers["X-Request-Id"]
assert set(response.json()) == {"error"}
error = response.json()["error"]
assert set(error) == {"code", "message", "request_id"}
assert error["code"] == code
assert error["message"]
assert error["request_id"] == response.headers["X-Request-Id"]
@pytest.mark.parametrize("username", NUL_TEXTS)
async def test_nul_basic_matches_wrong_password(client: AsyncClient, username: str) -> None:
user = await register(client, "nul_login")
responses = []
for name, password in [(user["username"], "wrong-password"), (username, PASSWORD)]:
response = await client.post(
"/api/v1/auth/sessions",
headers={**basic(name, password), "X-Request-Id": "nul-login"},
)
rejected(response, 401, "unauthorized")
assert response.headers["WWW-Authenticate"] == 'Basic realm="messenger", charset="UTF-8"'
responses.append(response.json())
assert responses[0] == responses[1]
@pytest.mark.parametrize("raw", NUL_TEXTS)
async def test_nul_display_name_does_not_create_user(client: AsyncClient, raw: str) -> None:
body = {**new_user("nul_display"), "display_name": raw}
rejected(await client.post("/api/v1/users", json=body), 400, "invalid_request")
response = await client.post("/api/v1/users", json={**body, "display_name": "Алиса 👋"})
assert response.status_code == 201
assert response.json()["display_name"] == "Алиса 👋"
@pytest.mark.parametrize("raw", NUL_TEXTS)
async def test_nul_title_does_not_create_chat(client: AsyncClient, raw: str) -> None:
user = await register(client, "nul_title")
body = {"title": raw, "member_ids": [user["id"]]}
rejected(
await client.post("/api/v1/chats", json=body, headers=actor(user)), 400, "invalid_request"
)
chats = await client.get("/api/v1/chats", headers=actor(user))
assert chats.status_code == 200
assert chats.json()["items"] == []
@pytest.mark.parametrize("raw", NUL_TEXTS)
async def test_nul_message_does_not_take_key(client: AsyncClient, raw: str) -> None:
user = await register(client, "nul_message")
chat = await make_chat(client, user)
path = f"/api/v1/chats/{chat['id']}/messages"
headers = keyed(user)
rejected(await client.post(path, json={"text": raw}, headers=headers), 400, "invalid_request")
history = await client.get(path, headers=actor(user))
assert history.status_code == 200
assert history.json()["items"] == []
text = "Исправлено\tбез потерь\n👋"
first = await client.post(path, json={"text": text}, headers=headers)
again = await client.post(path, json={"text": text}, headers=headers)
assert first.status_code == again.status_code == 201
assert first.json()["text"] == text
assert first.json() == again.json()
assert (await client.get(path, headers=actor(user))).json()["items"] == [first.json()]
async def test_nul_message_does_not_disclose_chat(client: AsyncClient) -> None:
owner = await register(client, "nul_owner")
outsider = await register(client, "nul_outsider")
chat = await make_chat(client, owner)
responses = []
for chat_id in [chat["id"], str(uuid4())]:
response = await client.post(
f"/api/v1/chats/{chat_id}/messages",
json={"text": "abc\x00def"},
headers={**keyed(outsider), "X-Request-Id": "nul-access"},
)
rejected(response, 404, "not_found")
responses.append(response.json())
assert responses[0] == responses[1]
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(owner))
assert history.status_code == 200
assert history.json()["items"] == []
+171
View File
@@ -0,0 +1,171 @@
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,
new_user,
register,
running_app,
split_settings,
)
from messenger.main import create_app
MARKER_TEXT = "маркер-который-не-должен-попасть-в-логи-9f3a"
async def test_health_needs_no_identity(client: AsyncClient) -> None:
for path in ("/health/live", "/health/ready"):
response = await client.get(path)
assert response.status_code == 200
assert response.json() == {"status": "ok"}
assert response.headers["X-Request-Id"]
async def test_every_response_carries_request_id(client: AsyncClient) -> None:
alice = await register(client, "alice")
probes = [
await client.get("/health/live"),
await client.get("/api/v1/users/me", headers=actor(alice)),
await client.get("/api/v1/users/me"),
await client.get(f"/api/v1/chats/{uuid4()}", headers=actor(alice)),
await client.get("/api/v1/unknown-path"),
]
assert all(probe.headers.get("X-Request-Id") for probe in probes)
async def test_client_request_id_is_preserved(client: AsyncClient) -> None:
response = await client.get("/health/live", headers={"X-Request-Id": "trace-42"})
assert response.headers["X-Request-Id"] == "trace-42"
async def test_unknown_public_route_is_404(client: AsyncClient) -> None:
response = await client.get("/nothing-here")
assert response.status_code == 404
assert response.json()["error"]["code"] == "not_found"
async def test_unknown_protected_route_needs_identity(client: AsyncClient) -> None:
anonymous = await client.get("/api/v1/unknown-path")
assert anonymous.status_code == 401
assert set(anonymous.json()["error"]) == {"code", "message", "request_id"}
alice = await register(client, "alice")
identified = await client.get("/api/v1/unknown-path", headers=actor(alice))
assert identified.status_code == 404
async def test_method_not_allowed_is_hidden(client: AsyncClient) -> None:
response = await client.delete("/health/live")
assert response.status_code == 404
assert response.json()["error"]["code"] == "not_found"
async def test_logs_do_not_contain_message_text(capsys) -> None:
app = create_app(**split_settings(log_level="INFO"))
async with (
app.router.lifespan_context(app),
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
):
alice = await register(http, "alice")
chat = await make_chat(http, alice)
response = await http.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": MARKER_TEXT},
headers=keyed(alice),
)
assert response.status_code == 201
captured = capsys.readouterr()
assert MARKER_TEXT not in captured.out
assert MARKER_TEXT not in captured.err
assert alice["display_name"] not in captured.out
assert any("request.handled" in line for line in captured.out.splitlines())
async def test_log_lines_are_json(capsys) -> None:
app = create_app(**split_settings(log_level="INFO"))
async with (
app.router.lifespan_context(app),
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
):
await http.get("/health/live")
for line in capsys.readouterr().out.splitlines():
record = json.loads(line)
assert {"ts", "level", "event"} <= set(record)
async def test_body_limit_returns_413() -> None:
app = create_app(**split_settings(max_body_bytes=4096))
async with (
app.router.lifespan_context(app),
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
):
response = await http.post("/api/v1/users", content=b"x" * 5000)
assert response.status_code == 413
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()
ready = await http.get("/health/ready")
live = await http.get("/health/live")
elapsed = time.perf_counter() - started
assert ready.status_code == 503
assert ready.json()["error"]["code"] == "unavailable"
assert live.status_code == 200
assert elapsed < 2
async def test_protected_request_is_503_not_401_without_database() -> None:
async with running_app(database_url="postgresql://u:p@127.0.0.1:1/none") as http:
response = await http.get(
"/api/v1/users/me", headers={"Authorization": "Bearer " + "x" * 43}
)
assert response.status_code == 503
assert response.json()["error"]["code"] == "unavailable"
assert response.json()["error"]["request_id"] == response.headers["X-Request-Id"]
async def test_state_survives_new_process() -> None:
async with running_app() as http:
alice = await register(http, "alice")
chat = await make_chat(http, alice)
async with running_app() as http:
me = await http.get("/api/v1/users/me", headers=actor(alice))
listed = await http.get("/api/v1/chats?limit=100", headers=actor(alice))
assert me.json() == alice
assert [item["id"] for item in listed.json()["items"]] == [chat["id"]]
async def test_logs_do_not_contain_credentials(capsys) -> None:
async with running_app(log_level="INFO") as http:
alice = await register(http, "secret")
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
output = capsys.readouterr()
captured = output.out + output.err
assert PASSWORD not in captured
assert actor(alice)["Authorization"].split()[1] not in captured
assert "audit.session_opened" in captured
+156
View File
@@ -0,0 +1,156 @@
from urllib.parse import quote
import pytest
from httpx import AsyncClient
from conftest import actor, keyed, make_chat, register
TOTAL = 12
async def fill(client: AsyncClient, chat: dict, sender: dict, count: int) -> list[str]:
texts = []
for index in range(count):
text = f"сообщение {index:02d}"
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": text},
headers=keyed(sender),
)
assert response.status_code == 201, response.text
texts.append(text)
return texts
async def walk(client: AsyncClient, chat: dict, reader: dict, limits: list[int]) -> list[str]:
collected: list[str] = []
cursor: str | None = None
step = 0
while True:
limit = limits[min(step, len(limits) - 1)]
query = f"?limit={limit}"
if cursor:
query += f"&cursor={quote(cursor, safe='')}"
response = await client.get(
f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader)
)
assert response.status_code == 200, response.text
page = response.json()
assert len(page["items"]) <= limit
collected.extend(item["text"] for item in page["items"])
cursor = page["next_cursor"]
step += 1
if cursor is None:
return collected
async def test_full_walk_has_no_gaps_or_repeats(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
expected = await fill(client, chat, alice, TOTAL)
assert await walk(client, chat, bob, [5]) == expected
async def test_limit_may_change_between_pages(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
expected = await fill(client, chat, alice, TOTAL)
assert await walk(client, chat, alice, [1, 7, 3, 100]) == expected
async def test_last_page_closes_history(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
await fill(client, chat, alice, 2)
first = (
await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=2", headers=actor(alice))
).json()
assert len(first["items"]) == 2
assert first["next_cursor"] is None
async def test_cursor_is_shared_between_members(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
await fill(client, chat, alice, 3)
page = (
await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=actor(alice))
).json()
cursor = quote(page["next_cursor"], safe="")
response = await client.get(
f"/api/v1/chats/{chat['id']}/messages?limit=1&cursor={cursor}", headers=actor(bob)
)
assert response.status_code == 200
async def test_cursor_from_another_chat_is_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
first = await make_chat(client, alice)
second = await make_chat(client, alice)
await fill(client, first, alice, 3)
await fill(client, second, alice, 3)
page = (
await client.get(f"/api/v1/chats/{first['id']}/messages?limit=1", headers=actor(alice))
).json()
cursor = quote(page["next_cursor"], safe="")
response = await client.get(
f"/api/v1/chats/{second['id']}/messages?limit=1&cursor={cursor}", headers=actor(alice)
)
assert response.status_code == 400
assert response.json()["error"]["code"] == "invalid_request"
@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)
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", ""])
async def test_limit_out_of_range(client: AsyncClient, limit: str) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
response = await client.get(f"{path}?limit={limit}", headers=actor(alice))
assert response.status_code == 400, f"{path}?limit={limit} → {response.status_code}"
async def test_default_limit_is_50(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
await fill(client, chat, alice, 51)
page = (await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))).json()
assert len(page["items"]) == 50
assert page["next_cursor"] is not None
async def test_unknown_query_parameter_is_ignored(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
await fill(client, chat, alice, 2)
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
response = await client.get(f"{path}?limit=1&unknown=x", headers=actor(alice))
assert response.status_code == 200, response.text
assert len(response.json()["items"]) == 1
async def test_chat_list_pagination(client: AsyncClient) -> None:
alice = await register(client, "alice")
created = [(await make_chat(client, alice))["id"] for _ in range(5)]
collected: list[str] = []
cursor: str | None = None
while True:
query = "?limit=2" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
page = (await client.get(f"/api/v1/chats{query}", headers=actor(alice))).json()
collected.extend(item["id"] for item in page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
assert collected == created
+300
View File
@@ -0,0 +1,300 @@
import asyncio
import json
import re
from typing import Any
from uuid import uuid4
import pytest
from httpx import AsyncClient
from test_attachments import storage, trio, upload
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
from messenger.attachments.domain.jobs import Job, Outcome, RetryPolicy
from messenger.attachments.entrypoints.schemas import JobMessage
from messenger.shared.application.errors import Unavailable
from pictures import SAMPLE
from pipeline import pipeline_of
async def rows(sql: str, *args: Any) -> list[dict[str, Any]]:
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]:
alice, bob, _, chat = await trio(http)
response = await upload(http, alice, chat)
assert response.status_code == 202, response.text
return alice, bob, response.json()["id"]
async def state(attachment_id: str) -> dict[str, Any]:
(row,) = await rows(
"SELECT a.status, a.error_code, a.published_version, a.staging_key, a.original_key, "
"j.status AS job_status, j.attempt, j.claims FROM attachments a "
"JOIN jobs j ON j.attachment_id = a.id WHERE a.id = $1",
attachment_id,
)
return row
async def variants(attachment_id: str) -> list[dict[str, Any]]:
return await rows(
"SELECT pipeline_version, name, sha256, size_bytes, object_key FROM attachment_variants "
"WHERE attachment_id = $1 ORDER BY name",
attachment_id,
)
async def events(attachment_id: str) -> list[str]:
found = await rows(
"SELECT kind FROM job_events WHERE attachment_id = $1 ORDER BY id", attachment_id
)
return [row["kind"] for row in found]
async def job_of(attachment_id: str) -> Job:
(row,) = await rows(
"SELECT payload::text AS body FROM outbox o JOIN jobs j USING (job_id) "
"WHERE j.attachment_id = $1 ORDER BY o.id LIMIT 1",
attachment_id,
)
return JobMessage.model_validate_json(row["body"]).job()
async def test_job_is_processed_once_and_staging_is_cleaned(client: AsyncClient) -> None:
_, bob, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
outcomes = await pipeline.drain()
assert Outcome.DONE in outcomes
done = await state(attachment_id)
assert (done["status"], done["job_status"], done["published_version"]) == ("ready", "done", 1)
assert done["original_key"] == f"originals/{attachment_id}"
assert done["staging_key"] == f"staging/{attachment_id}"
pattern = rf"variants/{attachment_id}/1/(crop|optimized|thumbnail)-[0-9a-f]{{16}}\.(jpg|webp)"
found = [re.fullmatch(pattern, row["object_key"]) for row in await variants(attachment_id)]
assert [match.groups() for match in found if match] == [
("crop", "jpg"),
("optimized", "webp"),
("thumbnail", "jpg"),
]
assert await pipeline.clean() >= 1
assert (await state(attachment_id))["staging_key"] is None
objects = (await storage(client)).objects
assert f"staging/{attachment_id}" not in objects
assert objects[f"originals/{attachment_id}"][0] == SAMPLE
content = await client.get(f"/api/v1/attachments/{attachment_id}/content", headers=actor(bob))
assert content.content == SAMPLE
assert await events(attachment_id) == ["enqueued", "claimed", "done"]
async def test_message_is_a_contract_job(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
await pipeline.publish()
mine = [
json.loads(body)
for body in pipeline.publisher.bodies
if json.loads(body)["attachment_id"] == attachment_id
]
assert len(mine) == 1
assert set(mine[0]) == {
"schema_version",
"job_id",
"type",
"attachment_id",
"pipeline_version",
"attempt",
"created_at",
}
assert (mine[0]["pipeline_version"], mine[0]["attempt"]) == (1, 1)
assert await pipeline.publish() == []
async def test_redelivery_after_ready_changes_nothing(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
await pipeline.drain()
before, job = await variants(attachment_id), await job_of(attachment_id)
assert await pipeline.process(job) is Outcome.DUPLICATE
assert await variants(attachment_id) == before
assert (await state(attachment_id))["status"] == "ready"
assert (await events(attachment_id))[-1] == "duplicate_noop"
async def test_two_copies_in_flight_give_one_result(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
await pipeline.publish()
job = await job_of(attachment_id)
outcomes = await asyncio.gather(pipeline.process(job), pipeline.process(job))
assert sorted(outcomes) == sorted([Outcome.DONE, Outcome.DUPLICATE])
assert len(await variants(attachment_id)) == 3
assert (await state(attachment_id))["claims"] == 1
async def test_partial_variant_set_is_never_published(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
await pipeline.publish()
store = await storage(client)
async def refuse(key: str) -> None:
if "/optimized-" in key:
raise Unavailable("S3 недоступно")
store.after_put = refuse
try:
assert await pipeline.process(await job_of(attachment_id)) is Outcome.RESCHEDULED
finally:
store.after_put = None
assert (await state(attachment_id))["status"] == "queued"
assert await variants(attachment_id) == []
async def test_transient_error_reschedules_with_the_same_job(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
await pipeline.publish()
job = await job_of(attachment_id)
store = await storage(client)
store.failing = True
try:
assert await pipeline.process(job) is Outcome.RESCHEDULED
finally:
store.failing = False
queued = await state(attachment_id)
assert (queued["status"], queued["job_status"], queued["attempt"]) == ("queued", "queued", 2)
(retry,) = [j for j in await pipeline.publish() if str(j.attachment_id) == attachment_id]
assert (retry.id, retry.attempt) == (job.id, 2)
assert await pipeline.process(retry) is Outcome.DONE
assert (await state(attachment_id))["status"] == "ready"
async def test_attempts_are_bounded(client: AsyncClient) -> None:
alice, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
pipeline.faults = FailingFaults()
await pipeline.drain()
failed = await state(attachment_id)
assert (failed["status"], failed["error_code"], failed["job_status"]) == (
"failed",
"retry_exhausted",
"failed",
)
assert failed["attempt"] == pipeline.policy.max_attempts
assert (await events(attachment_id)).count("retry_scheduled") == 4
content = await client.get(f"/api/v1/attachments/{attachment_id}/content", headers=actor(alice))
assert content.status_code == 409
async def test_undecodable_image_fails_without_retries(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
(await storage(client)).objects[f"staging/{attachment_id}"] = (b"not a png", "image/png")
pipeline = await pipeline_of(client)
await pipeline.drain()
failed = await state(attachment_id)
assert (failed["status"], failed["error_code"], failed["attempt"]) == (
"failed",
"invalid_image",
1,
)
class DemandingRenderer:
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
raise ImageTooDemanding("рендер дольше допустимого времени")
@pytest.mark.parametrize("cause", ["limit", "missing"])
async def test_limits_and_lost_original_fail_without_retries(
client: AsyncClient, cause: str
) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
if cause == "limit":
pipeline.renderer = DemandingRenderer()
else:
del (await storage(client)).objects[f"staging/{attachment_id}"]
await pipeline.drain()
failed = await state(attachment_id)
assert (failed["status"], failed["error_code"], failed["attempt"]) == (
"failed",
"processing_failed",
1,
)
async def test_expired_lease_is_recovered_and_old_holder_is_fenced(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
await pipeline.publish()
job = await job_of(attachment_id)
uow = pipeline.uow()
async with uow.transaction():
claim = await uow.jobs.claim(job, uuid4(), pipeline.lease)
await uow.commit()
assert claim is not None
assert (await state(attachment_id))["status"] == "processing"
await rows(
"UPDATE jobs SET lease_until = now() - interval '1 second' WHERE attachment_id = $1",
attachment_id,
)
assert await pipeline.recover() >= 1
assert (await state(attachment_id))["status"] == "queued"
late = pipeline.uow()
async with late.transaction():
outcome = await late.jobs.complete(claim.lease, [], f"originals/{attachment_id}")
await late.commit()
assert outcome is Outcome.FENCED
assert await variants(attachment_id) == []
await pipeline.drain()
recovered = await state(attachment_id)
assert (recovered["status"], recovered["attempt"]) == ("ready", 2)
assert {"lease_expired", "fenced"} <= set(await events(attachment_id))
async def test_unpublished_rows_stay_when_the_broker_refuses(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
pipeline.publisher.failing = True
with pytest.raises(Unavailable):
await pipeline.publish()
pending = await rows(
"SELECT o.published_at FROM outbox o JOIN jobs j USING (job_id) WHERE j.attachment_id = $1",
attachment_id,
)
assert pending == [{"published_at": None}]
pipeline.publisher.failing = False
assert any(str(job.attachment_id) == attachment_id for job in await pipeline.publish())
async def test_backoff_delays_the_next_attempt(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client, policy=RetryPolicy(5, 30, 60))
pipeline.faults = FailingFaults()
await pipeline.drain()
queued = await state(attachment_id)
assert (queued["status"], queued["attempt"]) == ("queued", 2)
(row,) = await rows(
"SELECT extract(epoch FROM next_attempt_at - now()) AS wait FROM jobs "
"WHERE attachment_id = $1",
attachment_id,
)
assert 20 < row["wait"] <= 22.5
(event,) = await rows(
"SELECT (detail->>'delay_seconds')::float8 AS delay FROM job_events "
"WHERE attachment_id = $1 AND kind = 'retry_scheduled'",
attachment_id,
)
assert event["delay"] == 22.5
class FailingFaults:
async def reach(self, point: str) -> None:
if point == TRANSIENT_ERROR:
raise Unavailable(point)
+232
View File
@@ -0,0 +1,232 @@
import time
from dataclasses import replace
from datetime import UTC, datetime, timedelta
from uuid import UUID, uuid4
import pytest
from sqlalchemy import func, select
from sqlalchemy.exc import DBAPIError, IntegrityError
from conftest import (
actor,
keyed,
make_chat,
new_user,
register,
resolve,
running_app,
sql_connection,
)
from messenger.identity.domain.models import Session
from messenger.identity.infrastructure.postgres import (
PostgresIdentityUnitOfWork,
PostgresSessionDirectory,
UserRow,
)
from messenger.messaging.application.ports import AttachmentStates
from messenger.messaging.domain.models import Message
from messenger.messaging.domain.values import MessageText
from messenger.messaging.infrastructure.postgres import (
ChatRow,
IdempotencyKeyRow,
PostgresMessageLog,
)
from messenger.shared.application.errors import Unavailable
from messenger.shared.domain.events import DomainEvent
from messenger.shared.infrastructure.postgres import Database
async def test_exhausted_pool_answers_503_in_bounded_time() -> None:
async with running_app(db_pool_max_size=1, db_acquire_timeout_seconds=0.3) as http:
alice = await register(http, "alice")
database = await resolve(http, Database)
async with database.session() as session:
await session.execute(select(1))
started = time.perf_counter()
starved = await http.get("/api/v1/users/me", headers=actor(alice))
elapsed = time.perf_counter() - started
recovered = await http.get("/api/v1/users/me", headers=actor(alice))
assert starved.status_code == 503
assert starved.json()["error"]["code"] == "unavailable"
assert 0.25 < elapsed < 1
assert recovered.json() == alice
async def test_statement_timeout_is_set_on_connections() -> None:
async with running_app(db_command_timeout_seconds=1.5) as http:
database = await resolve(http, Database)
async with database.session() as session:
statement_timeout = await session.scalar(
select(func.current_setting("statement_timeout"))
)
lock_timeout = await session.scalar(select(func.current_setting("lock_timeout")))
idle_timeout = await session.scalar(
select(func.current_setting("idle_in_transaction_session_timeout"))
)
assert statement_timeout == "1500ms"
assert lock_timeout == "1500ms"
assert idle_timeout == "10s"
async def test_idle_session_does_not_acquire_connection() -> None:
async with running_app(db_pool_max_size=1) as http:
database = await resolve(http, Database)
async with database.session(), database.session() as active:
assert await active.scalar(select(1)) == 1
await database.ping()
async def test_closed_idle_connection_is_replaced_before_registration() -> None:
async with running_app(db_pool_max_size=1) as http:
database = await resolve(http, Database)
async with database.session() as session:
pid = await session.scalar(select(func.pg_backend_pid()))
async with sql_connection() as connection:
assert await connection.scalar(select(func.pg_terminate_backend(pid, 1000)))
body = new_user("reconnect")
response = await http.post("/api/v1/users", json=body)
assert response.status_code == 201
assert response.headers["X-Instance-Id"] and response.headers["X-Request-Id"]
async with database.session() as session:
assert (
await session.scalar(
select(func.count())
.select_from(UserRow)
.where(UserRow.username == body["username"])
)
== 1
)
async def test_readiness_timeout_releases_waiter() -> None:
async with running_app(db_pool_max_size=1, db_acquire_timeout_seconds=2) as http:
database = await resolve(http, Database)
async with database.session() as session:
await session.execute(select(1))
started = time.perf_counter()
response = await http.get("/health/ready")
elapsed = time.perf_counter() - started
assert response.status_code == 503
assert response.json()["error"]["code"] == "unavailable"
assert 0.3 < elapsed < 1
assert (await http.get("/health/ready")).status_code == 200
async def test_server_statement_timeout_returns_connection() -> None:
async with running_app(db_pool_max_size=1, db_command_timeout_seconds=1.5) as http:
database = await resolve(http, Database)
with pytest.raises(Unavailable) as failure:
async with database.session() as session:
await session.execute(select(func.set_config("statement_timeout", "100ms", True)))
await session.execute(select(func.pg_sleep(2)))
assert isinstance(failure.value.__cause__, DBAPIError)
assert getattr(failure.value.__cause__.orig, "sqlstate", None) == "57014"
await database.ping()
@pytest.mark.parametrize("commit", [False, True])
async def test_unit_of_work_persists_sessions_and_events_only_on_commit(commit: bool) -> None:
async with running_app(db_pool_max_size=1) as http:
alice = await register(http, "alice")
database = await resolve(http, Database)
uow = PostgresIdentityUnitOfWork(database)
now = datetime.now(UTC)
_, session = Session.issue(user_id=UUID(alice["id"]), issued_at=now, ttl=timedelta(hours=1))
event = DomainEvent()
async with uow.transaction():
await uow.sessions.add(session)
uow.record(event)
if commit:
await uow.commit()
stored = await PostgresSessionDirectory(database).find(session.token_hash, now)
assert stored == (session if commit else None)
assert uow.collect_new_events() == ([event] if commit else [])
assert uow.collect_new_events() == []
with pytest.raises(RuntimeError, match="вне транзакции"):
_ = uow.session
async def test_integrity_failure_rolls_back_and_keeps_pool_usable() -> None:
async with running_app(db_pool_max_size=1) as http:
database = await resolve(http, Database)
uow = PostgresIdentityUnitOfWork(database)
_, session = Session.issue(
user_id=uuid4(), issued_at=datetime.now(UTC), ttl=timedelta(hours=1)
)
with pytest.raises(IntegrityError) as failure:
async with uow.transaction():
uow.record(DomainEvent())
await uow.sessions.add(session)
await uow.commit()
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
assert uow.collect_new_events() == []
assert uow.seen == []
await database.ping()
@pytest.mark.parametrize(
("command_timeout", "request_timeout"), [(0.15, 5), (1.5, 0.3)], ids=["database", "request"]
)
async def test_blocked_message_times_out_without_taking_key(
command_timeout: float, request_timeout: float
) -> None:
async with running_app(
db_command_timeout_seconds=command_timeout, request_timeout_seconds=request_timeout
) as http:
alice = await register(http, "alice")
chat = await make_chat(http, alice)
database = await resolve(http, Database)
headers = keyed(alice)
path = f"/api/v1/chats/{chat['id']}/messages"
async with database.session() as session:
await session.execute(
select(ChatRow.id).where(ChatRow.id == UUID(chat["id"])).with_for_update()
)
started = time.perf_counter()
blocked = await http.post(path, json={"text": "повтор"}, headers=headers)
assert time.perf_counter() - started < 2
assert blocked.status_code == 503
assert blocked.json()["error"]["code"] == "unavailable"
recovered = await http.post(path, json={"text": "повтор"}, headers=headers)
replay = await http.post(path, json={"text": "повтор"}, headers=headers)
history = await http.get(path, headers=actor(alice))
assert recovered.status_code == replay.status_code == 201
assert replay.json() == recovered.json()
assert history.json()["items"] == [recovered.json()]
async def test_message_integrity_failure_rolls_back_receipt_and_timestamp() -> None:
async with running_app() as http:
alice = await register(http, "alice")
chat = await make_chat(http, alice)
database = await resolve(http, Database)
log = PostgresMessageLog(database, await resolve(http, AttachmentStates))
now = datetime.now(UTC)
since = now - timedelta(days=1)
message = Message(uuid4(), UUID(chat["id"]), UUID(alice["id"]), MessageText("текст"), now)
fingerprint = b"x" * 32
first = await log.post(message, "first", fingerprint, since)
assert first is not None
with pytest.raises(IntegrityError):
await log.post(message, "retry", fingerprint, since)
async with database.session() as session:
assert (
await session.scalar(
select(ChatRow.last_message_at).where(ChatRow.id == message.chat_id)
)
== first.message.created_at
)
assert (
await session.scalar(
select(func.count())
.select_from(IdempotencyKeyRow)
.where(
IdempotencyKeyRow.chat_id == message.chat_id,
IdempotencyKeyRow.key == "retry",
)
)
== 0
)
retry = await log.post(replace(message, id=uuid4()), "retry", fingerprint, since)
assert retry is not None
assert retry.message.created_at > first.message.created_at
+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
+307
View File
@@ -0,0 +1,307 @@
import asyncio
import json
import subprocess
import sys
from datetime import datetime, timedelta
from uuid import UUID, uuid4
import pytest
from httpx import AsyncClient
from test_attachments import storage
from test_pipeline import FailingFaults, accepted, events, job_of, rows, state, variants
from conftest import DATABASE
from fakes import NullLogger
from messenger.admin import serve
from messenger.attachments.application.pipeline import (
AFTER_CLAIM,
AFTER_COMMIT_BEFORE_ACK,
AFTER_COMMIT_BEFORE_PUBLISH,
AFTER_PUBLISH_BEFORE_CONFIRM,
AFTER_S3_WRITE,
STALL_AFTER_CLAIM,
TRANSIENT_ERROR,
)
from messenger.attachments.application.ports import Rendition
from messenger.attachments.domain.jobs import Outcome, ReplayResult
from messenger.attachments.infrastructure.faults import EnvironmentFaults
from messenger.shared.application.errors import Unavailable
from pipeline import InlinePipeline, InlineRenderer, pipeline_of
WORKER_POINTS = [
AFTER_CLAIM,
STALL_AFTER_CLAIM,
TRANSIENT_ERROR,
AFTER_S3_WRITE,
AFTER_COMMIT_BEFORE_ACK,
]
class Crash(BaseException):
pass
class RecordingFaults:
__slots__ = ("crash_at", "reached")
def __init__(self, crash_at: str = "") -> None:
self.crash_at = crash_at
self.reached: list[str] = []
async def reach(self, point: str) -> None:
self.reached.append(point)
if point == self.crash_at:
raise Crash(point)
class SlowRenderer:
__slots__ = ("seconds",)
def __init__(self, seconds: float) -> None:
self.seconds = seconds
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
await asyncio.sleep(self.seconds)
return await InlineRenderer().render(data, pipeline_version)
class ExpiringFaults:
__slots__ = ("attachment_id", "pipeline")
def __init__(self, pipeline: InlinePipeline, attachment_id: str) -> None:
self.pipeline = pipeline
self.attachment_id = attachment_id
async def reach(self, point: str) -> None:
if point == STALL_AFTER_CLAIM:
await rows(
"UPDATE jobs SET lease_until = now() - interval '1 second' "
"WHERE attachment_id = $1",
self.attachment_id,
)
await self.pipeline.recover()
async def outbox(attachment_id: str) -> list[bool]:
found = await rows(
"SELECT o.published_at IS NOT NULL AS published FROM outbox o JOIN jobs j USING (job_id) "
"WHERE j.attachment_id = $1 ORDER BY o.id",
attachment_id,
)
return [row["published"] for row in found]
def stored(objects: dict[str, tuple[bytes, str]], attachment_id: str) -> list[str]:
return sorted(key for key in objects if key.startswith(f"variants/{attachment_id}/"))
async def test_fault_points_are_reached_in_order(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
faults = RecordingFaults()
pipeline.faults = faults
published = await pipeline.publish()
assert faults.reached[:2] == [AFTER_COMMIT_BEFORE_PUBLISH, AFTER_PUBLISH_BEFORE_CONFIRM]
faults.reached.clear()
(job,) = [job for job in published if str(job.attachment_id) == attachment_id]
assert await pipeline.process(job) is Outcome.DONE
assert faults.reached == WORKER_POINTS
@pytest.mark.parametrize("point", [AFTER_COMMIT_BEFORE_PUBLISH, AFTER_PUBLISH_BEFORE_CONFIRM])
async def test_relay_crash_leaves_the_row_for_the_next_relay(
client: AsyncClient, point: str
) -> None:
pipeline = await pipeline_of(client)
await pipeline.drain()
_, _, attachment_id = await accepted(client)
pipeline.faults = RecordingFaults(point)
with pytest.raises(Crash):
await pipeline.publish()
assert await outbox(attachment_id) == [False]
sent = [body for body in pipeline.publisher.bodies if attachment_id.encode() in body]
assert len(sent) == (point == AFTER_PUBLISH_BEFORE_CONFIRM)
pipeline.faults = RecordingFaults()
outcomes = await pipeline.drain()
assert Outcome.DONE in outcomes
assert await outbox(attachment_id) == [True]
assert (await state(attachment_id))["status"] == "ready"
async def test_crash_after_s3_write_is_finished_by_the_next_attempt(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client, lease=timedelta(seconds=60))
await pipeline.publish()
job = await job_of(attachment_id)
pipeline.faults = RecordingFaults(AFTER_S3_WRITE)
with pytest.raises(Crash):
await pipeline.process(job)
objects = (await storage(client)).objects
written = stored(objects, attachment_id)
assert len(written) == 3
assert await variants(attachment_id) == []
assert (await state(attachment_id))["status"] == "processing"
await rows(
"UPDATE jobs SET lease_until = now() - interval '1 second' WHERE attachment_id = $1",
attachment_id,
)
pipeline.faults = RecordingFaults()
assert await pipeline.recover() >= 1
await pipeline.drain()
done = await state(attachment_id)
assert (done["status"], done["attempt"]) == ("ready", 2)
assert stored(objects, attachment_id) == written
assert sorted(row["object_key"] for row in await variants(attachment_id)) == written
async def test_crash_after_commit_is_a_duplicate_on_redelivery(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
await pipeline.publish()
job = await job_of(attachment_id)
pipeline.faults = RecordingFaults(AFTER_COMMIT_BEFORE_ACK)
with pytest.raises(Crash):
await pipeline.process(job)
before = await variants(attachment_id)
assert (await state(attachment_id))["status"] == "ready"
pipeline.faults = RecordingFaults()
assert await pipeline.process(job) is Outcome.DUPLICATE
assert await variants(attachment_id) == before
async def test_long_render_keeps_its_lease(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client, lease=timedelta(seconds=1))
pipeline.renderer = SlowRenderer(2.5)
await pipeline.publish()
job = await job_of(attachment_id)
async def sweep() -> None:
for _ in range(4):
await asyncio.sleep(0.6)
await pipeline.recover()
outcome, _ = await asyncio.gather(pipeline.process(job), sweep())
assert outcome is Outcome.DONE
done = await state(attachment_id)
assert (done["status"], done["attempt"], done["claims"]) == ("ready", 1, 1)
assert "lease_expired" not in await events(attachment_id)
async def test_lost_lease_stops_before_side_effects(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
await pipeline.publish()
job = await job_of(attachment_id)
pipeline.faults = ExpiringFaults(pipeline, attachment_id)
assert await pipeline.process(job) is Outcome.FENCED
objects = (await storage(client)).objects
assert stored(objects, attachment_id) == []
assert f"originals/{attachment_id}" not in objects
assert (await state(attachment_id))["status"] == "queued"
assert (await events(attachment_id))[-2:] == ["lease_expired", "fenced"]
pipeline.faults = RecordingFaults()
await pipeline.drain()
assert (await state(attachment_id))["status"] == "ready"
async def test_environment_faults_stall_once_and_fail_transiently() -> None:
stall = EnvironmentFaults(STALL_AFTER_CLAIM, NullLogger(), stall_seconds=0.3)
started = asyncio.get_running_loop().time()
await stall.reach(AFTER_CLAIM)
await stall.reach(STALL_AFTER_CLAIM)
await stall.reach(STALL_AFTER_CLAIM)
assert 0.3 <= asyncio.get_running_loop().time() - started < 0.6
with pytest.raises(Unavailable):
await EnvironmentFaults(TRANSIENT_ERROR, NullLogger()).reach(TRANSIENT_ERROR)
def test_environment_fault_crashes_the_process_with_137() -> None:
script = (
"import asyncio\n"
"from fakes import NullLogger\n"
"from messenger.attachments.infrastructure.faults import EnvironmentFaults\n"
"asyncio.run(EnvironmentFaults('after_commit_before_ack', NullLogger())"
".reach('after_commit_before_ack'))\n"
"print('survived')\n"
)
done = subprocess.run(
[sys.executable, "-c", script],
capture_output=True,
text=True,
check=False,
env={"PYTHONPATH": ":".join(sys.path)},
)
assert (done.returncode, done.stdout) == (137, "")
async def failed(client: AsyncClient) -> tuple[InlinePipeline, str]:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
pipeline.faults = FailingFaults()
await pipeline.drain()
pipeline.faults = RecordingFaults()
assert (await state(attachment_id))["error_code"] == "retry_exhausted"
return pipeline, attachment_id
async def test_replay_of_failed_reaches_ready_once(client: AsyncClient) -> None:
pipeline, attachment_id = await failed(client)
job = await job_of(attachment_id)
assert await pipeline.replay(UUID(attachment_id)) is ReplayResult.REPLAYED
queued = await state(attachment_id)
assert (queued["status"], queued["job_status"], queued["attempt"], queued["error_code"]) == (
"queued",
"queued",
1,
None,
)
assert await outbox(attachment_id) == [True] * 5 + [False]
await pipeline.drain()
done = await state(attachment_id)
assert (done["status"], done["attempt"]) == ("ready", 1)
assert (await job_of(attachment_id)).id == job.id
before = await variants(attachment_id)
assert await pipeline.replay(UUID(attachment_id)) is ReplayResult.NOOP
assert await outbox(attachment_id) == [True] * 6
assert await variants(attachment_id) == before
assert (await events(attachment_id))[-1] == "replay_noop"
assert "replayed" in await events(attachment_id)
assert await pipeline.replay(uuid4()) is ReplayResult.NOT_FOUND
async def test_failed_staging_is_kept_for_the_retention_period(client: AsyncClient) -> None:
pipeline, attachment_id = await failed(client)
_, _, waiting = await accepted(client)
objects = (await storage(client)).objects
await pipeline.clean(timedelta(days=1))
assert (await state(attachment_id))["staging_key"] == f"staging/{attachment_id}"
assert f"staging/{attachment_id}" in objects
await pipeline.clean(timedelta(0))
assert (await state(attachment_id))["staging_key"] is None
assert f"staging/{attachment_id}" not in objects
assert (await state(waiting))["staging_key"] == f"staging/{waiting}"
assert f"staging/{waiting}" in objects
assert await pipeline.replay(UUID(attachment_id)) is ReplayResult.EXPIRED
assert (await state(attachment_id))["status"] == "failed"
async def test_operator_cli_lists_failed_jobs_and_replays(
client: AsyncClient, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
_, attachment_id = await failed(client)
monkeypatch.setenv("DATABASE_URL", DATABASE["url"])
monkeypatch.setenv("LOG_LEVEL", "WARNING")
assert await serve(["failed", "--limit", "500"]) == 0
registry = json.loads(capsys.readouterr().out.splitlines()[-1])["failed"]
(mine,) = [row for row in registry if row["attachment_id"] == attachment_id]
assert datetime.fromisoformat(mine["failed_at"]).utcoffset() == timedelta(0)
assert (mine["error_code"], mine["attempt"], mine["last_error"]) == (
"retry_exhausted",
5,
"Unavailable",
)
assert await serve(["replay", "--attachment-id", attachment_id, "--operator", "alice"]) == 0
report = json.loads(capsys.readouterr().out.splitlines()[-1])
assert report == {"result": "replayed", "attachment_id": attachment_id, "operator": "alice"}
assert await serve(["replay", "--attachment-id", str(uuid4())]) == 1
+203
View File
@@ -0,0 +1,203 @@
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,
actor,
basic,
bearer,
login,
make_chat,
new_user,
register,
running_app,
scalar,
)
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
BASIC = 'Basic realm="messenger", charset="UTF-8"'
BEARER = 'Bearer realm="messenger"'
def challenged(response, challenge: str) -> None:
assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == challenge
assert response.json()["error"]["code"] == "unauthorized"
assert response.json()["error"]["request_id"] == response.headers["X-Request-Id"]
async def test_login_returns_session_for_registered_user(client: AsyncClient) -> None:
body = new_user("alice")
user = (await client.post("/api/v1/users", json=body)).json()
session = await login(client, body["username"])
assert set(session) == {"token", "token_type", "expires_at", "user"}
assert session["token_type"] == "Bearer"
assert session["user"] == user
assert len(session["token"]) >= 43
assert body["username"] not in session["token"] and user["id"] not in session["token"]
assert session["expires_at"].endswith("Z")
expires = datetime.fromisoformat(session["expires_at"])
created = datetime.fromisoformat(user["created_at"])
assert timedelta(seconds=3500) < expires - created < timedelta(seconds=3700)
async def test_registration_response_hides_password(client: AsyncClient) -> None:
body = new_user("alice")
response = await client.post("/api/v1/users", json=body)
assert set(response.json()) == {"id", "username", "display_name", "created_at"}
assert PASSWORD not in response.text
async def test_password_is_stored_as_argon2id(client: AsyncClient) -> None:
alice = await register(client, "alice")
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
async def test_session_stores_only_token_digest(client: AsyncClient) -> None:
alice = await register(client, "alice")
token = actor(alice)["Authorization"].split()[1]
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:
alice = await register(client, "alice")
wrong = await client.post("/api/v1/auth/sessions", headers=basic(alice["username"], "x" * 20))
unknown = await client.post("/api/v1/auth/sessions", headers=basic("u_ghost_000", PASSWORD))
challenged(wrong, BASIC)
challenged(unknown, BASIC)
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
@pytest.mark.parametrize(
"headers",
[{}, {"Authorization": "Basic !!!"}, {"Authorization": "Bearer abc"}, {"X-User-Id": "x"}],
)
async def test_login_without_valid_basic(client: AsyncClient, headers: dict) -> None:
challenged(await client.post("/api/v1/auth/sessions", headers=headers), BASIC)
@pytest.mark.parametrize(
"raw", [b"Basic \x80", b"Basic \xff", b"Basic \xc3\xa9", b"Basic YWxpY2U6c2VjcmV0\xff"]
)
async def test_non_ascii_basic_matches_wrong_password(client: AsyncClient, raw: bytes) -> None:
alice = await register(client, "non_ascii_basic")
count = (
select(func.count()).select_from(SessionRow).where(SessionRow.user_id == UUID(alice["id"]))
)
before = await scalar(count)
wrong = await client.post(
"/api/v1/auth/sessions",
headers={**basic(alice["username"], "wrong-password"), "X-Request-Id": "non-ascii-basic"},
)
invalid = await client.post(
"/api/v1/auth/sessions",
headers={b"Authorization": raw, b"X-Request-Id": b"non-ascii-basic"},
)
for response in [wrong, invalid]:
challenged(response, BASIC)
assert response.headers["X-Instance-Id"]
assert response.headers["content-type"].startswith("application/json")
assert set(response.json()) == {"error"}
assert set(response.json()["error"]) == {"code", "message", "request_id"}
assert response.json()["error"]["message"]
assert wrong.json() == invalid.json()
assert await scalar(count) == before
async def test_password_with_colon_logs_in(client: AsyncClient) -> None:
body = new_user("colon", password="пароль:с:двоеточием")
assert (await client.post("/api/v1/users", json=body)).status_code == 201
assert (await login(client, body["username"], body["password"]))["token"]
async def test_login_with_body_is_rejected(client: AsyncClient) -> None:
body = new_user("body")
await client.post("/api/v1/users", json=body)
response = await client.post(
"/api/v1/auth/sessions", headers=basic(body["username"], PASSWORD), json={"x": 1}
)
assert response.status_code == 400
assert response.json()["error"]["code"] == "invalid_request"
async def test_basic_on_business_endpoint_gets_bearer_challenge(client: AsyncClient) -> None:
body = new_user("alice")
await client.post("/api/v1/users", json=body)
challenged(
await client.get("/api/v1/users/me", headers=basic(body["username"], PASSWORD)), BEARER
)
async def test_user_id_header_does_not_override_owner(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
response = await client.get(
"/api/v1/users/me", headers={**actor(alice), "X-User-Id": eve["id"]}
)
assert response.json() == alice
async def test_authentication_precedes_validation(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/chats/not-a-uuid/messages",
content=b"{broken",
headers={"Content-Type": "application/json"},
)
challenged(response, BEARER)
async def test_logout_revokes_only_current_session(client: AsyncClient) -> None:
body = new_user("alice")
await client.post("/api/v1/users", json=body)
first = (await login(client, body["username"]))["token"]
second = (await login(client, body["username"]))["token"]
logout = await client.delete("/api/v1/auth/sessions/current", headers=bearer(first))
assert logout.status_code == 204
assert logout.content == b""
assert logout.headers["X-Request-Id"]
challenged(await client.get("/api/v1/users/me", headers=bearer(first)), BEARER)
challenged(await client.delete("/api/v1/auth/sessions/current", headers=bearer(first)), BEARER)
assert (await client.get("/api/v1/users/me", headers=bearer(second))).status_code == 200
async def test_short_ttl_session_expires() -> None:
async with running_app(session_ttl_seconds=1) as client:
alice = await register(client, "alice")
assert (await client.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
await asyncio.sleep(1.2)
challenged(await client.get("/api/v1/users/me", headers=actor(alice)), BEARER)
async def test_expired_sessions_are_purged_on_next_login() -> None:
async with running_app(session_ttl_seconds=1) as client:
body = new_user("purge")
user = (await client.post("/api/v1/users", json=body)).json()
await login(client, body["username"])
await asyncio.sleep(1.2)
await login(client, body["username"])
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:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
for method, path in [
("GET", "/api/v1/chats"),
("POST", "/api/v1/chats"),
("GET", f"/api/v1/chats/{chat['id']}"),
("GET", f"/api/v1/chats/{chat['id']}/messages"),
("POST", f"/api/v1/chats/{chat['id']}/messages"),
("DELETE", "/api/v1/auth/sessions/current"),
]:
challenged(await client.request(method, path, headers={"X-User-Id": alice["id"]}), BEARER)
+148
View File
@@ -0,0 +1,148 @@
import asyncio
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
from httpx import AsyncClient
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 = "текст-который-не-должен-утечь-при-таймауте"
@asynccontextmanager
async def slow_post(delay: float) -> AsyncIterator[None]:
original: Callable = handlers.PostMessageHandler.__call__
async def stalled(self, command):
await asyncio.sleep(delay)
return await original(self, command)
handlers.PostMessageHandler.__call__ = stalled
try:
yield
finally:
handlers.PostMessageHandler.__call__ = original
async def post(client: AsyncClient, chat: dict, sender: dict, text: str):
return await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=keyed(sender)
)
async def prepared(client: AsyncClient) -> tuple[dict, dict]:
alice = await register(client, "alice")
return alice, await make_chat(client, alice)
async def test_timeout_returns_unavailable_error_body() -> None:
async with running_app(request_timeout_seconds=0.15) as client:
alice, chat = await prepared(client)
async with slow_post(1.0):
response = await post(client, chat, alice, "медленная запись")
assert response.status_code == 503
body = response.json()
assert body["error"]["code"] == "unavailable"
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
async def test_timeout_does_not_break_following_requests() -> None:
async with running_app(request_timeout_seconds=0.15) as client:
alice, chat = await prepared(client)
async with slow_post(1.0):
assert (await post(client, chat, alice, "зависшая запись")).status_code == 503
assert (await post(client, chat, alice, "нормальная запись")).status_code == 201
assert (await client.get("/health/ready")).status_code == 200
async def test_timeout_is_logged_without_message_text(capsys) -> None:
async with running_app(request_timeout_seconds=0.15, log_level="INFO") as client:
alice, chat = await prepared(client)
async with slow_post(1.0):
assert (await post(client, chat, alice, MARKER)).status_code == 503
captured = capsys.readouterr()
assert "request.timeout" in captured.out
assert MARKER not in captured.out
assert MARKER not in captured.err
async def test_normal_request_is_not_affected_by_timeout() -> None:
async with running_app(request_timeout_seconds=5.0) as client:
alice, chat = await prepared(client)
assert (await post(client, chat, alice, "обычная запись")).status_code == 201
async def test_slow_event_handler_does_not_trigger_timeout() -> None:
async with running_app(request_timeout_seconds=0.3) as client:
alice, chat = await prepared(client)
blocked = asyncio.Event()
bus = await resolve(client, EventBus)
async def stall(_event: MessagePosted) -> None:
await blocked.wait()
bus.subscribe(MessagePosted, stall)
response = await post(client, chat, alice, "ответ не ждёт обработчик")
blocked.set()
assert response.status_code == 201
async def test_healthcheck_stays_fast(client: AsyncClient) -> None:
loop = asyncio.get_running_loop()
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
+65
View File
@@ -0,0 +1,65 @@
import asyncio
from datetime import timedelta
from uuid import UUID
from httpx import AsyncClient
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.trace import SpanKind
from sqlalchemy import select
from test_pipeline import accepted, job_of
from conftest import sql_connection
from messenger.attachments.infrastructure.postgres import JobRow, OutboxRow, PostgresJobRepository
from messenger.shared.infrastructure.trace_context import capture_context, restored_context
from pipeline import pipeline_of
async def test_context_survives_outbox_delivery_and_lease_recovery(client: AsyncClient) -> None:
provider = TracerProvider(shutdown_on_exit=False)
tracer = provider.get_tracer("test")
with tracer.start_as_current_span("upload", kind=SpanKind.SERVER):
origin = capture_context()
_, _, attachment_id = await accepted(client)
job = await job_of(attachment_id)
async with sql_connection() as connection:
assert (
await connection.scalar(select(JobRow.trace_context).where(JobRow.job_id == job.id))
== origin
)
assert (
await connection.scalar(
select(OutboxRow.trace_context).where(OutboxRow.job_id == job.id)
)
== origin
)
pipeline = await pipeline_of(client)
await pipeline.publish()
assert pipeline.publisher.contexts == [origin]
uow = pipeline.uow()
async with uow.transaction():
claim = await uow.jobs.claim(job, UUID(int=1), timedelta(seconds=-1))
assert claim is not None
await uow.commit()
await pipeline.recover()
await asyncio.sleep(0.02)
await pipeline.publish()
assert len(pipeline.publisher.contexts) == 2
assert pipeline.publisher.contexts[-1] == origin
with restored_context(origin), tracer.start_as_current_span("retry", kind=SpanKind.CONSUMER):
retry = capture_context()
async with uow.transaction():
await PostgresJobRepository(uow.session)._enqueue(job)
await uow.commit()
async with sql_connection() as connection:
assert (
await connection.scalar(
select(OutboxRow.trace_context)
.where(OutboxRow.job_id == job.id)
.order_by(OutboxRow.id.desc())
.limit(1)
)
== retry
)
assert retry["traceparent"].split("-")[1] == origin["traceparent"].split("-")[1]
assert retry != origin
provider.shutdown()
@@ -0,0 +1,255 @@
import asyncio
from collections.abc import AsyncIterator
from typing import Any
from uuid import uuid4
from httpx import AsyncClient
from starlette.types import Message
from test_attachments import storage, trio, upload
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
from pictures import SAMPLE
from pipeline import settle
AGED = "UPDATE attachments SET created_at = created_at - interval '1 hour' WHERE id = $1"
async def execute(sql: str, *args: Any) -> None:
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) -> 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
name = f"intent-{uuid4().hex}.png"
try:
assert (await upload(http, user, chat, filename=name)).status_code == 503
finally:
store.failing = False
found = await scalar(
"SELECT id::text FROM attachments WHERE filename = $1 AND status = 'pending'", name
)
assert found is not None
store.objects[f"staging/{found}"] = (SAMPLE, "image/png")
return found
async def exists(attachment_id: str) -> bool:
return await scalar("SELECT count(*) FROM attachments WHERE id = $1", attachment_id) == 1
async def test_commit_failure_after_put_is_compensated(client: AsyncClient) -> None:
alice, _, _, chat = await trio(client)
store = await storage(client)
name = f"fail-{uuid4().hex}.png"
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 $$"""
)
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")
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
assert (
await scalar(
"SELECT count(*) FROM jobs j JOIN attachments a ON a.id = j.attachment_id "
"WHERE a.filename = $1",
name,
)
== 0
)
assert set(store.objects) == before
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:
alice, _, _, chat = await trio(client)
store = await storage(client)
async def swept_meanwhile(key: str) -> None:
await execute("DELETE FROM attachments WHERE staging_key = $1", key)
store.after_put = swept_meanwhile
before = set(store.objects)
try:
response = await upload(client, alice, chat, filename="late.png")
finally:
store.after_put = None
assert response.status_code == 503
assert set(store.objects) == before
async def test_failed_put_leaves_an_intent_until_grace_ends(client: AsyncClient) -> None:
alice, _, _, chat = await trio(client)
pending = await intent(client, alice, chat)
await sweeper(client).sweep()
assert await exists(pending)
await execute(AGED, pending)
assert await sweeper(client).sweep() >= 1
assert not await exists(pending)
assert f"staging/{pending}" not in (await storage(client)).objects
async def test_sweep_keeps_fresh_intents_and_ready_attachments(client: AsyncClient) -> None:
alice, bob, _, chat = await trio(client)
ready = (await upload(client, alice, chat)).json()
await settle(client)
sent = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "", "attachment_ids": [ready["id"]]},
headers=keyed(alice),
)
assert sent.status_code == 201
old, fresh = await intent(client, alice, chat), await intent(client, alice, chat)
await execute(AGED, old)
await execute(AGED, ready["id"])
assert await sweeper(client).sweep() == 1
objects = (await storage(client)).objects
assert not await exists(old)
assert f"staging/{old}" not in objects
assert await exists(fresh)
assert f"staging/{fresh}" in objects
download = await client.get(f"/api/v1/attachments/{ready['id']}/content", headers=actor(bob))
assert download.status_code == 200
assert download.content == SAMPLE
assert await sweeper(client).sweep() == 0
async def test_parallel_sweeps_share_the_work(client: AsyncClient) -> None:
alice, _, _, chat = await trio(client)
pending = [await intent(client, alice, chat) for _ in range(5)]
for attachment_id in pending:
await execute(AGED, attachment_id)
seen = await discarded(client)
first, second = await asyncio.gather(sweeper(client).sweep(), sweeper(client).sweep())
assert first + second == 5
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)
async def test_background_sweeper_removes_abandoned_intents() -> None:
async with running_app(upload_sweep_interval_seconds=0.05) as http:
alice, _, _, chat = await trio(http)
pending = await intent(http, alice, chat)
await execute(AGED, pending)
for _ in range(100):
if not await exists(pending):
break
await asyncio.sleep(0.05)
assert not await exists(pending)
async def test_upload_waits_for_a_free_slot() -> None:
async with running_app(upload_concurrency=1) as http:
alice, _, _, chat = await trio(http)
gate, holding, read = asyncio.Event(), asyncio.Event(), []
async def held() -> AsyncIterator[bytes]:
read.append("first")
holding.set()
yield SAMPLE[:1000]
await gate.wait()
yield SAMPLE[1000:]
async def queued() -> AsyncIterator[bytes]:
read.append("second")
yield SAMPLE
first = asyncio.create_task(upload(http, alice, chat, held()))
await holding.wait()
second = asyncio.create_task(upload(http, alice, chat, queued()))
await asyncio.sleep(0.3)
assert read == ["first"]
gate.set()
assert [(await first).status_code, (await second).status_code] == [202, 202]
assert read == ["first", "second"]
async def test_aborted_upload_is_a_client_error(client: AsyncClient) -> None:
alice, _, _, chat = await trio(client)
name = f"abort-{uuid4().hex}.png"
headers = [(k.lower().encode(), v.encode()) for k, v in actor(alice).items()]
scope = {
"type": "http",
"asgi": {"version": "3.0"},
"http_version": "1.1",
"method": "POST",
"scheme": "http",
"path": f"/api/v1/chats/{chat['id']}/attachments",
"raw_path": f"/api/v1/chats/{chat['id']}/attachments".encode(),
"query_string": f"filename={name}".encode(),
"root_path": "",
"headers": [
*headers,
(b"content-type", b"image/png"),
(b"content-length", b"1000000"),
],
"client": ("127.0.0.1", 50000),
"server": ("testserver", 80),
}
messages = iter(
[
{"type": "http.request", "body": SAMPLE[:1000], "more_body": True},
{"type": "http.disconnect"},
]
)
sent: list[Message] = []
async def receive() -> dict[str, Any]:
return next(messages, {"type": "http.disconnect"})
async def send(message: Message) -> None:
sent.append(message)
await APPS[id(client)](scope, receive, send)
assert sent[0]["status"] == 400
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
async def test_stalled_upload_times_out_and_frees_the_slot() -> None:
async with running_app(upload_concurrency=1, request_timeout_seconds=0.5) as http:
alice, _, _, chat = await trio(http)
name = f"stalled-{uuid4().hex}.png"
async def stalled() -> AsyncIterator[bytes]:
yield SAMPLE[:1000]
await asyncio.Event().wait()
response = await upload(http, alice, chat, stalled(), filename=name)
assert response.status_code == 503
assert response.json()["error"]["code"] == "unavailable"
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
assert (await upload(http, alice, chat)).status_code == 202
@@ -0,0 +1,200 @@
import asyncio
import json
from uuid import UUID, uuid4
import pytest
from httpx import AsyncClient
from test_attachments import storage
from test_pipeline import accepted, job_of, rows
from conftest import DATABASE, actor
from messenger.admin import serve
from messenger.attachments.application.commands import ReprocessAttachment
from messenger.attachments.application.pipeline import (
AFTER_CLAIM,
AFTER_S3_WRITE,
ReprocessAttachmentHandler,
)
from messenger.attachments.application.ports import Rendition
from messenger.attachments.domain.errors import ImageTooDemanding
from messenger.attachments.domain.jobs import Outcome, ReprocessResult
from messenger.shared.infrastructure.clock import MonotonicUtcClock
from messenger.shared.infrastructure.ids import Uuid7Generator
from pipeline import InlinePipeline, InlineRenderer, pipeline_of
async def reprocess(pipeline: InlinePipeline, ident: str, version: int = 2) -> ReprocessResult:
handler = ReprocessAttachmentHandler(pipeline.uow(), Uuid7Generator(), MonotonicUtcClock())
return await handler(ReprocessAttachment(UUID(ident), version, "test"))
async def attachment(ident: str) -> dict:
(row,) = await rows(
"SELECT status, published_version, error_code FROM attachments WHERE id = $1", ident
)
return row
async def versions(pipeline: InlinePipeline, ident: str) -> dict:
return {
job.pipeline_version: job
for job in await pipeline.publish()
if str(job.attachment_id) == ident
}
async def test_concurrent_reprocess_creates_one_job_and_outbox(client: AsyncClient) -> None:
_, _, ident = await accepted(client)
pipeline = await pipeline_of(client)
results = await asyncio.gather(*(reprocess(pipeline, ident) for _ in range(6)))
assert results.count(ReprocessResult.QUEUED) == 1
assert results.count(ReprocessResult.NOOP) == 5
jobs = await rows(
"SELECT pipeline_version, count(*) FROM jobs WHERE attachment_id = $1 GROUP BY 1", ident
)
assert {r["pipeline_version"]: r["count"] for r in jobs} == {1: 1, 2: 1}
assert len(await versions(pipeline, ident)) == 2
@pytest.mark.parametrize("order", [(1, 2), (2, 1)])
async def test_version_order_never_reverts_published_bytes(
client: AsyncClient, order: tuple[int, int]
) -> None:
_, bob, ident = await accepted(client)
pipeline = await pipeline_of(client)
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
jobs = await versions(pipeline, ident)
for version in order:
outcome = await pipeline.process(jobs[version])
assert outcome is (Outcome.SUPERSEDED if order == (2, 1) and version == 1 else Outcome.DONE)
assert (await attachment(ident))["status"] == "ready"
await pipeline.clean()
assert (await attachment(ident))["published_version"] == 2
public = (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json()
stored = await rows(
"SELECT pipeline_version, name, sha256 FROM attachment_variants WHERE attachment_id = $1",
ident,
)
current = {r["name"]: r["sha256"] for r in stored if r["pipeline_version"] == 2}
older = {r["name"]: r["sha256"] for r in stored if r["pipeline_version"] == 1}
assert current != older
assert {r["name"]: r["sha256"] for r in public["variants"]} == current
assert await pipeline.process(jobs[1]) is Outcome.DUPLICATE
assert await reprocess(pipeline, ident) is ReprocessResult.NOOP
assert (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json() == public
class PausedEffect:
def __init__(self, point: str) -> None:
self.point = point
self.reached = asyncio.Event()
self.resume = asyncio.Event()
async def reach(self, point: str) -> None:
if point == self.point:
self.reached.set()
await self.resume.wait()
@pytest.mark.parametrize("point", [AFTER_CLAIM, AFTER_S3_WRITE])
async def test_old_holder_finishes_after_new_publication(client: AsyncClient, point: str) -> None:
_, bob, ident = await accepted(client)
old, new = await pipeline_of(client), await pipeline_of(client)
old.faults = pause = PausedEffect(point)
job = await job_of(ident)
running = asyncio.create_task(old.process(job))
try:
await asyncio.wait_for(pause.reached.wait(), 5)
assert await reprocess(new, ident) is ReprocessResult.QUEUED
jobs = await versions(new, ident)
assert await new.process(jobs[2]) is Outcome.DONE
public = (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json()
assert await new.clean() == 0
pause.resume.set()
assert await asyncio.wait_for(running, 5) is Outcome.SUPERSEDED
assert await new.clean() == 1
assert (await attachment(ident))["published_version"] == 2
assert (
await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))
).json() == public
finally:
pause.resume.set()
await running
class RejectingRenderer:
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
raise ImageTooDemanding("test limit")
async def test_failed_old_version_keeps_other_version_active(client: AsyncClient) -> None:
_, _, ident = await accepted(client)
pipeline = await pipeline_of(client)
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
jobs = await versions(pipeline, ident)
pipeline.renderer = RejectingRenderer()
assert await pipeline.process(jobs[1]) is Outcome.FAILED
assert (await attachment(ident))["status"] in ("queued", "processing")
pipeline.renderer = InlineRenderer()
assert await pipeline.process(jobs[2]) is Outcome.DONE
assert (await attachment(ident))["published_version"] == 2
async def test_concurrent_failures_leave_no_stuck_attachment(client: AsyncClient) -> None:
_, _, ident = await accepted(client)
pipeline = await pipeline_of(client)
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
jobs = await versions(pipeline, ident)
pipeline.renderer = RejectingRenderer()
assert await asyncio.gather(*(pipeline.process(job) for job in jobs.values())) == [
Outcome.FAILED,
Outcome.FAILED,
]
assert (await attachment(ident))["status"] == "failed"
assert await reprocess(pipeline, ident) is ReprocessResult.CONFLICT
assert await pipeline.publish() == []
async def test_failed_new_version_keeps_ready_original(client: AsyncClient) -> None:
_, bob, ident = await accepted(client)
pipeline = await pipeline_of(client)
await pipeline.drain()
public = (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json()
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
assert (await attachment(ident))["status"] == "ready"
jobs = await versions(pipeline, ident)
pipeline.renderer = RejectingRenderer()
assert await pipeline.process(jobs[2]) is Outcome.FAILED
assert (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json() == public
async def test_reprocess_rejects_unknown_id_and_version(client: AsyncClient) -> None:
pipeline = await pipeline_of(client)
assert await reprocess(pipeline, str(uuid4())) is ReprocessResult.NOT_FOUND
with pytest.raises(ValueError, match="версия"):
await reprocess(pipeline, str(uuid4()), 3)
async def test_operator_cli_schedules_version_once(
client: AsyncClient, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
_, _, ident = await accepted(client)
monkeypatch.setenv("DATABASE_URL", DATABASE["url"])
monkeypatch.setenv("LOG_LEVEL", "WARNING")
args = ["reprocess", "--attachment-id", ident, "--pipeline-version", "2"]
for expected in ("queued", "noop"):
assert await serve(args) == 0
report = json.loads(capsys.readouterr().out.splitlines()[-1])
assert report["result"] == expected
assert report["pipeline_version"] == 2
async def test_ready_reprocess_survives_cleanup_before_metadata_commit(client: AsyncClient) -> None:
_, _, ident = await accepted(client)
pipeline = await pipeline_of(client)
await pipeline.drain()
await (await storage(client)).delete(f"staging/{ident}")
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
jobs = await versions(pipeline, ident)
assert await pipeline.process(jobs[2]) is Outcome.DONE
assert (await attachment(ident))["published_version"] == 2
+69
View File
@@ -0,0 +1,69 @@
import json
import re
from datetime import UTC, datetime
from typing import Any
import pytest
from httpx import Response
from conftest import bearer, login, new_user, running_app
from messenger.shared.infrastructure.clock import MonotonicUtcClock
RFC3339_UTC = re.compile(r"\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z\Z")
MOMENTS = [
datetime(2026, 10, 12, 8, 49, 2, tzinfo=UTC),
datetime(2026, 10, 12, 8, 49, 2, 120, tzinfo=UTC),
]
def assert_wire(response: Response, expected: dict[str, Any]) -> None:
assert (
response.content == json.dumps(expected, ensure_ascii=False, separators=(",", ":")).encode()
)
@pytest.mark.parametrize("moment", MOMENTS, ids=["whole-second", "microseconds"])
async def test_created_at_is_rfc3339_utc(monkeypatch: pytest.MonkeyPatch, moment: datetime) -> None:
monkeypatch.setattr(MonotonicUtcClock, "now", lambda _self: moment)
stamp = moment.isoformat().replace("+00:00", "Z")
assert RFC3339_UTC.match(stamp)
async with running_app() as http:
body = new_user("wire")
response = await http.post("/api/v1/users", json=body)
user_id = response.json()["id"]
user = {
"id": user_id,
"username": body["username"],
"display_name": body["display_name"],
"created_at": stamp,
}
assert_wire(response, user)
session = await login(http, body["username"])
headers = bearer(session["token"])
assert session["user"] == user
assert_wire(await http.get("/api/v1/users/me", headers=headers), user)
response = await http.post(
"/api/v1/chats", json={"title": "Чат", "member_ids": [user_id]}, headers=headers
)
chat_id = response.json()["id"]
chat = {"id": chat_id, "title": "Чат", "member_ids": [user_id], "created_at": stamp}
assert_wire(response, chat)
assert_wire(await http.get(f"/api/v1/chats/{chat_id}", headers=headers), chat)
listed = await http.get("/api/v1/chats", headers=headers)
assert_wire(listed, {"items": [chat], "next_cursor": None})
path = f"/api/v1/chats/{chat_id}/messages"
sent = {**headers, "Idempotency-Key": "wire-1"}
response = await http.post(path, json={"text": "привет"}, headers=sent)
message = {
"id": response.json()["id"],
"chat_id": chat_id,
"sender_id": user_id,
"text": "привет",
"created_at": stamp,
"attachment_ids": [],
}
assert_wire(response, message)
history = await http.get(path, headers=headers)
assert_wire(history, {"items": [message], "next_cursor": None})