refactor: move services to a unit of work over repository ports
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>
This commit is contained in:
+75
-72
@@ -6,6 +6,7 @@ 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
|
||||
@@ -46,77 +47,79 @@ def to_message_dto(fields: Mapping[str, Any]) -> dataclasses.MessageFullDTO:
|
||||
)
|
||||
|
||||
|
||||
async def insert_message(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
instance_id: str,
|
||||
) -> dataclasses.MessageFullDTO:
|
||||
"""Строка сообщения; `instance_id` — реплика, которая его записала
|
||||
(колонка только для диагностики, в DTO и ответ не попадает). Связи с
|
||||
вложениями пишет `insert_message_attachments`."""
|
||||
await db_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
|
||||
class SqlAlchemyMessageRepository(AbstractMessageRepository):
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
|
||||
async def insert_message_attachments(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
) -> int:
|
||||
"""Все связи одной вставкой; `position` — место в `attachment_ids`.
|
||||
|
||||
Вызывается только с непустым `attachment_ids`. `created_at` связи —
|
||||
время сообщения.
|
||||
"""
|
||||
result = await db_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(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
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),
|
||||
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,
|
||||
),
|
||||
)
|
||||
rows = (await db_session.execute(statement)).all()
|
||||
return [to_message_dto(row._mapping) for row in rows]
|
||||
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]
|
||||
|
||||
Reference in New Issue
Block a user