Refuse failed attachments in messages through a zone port

The messaging zone asks a new AttachmentStates port whether any listed
attachment of the chat has failed and answers 409 conflict before the
message is stored; queued and processing attachments can still be
sent right after the upload. The check runs only on the first execution
of a key, so a replay returns the original 201 even if the attachment
failed later. main.py wires the port to the attachments directory, so
neither zone reads the other's tables.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Artyom
2026-10-29 01:09:31 +03:00
co-authored by Claude Opus 5.5
parent b152b6e07e
commit 34741dc2d2
8 changed files with 95 additions and 12 deletions
@@ -27,9 +27,9 @@
## 5. Связь зон ## 5. Связь зон
- [ ] 5.1 `messaging`: порт `AttachmentStates`, ошибка `AttachmentUnavailable` → `409`, проверка только для первого исполнения (повтор по ключу возвращает исходный ответ) - [x] 5.1 `messaging`: порт `AttachmentStates`, ошибка `AttachmentUnavailable` → `409`, проверка только для первого исполнения (повтор по ключу возвращает исходный ответ)
- [ ] 5.2 `main.py`: адаптер порта поверх `AttachmentDirectory`, версия 1.5.0 - [x] 5.2 `main.py`: адаптер порта поверх `AttachmentDirectory`, версия 1.5.0
- [ ] 5.3 Проверка группы: API-тесты — `202 queued`, `409` на `/content` до `ready`, `400` на неизвестный `variant`, `404` на `crop`, сообщение с `queued` — `201`, с `failed` — `409` - [x] 5.3 Проверка группы: API-тесты — `202 queued`, `409` на `/content` до `ready`, `400` на неизвестный `variant`, `404` на `crop`, сообщение с `queued` — `201`, с `failed` — `409`
## 6. Стенд ## 6. Стенд
+16 -2
View File
@@ -6,7 +6,7 @@ from dishka import Provider, Scope, make_async_container, provide
from dishka.integrations.fastapi import FastapiProvider, setup_dishka from dishka.integrations.fastapi import FastapiProvider, setup_dishka
from fastapi import FastAPI from fastapi import FastAPI
from messenger.attachments.application.ports import ChatMembership from messenger.attachments.application.ports import AttachmentDirectory, ChatMembership
from messenger.attachments.config import AttachmentsSettings from messenger.attachments.config import AttachmentsSettings
from messenger.attachments.entrypoints.errors import ERROR_CODES as ATTACHMENT_ERRORS from messenger.attachments.entrypoints.errors import ERROR_CODES as ATTACHMENT_ERRORS
from messenger.attachments.entrypoints.http import UPLOAD_PATH, attachments_router, uploads_router from messenger.attachments.entrypoints.http import UPLOAD_PATH, attachments_router, uploads_router
@@ -23,7 +23,7 @@ from messenger.identity.entrypoints.http import sessions_router
from messenger.identity.entrypoints.ioc import IdentityProvider from messenger.identity.entrypoints.ioc import IdentityProvider
from messenger.identity.entrypoints.journal import LOG_FIELDS as IDENTITY_FIELDS from messenger.identity.entrypoints.journal import LOG_FIELDS as IDENTITY_FIELDS
from messenger.identity.entrypoints.journal import IdentityJournal from messenger.identity.entrypoints.journal import IdentityJournal
from messenger.messaging.application.ports import ChatDirectory from messenger.messaging.application.ports import AttachmentStates, ChatDirectory
from messenger.messaging.config import MessagingSettings from messenger.messaging.config import MessagingSettings
from messenger.messaging.domain.events import ChatCreated, MessagePosted from messenger.messaging.domain.events import ChatCreated, MessagePosted
from messenger.messaging.entrypoints.errors import ERROR_CODES as MESSAGING_ERRORS from messenger.messaging.entrypoints.errors import ERROR_CODES as MESSAGING_ERRORS
@@ -58,11 +58,25 @@ class MessagingMembership:
return await self._chats.chat_for_member(chat_id, user_id) is not None return await self._chats.chat_for_member(chat_id, user_id) is not None
class AttachmentGate:
__slots__ = ("_attachments",)
def __init__(self, attachments: AttachmentDirectory) -> None:
self._attachments = attachments
async def unusable(self, chat_id: UUID, attachment_ids: Sequence[UUID]) -> bool:
return await self._attachments.failed_among(chat_id, attachment_ids)
class ZoneLinks(Provider): class ZoneLinks(Provider):
@provide(scope=Scope.APP) @provide(scope=Scope.APP)
def membership(self, chats: ChatDirectory) -> ChatMembership: def membership(self, chats: ChatDirectory) -> ChatMembership:
return MessagingMembership(chats) return MessagingMembership(chats)
@provide(scope=Scope.APP)
def attachment_states(self, attachments: AttachmentDirectory) -> AttachmentStates:
return AttachmentGate(attachments)
def wire_events(bus: EventBus, logger: Logger) -> None: def wire_events(bus: EventBus, logger: Logger) -> None:
identity = IdentityJournal(logger) identity = IdentityJournal(logger)
@@ -1,8 +1,8 @@
from datetime import timedelta from datetime import timedelta
from messenger.messaging.application.commands import CreateChat, PostMessage from messenger.messaging.application.commands import CreateChat, PostMessage
from messenger.messaging.application.ports import MessagingUnitOfWork from messenger.messaging.application.ports import AttachmentStates, MessagingUnitOfWork
from messenger.messaging.domain.errors import ChatNotFound from messenger.messaging.domain.errors import AttachmentUnavailable, ChatNotFound
from messenger.messaging.domain.models import Chat, Message, Receipt from messenger.messaging.domain.models import Chat, Message, Receipt
from messenger.shared.application.ports import Clock, IdGenerator from messenger.shared.application.ports import Clock, IdGenerator
@@ -30,12 +30,18 @@ class CreateChatHandler:
class PostMessageHandler: class PostMessageHandler:
__slots__ = ("_clock", "_ids", "_ttl", "_uow") __slots__ = ("_attachments", "_clock", "_ids", "_ttl", "_uow")
def __init__( def __init__(
self, uow: MessagingUnitOfWork, clock: Clock, ids: IdGenerator, ttl: timedelta self,
uow: MessagingUnitOfWork,
attachments: AttachmentStates,
clock: Clock,
ids: IdGenerator,
ttl: timedelta,
) -> None: ) -> None:
self._uow = uow self._uow = uow
self._attachments = attachments
self._clock = clock self._clock = clock
self._ids = ids self._ids = ids
self._ttl = ttl self._ttl = ttl
@@ -58,6 +64,10 @@ class PostMessageHandler:
) )
if known is not None: if known is not None:
return known.replay(command.fingerprint) return known.replay(command.fingerprint)
if message.attachment_ids and await self._attachments.unusable(
chat.id, message.attachment_ids
):
raise AttachmentUnavailable("вложение не обработано и не может быть отправлено")
await self._uow.chats.append(Receipt(command.key, command.fingerprint, message)) await self._uow.chats.append(Receipt(command.key, command.fingerprint, message))
await self._uow.commit() await self._uow.commit()
return message return message
@@ -1,3 +1,4 @@
from collections.abc import Sequence
from datetime import datetime from datetime import datetime
from typing import Protocol, runtime_checkable from typing import Protocol, runtime_checkable
from uuid import UUID from uuid import UUID
@@ -33,6 +34,11 @@ class MessagingUnitOfWork(UnitOfWork, Protocol):
def chats(self) -> ChatRepository: ... def chats(self) -> ChatRepository: ...
@runtime_checkable
class AttachmentStates(Protocol):
async def unusable(self, chat_id: UUID, attachment_ids: Sequence[UUID]) -> bool: ...
@runtime_checkable @runtime_checkable
class ChatDirectory(Protocol): class ChatDirectory(Protocol):
async def chat_for_member(self, chat_id: UUID, user_id: UUID) -> Chat | None: ... async def chat_for_member(self, chat_id: UUID, user_id: UUID) -> Chat | None: ...
+4
View File
@@ -31,3 +31,7 @@ class InvalidAttachmentList(MessagingError):
class UnknownAttachment(MessagingError): class UnknownAttachment(MessagingError):
pass pass
class AttachmentUnavailable(MessagingError):
pass
@@ -1,4 +1,5 @@
from messenger.messaging.domain.errors import ( from messenger.messaging.domain.errors import (
AttachmentUnavailable,
ChatNotFound, ChatNotFound,
IdempotencyConflict, IdempotencyConflict,
InvalidAttachmentList, InvalidAttachmentList,
@@ -17,4 +18,5 @@ ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
ChatNotFound: ("not_found", 404), ChatNotFound: ("not_found", 404),
UnknownAttachment: ("not_found", 404), UnknownAttachment: ("not_found", 404),
IdempotencyConflict: ("conflict", 409), IdempotencyConflict: ("conflict", 409),
AttachmentUnavailable: ("conflict", 409),
} }
+8 -2
View File
@@ -5,7 +5,12 @@ from dishka import Provider, Scope, provide
from messenger.messaging.application.bus import MessagingCommandBus from messenger.messaging.application.bus import MessagingCommandBus
from messenger.messaging.application.commands import CreateChat, PostMessage from messenger.messaging.application.commands import CreateChat, PostMessage
from messenger.messaging.application.handlers import CreateChatHandler, PostMessageHandler from messenger.messaging.application.handlers import CreateChatHandler, PostMessageHandler
from messenger.messaging.application.ports import ChatDirectory, CursorCodec, MessagingUnitOfWork from messenger.messaging.application.ports import (
AttachmentStates,
ChatDirectory,
CursorCodec,
MessagingUnitOfWork,
)
from messenger.messaging.application.queries import GetChat, ListChats, ReadHistory from messenger.messaging.application.queries import GetChat, ListChats, ReadHistory
from messenger.messaging.config import MessagingSettings from messenger.messaging.config import MessagingSettings
from messenger.messaging.infrastructure.cursor import SignedCursorCodec from messenger.messaging.infrastructure.cursor import SignedCursorCodec
@@ -56,6 +61,7 @@ class MessagingProvider(Provider):
def command_bus( def command_bus(
self, self,
uow: MessagingUnitOfWork, uow: MessagingUnitOfWork,
attachments: AttachmentStates,
publisher: EventPublisher, publisher: EventPublisher,
clock: Clock, clock: Clock,
ids: IdGenerator, ids: IdGenerator,
@@ -64,6 +70,6 @@ class MessagingProvider(Provider):
ttl = timedelta(seconds=settings.idempotency_ttl_seconds) ttl = timedelta(seconds=settings.idempotency_ttl_seconds)
handlers: dict[type[Command], CommandHandler] = { handlers: dict[type[Command], CommandHandler] = {
CreateChat: CreateChatHandler(uow, clock, ids), CreateChat: CreateChatHandler(uow, clock, ids),
PostMessage: PostMessageHandler(uow, clock, ids, ttl), PostMessage: PostMessageHandler(uow, attachments, clock, ids, ttl),
} }
return MessagingCommandBus(handlers, uow, publisher) return MessagingCommandBus(handlers, uow, publisher)
+42 -1
View File
@@ -4,8 +4,11 @@ from uuid import uuid4
import pytest import pytest
from httpx import AsyncClient from httpx import AsyncClient
from conftest import actor, keyed, make_chat, register 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 pictures import SAMPLE
from pipeline import settle
async def attach(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str: async def attach(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
@@ -106,3 +109,41 @@ async def test_one_attachment_in_several_messages(client: AsyncClient) -> None:
response = await send(client, user, chat, {"text": "", "attachment_ids": [file]}) response = await send(client, user, chat, {"text": "", "attachment_ids": [file]})
assert response.status_code == 201 assert response.status_code == 201
assert response.json()["attachment_ids"] == [file] 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()