Services depend only on src/core/ports: async with self.uow is one transaction, commit is explicit, leaving without it rolls back. A connection is held per step, the JSON routers keep a shared request deadline, and rollback runs under the block deadline. Adds service-tests with fakes, a repo contract run on both the fake and SQL, and make service_test / service_test_db. API, schema and settings are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
126 lines
4.6 KiB
Python
126 lines
4.6 KiB
Python
from collections.abc import Mapping
|
|
from typing import Any
|
|
from uuid import UUID
|
|
|
|
from sqlalchemy import Uuid, func, insert, select, tuple_
|
|
from sqlalchemy.dialects.postgresql import ARRAY
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from src.core.ports.message import AbstractMessageRepository
|
|
from src.infra.db.models import Message, MessageAttachment
|
|
from src.schemas import dataclasses
|
|
from src.utils.cursor import CursorKey
|
|
|
|
# вложения сообщения в порядке отправки: коррелированный подзапрос по
|
|
# первичному ключу `(message_id, position)` на каждую строку страницы,
|
|
# индекс истории прежний (design change `attachments`, решение 8). Нет
|
|
# вложений — пустой массив, а не NULL
|
|
_ATTACHMENT_IDS = func.array(
|
|
select(MessageAttachment.attachment_id)
|
|
.where(MessageAttachment.message_id == Message.id)
|
|
.order_by(MessageAttachment.position)
|
|
.scalar_subquery(),
|
|
type_=ARRAY(Uuid()),
|
|
).label("attachment_ids")
|
|
|
|
# колонки MessageFullDTO; их же выбирает чтение сохранённого результата
|
|
# ключа идемпотентности
|
|
MESSAGE_COLUMNS = (
|
|
Message.id,
|
|
Message.chat_id,
|
|
Message.sender_id,
|
|
Message.text,
|
|
Message.created_at,
|
|
_ATTACHMENT_IDS,
|
|
)
|
|
|
|
|
|
def to_message_dto(fields: Mapping[str, Any]) -> dataclasses.MessageFullDTO:
|
|
"""DTO из колонок `MESSAGE_COLUMNS`."""
|
|
return dataclasses.MessageFullDTO(
|
|
id=fields["id"],
|
|
chat_id=fields["chat_id"],
|
|
sender_id=fields["sender_id"],
|
|
text=fields["text"],
|
|
created_at=fields["created_at"],
|
|
attachment_ids=tuple(fields["attachment_ids"]),
|
|
)
|
|
|
|
|
|
class SqlAlchemyMessageRepository(AbstractMessageRepository):
|
|
def __init__(self, session: AsyncSession) -> None:
|
|
self._session = session
|
|
|
|
async def insert_message(
|
|
self,
|
|
*,
|
|
message: dataclasses.MessageFullDTO,
|
|
instance_id: str,
|
|
) -> dataclasses.MessageFullDTO:
|
|
"""Строка сообщения; `instance_id` — реплика, которая его записала
|
|
(колонка только для диагностики, в DTO и ответ не попадает). Связи с
|
|
вложениями пишет `insert_message_attachments`."""
|
|
await self._session.execute(
|
|
insert(Message).values(
|
|
id=message.id,
|
|
chat_id=message.chat_id,
|
|
sender_id=message.sender_id,
|
|
text=message.text,
|
|
created_at=message.created_at,
|
|
instance_id=instance_id,
|
|
),
|
|
)
|
|
return message
|
|
|
|
async def insert_message_attachments(
|
|
self,
|
|
*,
|
|
message: dataclasses.MessageFullDTO,
|
|
) -> int:
|
|
"""Все связи одной вставкой; `position` — место в `attachment_ids`.
|
|
|
|
Вызывается только с непустым `attachment_ids`. `created_at` связи —
|
|
время сообщения.
|
|
"""
|
|
result = await self._session.execute(
|
|
insert(MessageAttachment).values(
|
|
[
|
|
{
|
|
"message_id": message.id,
|
|
"position": position,
|
|
"attachment_id": attachment_id,
|
|
"created_at": message.created_at,
|
|
}
|
|
for position, attachment_id in enumerate(
|
|
message.attachment_ids,
|
|
)
|
|
],
|
|
),
|
|
)
|
|
return result.rowcount
|
|
|
|
async def get_chat_messages_page(
|
|
self,
|
|
*,
|
|
chat_id: UUID,
|
|
after: CursorKey | None,
|
|
limit: int,
|
|
) -> list[dataclasses.MessageFullDTO]:
|
|
"""До `limit + 1` сообщений чата строго после ключа `after`.
|
|
|
|
Keyset по индексу `(chat_id, created_at, id)`, без OFFSET: страница
|
|
не просматривает историю до курсора.
|
|
"""
|
|
statement = (
|
|
select(*MESSAGE_COLUMNS)
|
|
.where(Message.chat_id == chat_id)
|
|
.order_by(Message.created_at, Message.id)
|
|
.limit(limit + 1)
|
|
)
|
|
if after is not None:
|
|
statement = statement.where(
|
|
tuple_(Message.created_at, Message.id) > tuple_(*after),
|
|
)
|
|
rows = (await self._session.execute(statement)).all()
|
|
return [to_message_dto(row._mapping) for row in rows]
|