Link messages to attachments of the same chat
A message now carries attachment_ids in the request, in every response, in the idempotent replay and in history, in the order they were sent. The chat aggregate checks membership first, then refuses whitespace text, more than ten or repeated attachments, and an empty text without attachments, so an outsider still gets 404 before any 400. The send statement inserts the links next to the message and the idempotency key, and the foreign key from message_attachments to attachments of the same chat turns an unknown or foreign attachment into 404 and rolls the whole send back, without the messaging zone reading the attachments table. Replay and history read the list with a subquery on the primary key. The request fingerprint covers the list, so a missing attachment_ids and [] are the same body while a different order is a conflict. The zone dependency test now covers three zones, and the SQL ownership test checks that every zone touches only its own tables. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
00826a40d3
commit
f9760fc098
@@ -5,6 +5,8 @@ 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]:
|
||||
@@ -45,9 +47,23 @@ def test_messaging_touches_identity_only_through_events() -> None:
|
||||
assert not offenders
|
||||
|
||||
|
||||
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 ("identity", "messaging", "shared"):
|
||||
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]
|
||||
@@ -58,7 +74,7 @@ def test_domains_do_not_import_infrastructure() -> None:
|
||||
|
||||
def test_core_layers_do_not_import_pydantic() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for zone in ("identity", "messaging", "shared"):
|
||||
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"]
|
||||
@@ -73,7 +89,7 @@ def test_shared_knows_nothing_about_zones() -> None:
|
||||
borrowed = [
|
||||
module
|
||||
for module in imports_of(path)
|
||||
if module.startswith(IDENTITY) or module.startswith(MESSAGING)
|
||||
if module.startswith((IDENTITY, MESSAGING, ATTACHMENTS))
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
@@ -126,31 +142,28 @@ def test_shared_entrypoints_hold_only_transport() -> None:
|
||||
|
||||
|
||||
def test_every_zone_owns_its_errors_events_and_commands() -> None:
|
||||
for zone in ("identity", "messaging"):
|
||||
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 ("identity", "messaging"):
|
||||
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}"
|
||||
|
||||
|
||||
def test_only_main_knows_both_zones() -> None:
|
||||
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 {
|
||||
"identity",
|
||||
"messaging",
|
||||
}:
|
||||
if path.name in {"__init__.py", "main.py"} or relative.parts[0] in ZONES:
|
||||
continue
|
||||
borrowed = [
|
||||
module
|
||||
for module in imports_of(path)
|
||||
if module.startswith(IDENTITY) or module.startswith(MESSAGING)
|
||||
if module.startswith((IDENTITY, MESSAGING, ATTACHMENTS))
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(relative)] = borrowed
|
||||
@@ -172,6 +185,8 @@ ZONE_WORDS = (
|
||||
"sender",
|
||||
"message_id",
|
||||
"message_text",
|
||||
"attachment",
|
||||
"filename",
|
||||
)
|
||||
|
||||
|
||||
@@ -193,7 +208,10 @@ def test_shared_declares_no_concrete_commands_or_events() -> None:
|
||||
name
|
||||
for name in declared
|
||||
if name not in {"Command", "DomainEvent", "DomainError"}
|
||||
and (name.endswith("Event") or name in {"RegisterUser", "CreateChat", "PostMessage"})
|
||||
and (
|
||||
name.endswith("Event")
|
||||
or name in {"RegisterUser", "CreateChat", "PostMessage", "UploadAttachment"}
|
||||
)
|
||||
]
|
||||
assert not concrete, f"{path.name}: {concrete}"
|
||||
|
||||
@@ -206,7 +224,7 @@ def test_shared_has_no_test_doubles() -> None:
|
||||
|
||||
|
||||
def test_zone_errors_do_not_leak_transport_codes() -> None:
|
||||
for zone in ("identity", "messaging", "shared"):
|
||||
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
|
||||
@@ -214,7 +232,8 @@ def test_zone_errors_do_not_leak_transport_codes() -> None:
|
||||
|
||||
|
||||
IDENTITY_TABLES = ("users", "sessions")
|
||||
MESSAGING_TABLES = ("chats", "chat_members", "messages", "idempotency_keys")
|
||||
MESSAGING_TABLES = ("chats", "chat_members", "messages", "idempotency_keys", "message_attachments")
|
||||
ATTACHMENT_TABLES = ("attachments",)
|
||||
|
||||
|
||||
def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
|
||||
@@ -228,10 +247,14 @@ def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
|
||||
|
||||
|
||||
def test_sql_of_each_zone_reads_only_its_tables() -> None:
|
||||
assert sql_tables("messaging", IDENTITY_TABLES) == set()
|
||||
assert sql_tables("identity", MESSAGING_TABLES) == set()
|
||||
assert sql_tables("messaging", MESSAGING_TABLES) == set(MESSAGING_TABLES)
|
||||
assert sql_tables("identity", IDENTITY_TABLES) == set(IDENTITY_TABLES)
|
||||
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:
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import actor, keyed, make_chat, register
|
||||
from pictures import SAMPLE
|
||||
|
||||
|
||||
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 == 201, 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]
|
||||
@@ -62,6 +62,7 @@ async def test_created_at_is_rfc3339_utc(monkeypatch: pytest.MonkeyPatch, moment
|
||||
"sender_id": user_id,
|
||||
"text": "привет",
|
||||
"created_at": stamp,
|
||||
"attachment_ids": [],
|
||||
}
|
||||
assert_wire(response, message)
|
||||
history = await http.get(path, headers=headers)
|
||||
|
||||
Reference in New Issue
Block a user