forked from mtusi2026/mtusi2026lab2
Forward the lab 5 foundation while preserving lab 6 telemetry
Source: immutable lab5 snapshot f88e9ba43cdfd7eb6a5a7ae5feb4247b4e820071; forward the allowed diff from 64d5c67. Carry SQLAlchemy, Alembic, reliability fixes, versioned jobs, infrastructure and student tests without changing protected coursework files.
Validation: make check, validate, lint; 515 student tests passed with one Linux-only skip; public smoke with telemetry enabled and repeat migration passed. Stop the owned stack and retain volumes. Preserve the existing OTel work in progress; grade implementation remains a separate phase.
This commit is contained in:
@@ -1,9 +1,14 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from messenger.messaging.application.commands import CreateChat, PostMessage
|
||||
from messenger.messaging.application.ports import AttachmentStates, MessagingUnitOfWork
|
||||
from messenger.messaging.domain.errors import AttachmentUnavailable, ChatNotFound
|
||||
from messenger.messaging.domain.models import Chat, Message, Receipt
|
||||
from messenger.messaging.application.ports import ChatDirectory, MessageLog, MessagingUnitOfWork
|
||||
from messenger.messaging.domain.errors import (
|
||||
ChatNotFound,
|
||||
InvalidAttachmentList,
|
||||
InvalidMessageText,
|
||||
)
|
||||
from messenger.messaging.domain.models import Chat, Message, attachment_list
|
||||
from messenger.messaging.domain.values import MessageText
|
||||
from messenger.shared.application.ports import Clock, IdGenerator
|
||||
|
||||
|
||||
@@ -30,44 +35,41 @@ class CreateChatHandler:
|
||||
|
||||
|
||||
class PostMessageHandler:
|
||||
__slots__ = ("_attachments", "_clock", "_ids", "_ttl", "_uow")
|
||||
__slots__ = ("_chats", "_clock", "_ids", "_log", "_ttl", "_uow")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: MessagingUnitOfWork,
|
||||
attachments: AttachmentStates,
|
||||
log: MessageLog,
|
||||
chats: ChatDirectory,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
*,
|
||||
ttl: timedelta,
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._attachments = attachments
|
||||
self._log = log
|
||||
self._chats = chats
|
||||
self._clock = clock
|
||||
self._ids = ids
|
||||
self._ttl = ttl
|
||||
|
||||
async def __call__(self, command: PostMessage) -> Message:
|
||||
async with self._uow.transaction():
|
||||
chat = await self._uow.chats.get(command.chat_id)
|
||||
if chat is None:
|
||||
raise ChatNotFound("чат не найден")
|
||||
now = self._clock.now()
|
||||
message = chat.post(
|
||||
message_id=self._ids.new_id(),
|
||||
sender_id=command.sender_id,
|
||||
text=command.text,
|
||||
now=now,
|
||||
attachment_ids=command.attachment_ids,
|
||||
)
|
||||
known = await self._uow.chats.receipt(
|
||||
chat.id, command.sender_id, command.key, now - self._ttl
|
||||
)
|
||||
if known is not None:
|
||||
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.commit()
|
||||
try:
|
||||
text = MessageText(command.text)
|
||||
attachments = attachment_list(text, command.attachment_ids)
|
||||
except InvalidMessageText, InvalidAttachmentList:
|
||||
if await self._chats.chat_for_member(command.chat_id, command.sender_id) is None:
|
||||
raise ChatNotFound("чат не найден") from None
|
||||
raise
|
||||
now = self._clock.now()
|
||||
draft = Message(
|
||||
self._ids.new_id(), command.chat_id, command.sender_id, text, now, attachments
|
||||
)
|
||||
receipt = await self._log.post(draft, command.key, command.fingerprint, now - self._ttl)
|
||||
if receipt is None:
|
||||
raise ChatNotFound("чат не найден")
|
||||
message = receipt.replay(command.fingerprint)
|
||||
if message.id == draft.id:
|
||||
self._uow.record(message.posted())
|
||||
return message
|
||||
|
||||
@@ -19,14 +19,13 @@ class CursorCodec(Protocol):
|
||||
class ChatRepository(Protocol):
|
||||
async def add(self, chat: Chat) -> None: ...
|
||||
|
||||
async def get(self, chat_id: UUID) -> Chat | None: ...
|
||||
|
||||
async def receipt(
|
||||
self, chat_id: UUID, sender_id: UUID, key: str, since: datetime
|
||||
@runtime_checkable
|
||||
class MessageLog(Protocol):
|
||||
async def post(
|
||||
self, message: Message, key: str, fingerprint: bytes, since: datetime
|
||||
) -> Receipt | None: ...
|
||||
|
||||
async def append(self, receipt: Receipt) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class MessagingUnitOfWork(UnitOfWork, Protocol):
|
||||
|
||||
@@ -43,7 +43,7 @@ class ListChats:
|
||||
|
||||
async def __call__(self, user_id: UUID, *, limit: int, cursor: str | None) -> Page[Chat]:
|
||||
scope = chats_scope(user_id)
|
||||
after: HistoryKey | None = self._cursors.decode(scope, cursor) if cursor else None
|
||||
after: HistoryKey | None = None if cursor is None else self._cursors.decode(scope, cursor)
|
||||
items, has_more = await self._chats.chats_of(user_id, after=after, limit=limit)
|
||||
next_cursor = self._cursors.encode(scope, items[-1].key) if has_more and items else None
|
||||
return Page(items=items, next_cursor=next_cursor)
|
||||
@@ -67,7 +67,7 @@ class ReadHistory:
|
||||
if await self._chats.chat_for_member(chat_id, user_id) is None:
|
||||
raise ChatNotFound("чат не найден")
|
||||
scope = messages_scope(chat_id)
|
||||
after: HistoryKey | None = self._cursors.decode(scope, cursor) if cursor else None
|
||||
after: HistoryKey | None = None if cursor is None else self._cursors.decode(scope, cursor)
|
||||
items, has_more = await self._chats.history(chat_id, after=after, limit=limit)
|
||||
next_cursor = self._cursors.encode(scope, items[-1].key) if has_more and items else None
|
||||
return Page(items=items, next_cursor=next_cursor)
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.messaging.domain.errors import (
|
||||
ChatNotFound,
|
||||
IdempotencyConflict,
|
||||
InvalidAttachmentList,
|
||||
InvalidChatData,
|
||||
@@ -20,8 +19,6 @@ from messenger.messaging.domain.values import (
|
||||
)
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
TICK = timedelta(microseconds=1)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Message:
|
||||
@@ -36,6 +33,15 @@ class Message:
|
||||
def key(self) -> HistoryKey:
|
||||
return (self.created_at, self.id.int)
|
||||
|
||||
def posted(self) -> MessagePosted:
|
||||
return MessagePosted(
|
||||
message_id=self.id,
|
||||
chat_id=self.chat_id,
|
||||
sender_id=self.sender_id,
|
||||
text_length=len(self.text.value),
|
||||
created_at=self.created_at,
|
||||
)
|
||||
|
||||
|
||||
def attachment_list(text: MessageText, attachment_ids: Sequence[UUID]) -> tuple[UUID, ...]:
|
||||
if len(attachment_ids) > MESSAGE_ATTACHMENTS_MAX:
|
||||
@@ -62,15 +68,7 @@ class Receipt:
|
||||
|
||||
|
||||
class Chat:
|
||||
__slots__ = (
|
||||
"_events",
|
||||
"_members",
|
||||
"created_at",
|
||||
"id",
|
||||
"last_message_at",
|
||||
"member_ids",
|
||||
"title",
|
||||
)
|
||||
__slots__ = ("_events", "created_at", "id", "member_ids", "title")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -79,14 +77,11 @@ class Chat:
|
||||
title: ChatTitle,
|
||||
member_ids: Sequence[UUID],
|
||||
created_at: datetime,
|
||||
last_message_at: datetime | None = None,
|
||||
) -> None:
|
||||
self.id = chat_id
|
||||
self.title = title
|
||||
self.member_ids: tuple[UUID, ...] = tuple(member_ids)
|
||||
self.created_at = created_at
|
||||
self.last_message_at = last_message_at
|
||||
self._members: frozenset[UUID] = frozenset(member_ids)
|
||||
self._events: list[DomainEvent] = []
|
||||
|
||||
@classmethod
|
||||
@@ -131,47 +126,6 @@ class Chat:
|
||||
def record(self, event: DomainEvent) -> None:
|
||||
self._events.append(event)
|
||||
|
||||
def is_member(self, user_id: UUID) -> bool:
|
||||
return user_id in self._members
|
||||
|
||||
def require_member(self, user_id: UUID) -> None:
|
||||
if not self.is_member(user_id):
|
||||
raise ChatNotFound("чат не найден")
|
||||
|
||||
def post(
|
||||
self,
|
||||
*,
|
||||
message_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
now: datetime,
|
||||
attachment_ids: Sequence[UUID] = (),
|
||||
) -> Message:
|
||||
self.require_member(sender_id)
|
||||
body = MessageText(text)
|
||||
attachments = attachment_list(body, attachment_ids)
|
||||
last = self.last_message_at
|
||||
created_at = now if last is None or now > last else last + TICK
|
||||
message = Message(
|
||||
id=message_id,
|
||||
chat_id=self.id,
|
||||
sender_id=sender_id,
|
||||
text=body,
|
||||
created_at=created_at,
|
||||
attachment_ids=attachments,
|
||||
)
|
||||
self.last_message_at = created_at
|
||||
self.record(
|
||||
MessagePosted(
|
||||
message_id=message.id,
|
||||
chat_id=self.id,
|
||||
sender_id=sender_id,
|
||||
text_length=len(message.text.value),
|
||||
created_at=created_at,
|
||||
)
|
||||
)
|
||||
return message
|
||||
|
||||
def collect_events(self) -> list[DomainEvent]:
|
||||
events, self._events = self._events, []
|
||||
return events
|
||||
|
||||
@@ -9,6 +9,7 @@ from messenger.messaging.application.ports import (
|
||||
AttachmentStates,
|
||||
ChatDirectory,
|
||||
CursorCodec,
|
||||
MessageLog,
|
||||
MessagingUnitOfWork,
|
||||
)
|
||||
from messenger.messaging.application.queries import GetChat, ListChats, ReadHistory
|
||||
@@ -16,6 +17,7 @@ from messenger.messaging.config import MessagingSettings
|
||||
from messenger.messaging.infrastructure.cursor import SignedCursorCodec
|
||||
from messenger.messaging.infrastructure.postgres import (
|
||||
PostgresChatDirectory,
|
||||
PostgresMessageLog,
|
||||
PostgresMessagingUnitOfWork,
|
||||
)
|
||||
from messenger.shared.application.commands import Command
|
||||
@@ -37,6 +39,10 @@ class MessagingProvider(Provider):
|
||||
def directory(self, database: Database) -> ChatDirectory:
|
||||
return PostgresChatDirectory(database)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def log(self, database: Database, attachments: AttachmentStates) -> MessageLog:
|
||||
return PostgresMessageLog(database, attachments)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def cursors(self, settings: MessagingSettings) -> CursorCodec:
|
||||
return SignedCursorCodec(settings.cursor_secret.get_secret_value().encode())
|
||||
@@ -61,7 +67,8 @@ class MessagingProvider(Provider):
|
||||
def command_bus(
|
||||
self,
|
||||
uow: MessagingUnitOfWork,
|
||||
attachments: AttachmentStates,
|
||||
log: MessageLog,
|
||||
directory: ChatDirectory,
|
||||
publisher: EventPublisher,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
@@ -70,6 +77,6 @@ class MessagingProvider(Provider):
|
||||
ttl = timedelta(seconds=settings.idempotency_ttl_seconds)
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
CreateChat: CreateChatHandler(uow, clock, ids),
|
||||
PostMessage: PostMessageHandler(uow, attachments, clock, ids, ttl),
|
||||
PostMessage: PostMessageHandler(uow, log, directory, clock, ids, ttl=ttl),
|
||||
}
|
||||
return MessagingCommandBus(handlers, uow, publisher)
|
||||
|
||||
@@ -37,7 +37,7 @@ class CreateMessageRequest(BaseModel):
|
||||
|
||||
class PageQuery(BaseModel):
|
||||
limit: int = Field(default=50, ge=1, le=100)
|
||||
cursor: str | None = None
|
||||
cursor: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
class ChatOut(BaseModel):
|
||||
|
||||
@@ -1,122 +1,266 @@
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timedelta
|
||||
from typing import cast
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import ForeignKeyViolationError, Record
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
ForeignKeyConstraint,
|
||||
Index,
|
||||
LargeBinary,
|
||||
RowMapping,
|
||||
Select,
|
||||
SmallInteger,
|
||||
Table,
|
||||
UniqueConstraint,
|
||||
bindparam,
|
||||
column,
|
||||
func,
|
||||
insert,
|
||||
lambda_stmt,
|
||||
literal,
|
||||
select,
|
||||
true,
|
||||
tuple_,
|
||||
update,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import ARRAY
|
||||
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.sql.elements import Label
|
||||
|
||||
from messenger.messaging.domain.errors import InvalidChatData, UnknownAttachment
|
||||
from messenger.messaging.application.ports import AttachmentStates
|
||||
from messenger.messaging.domain.errors import (
|
||||
AttachmentUnavailable,
|
||||
InvalidChatData,
|
||||
UnknownAttachment,
|
||||
)
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
from messenger.messaging.domain.models import Chat, Message, Receipt
|
||||
from messenger.messaging.domain.values import ChatTitle, MessageText
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.infrastructure.postgres import (
|
||||
Connection,
|
||||
Base,
|
||||
Database,
|
||||
DatabaseSession,
|
||||
EventSource,
|
||||
PostgresUnitOfWork,
|
||||
)
|
||||
|
||||
INSERT_CHAT = "INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)"
|
||||
INSERT_MEMBERS = """
|
||||
INSERT INTO chat_members (chat_id, user_id, position, chat_created_at)
|
||||
SELECT $1, member.user_id, member.position, $3
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS member (user_id, position)
|
||||
"""
|
||||
LOCK_CHAT = """
|
||||
SELECT c.id, c.title, c.created_at, c.last_message_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
|
||||
FROM chats c
|
||||
WHERE c.id = $1
|
||||
FOR UPDATE
|
||||
"""
|
||||
ATTACHMENT_FKEY = "message_attachments_attachment_fkey"
|
||||
RECEIPT = """
|
||||
SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.chat_id = $1 AND k.user_id = $2 AND k.key = $3 AND k.created_at > $4
|
||||
"""
|
||||
APPEND_MESSAGE = """
|
||||
WITH message AS (
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id, chat_id, sender_id, created_at
|
||||
), links AS (
|
||||
INSERT INTO message_attachments (message_id, position, chat_id, attachment_id)
|
||||
SELECT message.id, link.position - 1, message.chat_id, link.attachment_id
|
||||
FROM message, unnest($8::uuid[]) WITH ORDINALITY AS link (attachment_id, position)
|
||||
), receipt AS (
|
||||
INSERT INTO idempotency_keys (chat_id, user_id, key, fingerprint, message_id, created_at)
|
||||
SELECT chat_id, sender_id, $6, $7, id, created_at FROM message
|
||||
ON CONFLICT (chat_id, user_id, key) DO UPDATE
|
||||
SET fingerprint = EXCLUDED.fingerprint,
|
||||
message_id = EXCLUDED.message_id,
|
||||
created_at = EXCLUDED.created_at
|
||||
)
|
||||
UPDATE chats SET last_message_at = message.created_at
|
||||
FROM message
|
||||
WHERE chats.id = message.chat_id
|
||||
"""
|
||||
CHAT_OF_MEMBER = """
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
|
||||
FROM chat_members m JOIN chats c ON c.id = m.chat_id
|
||||
WHERE m.chat_id = $1 AND m.user_id = $2
|
||||
"""
|
||||
CHATS_FIRST = """
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
|
||||
FROM chat_members m JOIN chats c ON c.id = m.chat_id
|
||||
WHERE m.user_id = $1
|
||||
ORDER BY m.chat_created_at, m.chat_id
|
||||
LIMIT $2
|
||||
"""
|
||||
CHATS_AFTER = """
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
|
||||
FROM chat_members m JOIN chats c ON c.id = m.chat_id
|
||||
WHERE m.user_id = $1 AND (m.chat_created_at, m.chat_id) > ($2, $3)
|
||||
ORDER BY m.chat_created_at, m.chat_id
|
||||
LIMIT $4
|
||||
"""
|
||||
HISTORY_FIRST = """
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $2
|
||||
"""
|
||||
HISTORY_AFTER = """
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4
|
||||
"""
|
||||
FOREIGN_KEY_VIOLATED = "23503"
|
||||
|
||||
|
||||
def chat_of(row: Record) -> Chat:
|
||||
class ChatRow(Base):
|
||||
__tablename__ = "chats"
|
||||
__table_args__ = (
|
||||
CheckConstraint("char_length(title) BETWEEN 1 AND 100", name="chats_title_check"),
|
||||
)
|
||||
|
||||
id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
title: Mapped[str]
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
last_message_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class ChatMemberRow(Base):
|
||||
__tablename__ = "chat_members"
|
||||
__table_args__ = (
|
||||
CheckConstraint("position BETWEEN 1 AND 100", name="chat_members_position_check"),
|
||||
Index("chat_members_user_idx", "user_id", "chat_created_at", "chat_id"),
|
||||
)
|
||||
|
||||
chat_id: Mapped[UUID] = mapped_column(
|
||||
ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
user_id: Mapped[UUID] = mapped_column(ForeignKey("users.id"), primary_key=True)
|
||||
position: Mapped[int] = mapped_column(SmallInteger)
|
||||
chat_created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class MessageRow(Base):
|
||||
__tablename__ = "messages"
|
||||
__table_args__ = (
|
||||
CheckConstraint("char_length(text) <= 4000", name="messages_text_check"),
|
||||
ForeignKeyConstraint(
|
||||
["chat_id", "sender_id"], ["chat_members.chat_id", "chat_members.user_id"]
|
||||
),
|
||||
Index("messages_history_idx", "chat_id", "created_at", "id"),
|
||||
)
|
||||
|
||||
id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
chat_id: Mapped[UUID]
|
||||
sender_id: Mapped[UUID]
|
||||
text: Mapped[str]
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class IdempotencyKeyRow(Base):
|
||||
__tablename__ = "idempotency_keys"
|
||||
__table_args__ = (
|
||||
CheckConstraint("key ~ '^[A-Za-z0-9._:-]{1,128}$'", name="idempotency_keys_key_check"),
|
||||
CheckConstraint(
|
||||
"octet_length(fingerprint) = 32", name="idempotency_keys_fingerprint_check"
|
||||
),
|
||||
ForeignKeyConstraint(
|
||||
["chat_id", "user_id"], ["chat_members.chat_id", "chat_members.user_id"]
|
||||
),
|
||||
)
|
||||
|
||||
chat_id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
key: Mapped[str] = mapped_column(primary_key=True)
|
||||
fingerprint: Mapped[bytes] = mapped_column(LargeBinary)
|
||||
message_id: Mapped[UUID] = mapped_column(ForeignKey("messages.id", ondelete="CASCADE"))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class MessageAttachmentRow(Base):
|
||||
__tablename__ = "message_attachments"
|
||||
__table_args__ = (
|
||||
CheckConstraint("position BETWEEN 0 AND 9", name="message_attachments_position_check"),
|
||||
UniqueConstraint("message_id", "attachment_id"),
|
||||
ForeignKeyConstraint(
|
||||
["attachment_id", "chat_id"],
|
||||
["attachments.id", "attachments.chat_id"],
|
||||
name="message_attachments_attachment_fkey",
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
Index("message_attachments_attachment_idx", "attachment_id"),
|
||||
)
|
||||
|
||||
message_id: Mapped[UUID] = mapped_column(
|
||||
ForeignKey("messages.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
position: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
chat_id: Mapped[UUID]
|
||||
attachment_id: Mapped[UUID]
|
||||
|
||||
|
||||
def post_message() -> Select:
|
||||
chats, members = cast(Table, ChatRow.__table__), cast(Table, ChatMemberRow.__table__)
|
||||
keys, messages = cast(Table, IdempotencyKeyRow.__table__), cast(Table, MessageRow.__table__)
|
||||
sender = bindparam("sender_id", type_=PGUUID)
|
||||
chat_id = bindparam("chat_id", type_=PGUUID)
|
||||
message_id = bindparam("message_id", type_=PGUUID)
|
||||
chat = (
|
||||
select(
|
||||
chats.c.id,
|
||||
func.greatest(
|
||||
bindparam("stamp", type_=DateTime(timezone=True)),
|
||||
chats.c.last_message_at + timedelta(microseconds=1),
|
||||
).label("stamp"),
|
||||
)
|
||||
.join(members, (members.c.chat_id == chats.c.id) & (members.c.user_id == sender))
|
||||
.where(chats.c.id == chat_id)
|
||||
.with_for_update(of=chats)
|
||||
.cte("chat")
|
||||
)
|
||||
receipt_insert = pg_insert(keys).from_select(
|
||||
["chat_id", "user_id", "key", "fingerprint", "message_id", "created_at"],
|
||||
select(
|
||||
chat.c.id,
|
||||
sender,
|
||||
bindparam("key"),
|
||||
bindparam("fingerprint", type_=LargeBinary),
|
||||
message_id,
|
||||
chat.c.stamp,
|
||||
),
|
||||
)
|
||||
receipt = (
|
||||
receipt_insert.on_conflict_do_update(
|
||||
index_elements=[keys.c.chat_id, keys.c.user_id, keys.c.key],
|
||||
set_={
|
||||
name: receipt_insert.excluded[name]
|
||||
for name in ("fingerprint", "message_id", "created_at")
|
||||
},
|
||||
where=keys.c.created_at <= bindparam("since", type_=DateTime(timezone=True)),
|
||||
)
|
||||
.returning(keys.c.created_at)
|
||||
.cte("receipt")
|
||||
)
|
||||
message = (
|
||||
insert(messages)
|
||||
.from_select(
|
||||
["id", "chat_id", "sender_id", "text", "created_at"],
|
||||
select(message_id, chat_id, sender, bindparam("text"), receipt.c.created_at),
|
||||
)
|
||||
.returning(messages.c.chat_id, messages.c.created_at)
|
||||
.cte("message")
|
||||
)
|
||||
attachments = (
|
||||
func.unnest(bindparam("attachment_ids", type_=ARRAY(PGUUID)))
|
||||
.table_valued(column("attachment_id", PGUUID), with_ordinality="position")
|
||||
.render_derived(name="attachment")
|
||||
)
|
||||
links = (
|
||||
insert(cast(Table, MessageAttachmentRow.__table__))
|
||||
.from_select(
|
||||
["message_id", "position", "chat_id", "attachment_id"],
|
||||
select(
|
||||
message_id, attachments.c.position - 1, chat_id, attachments.c.attachment_id
|
||||
).select_from(message.join(attachments, true())),
|
||||
)
|
||||
.cte("links")
|
||||
)
|
||||
touched = (
|
||||
update(chats)
|
||||
.where(chats.c.id == message.c.chat_id)
|
||||
.values(last_message_at=message.c.created_at)
|
||||
.cte("touched")
|
||||
)
|
||||
return select(
|
||||
select(chat.c.id).exists().label("member"),
|
||||
select(message.c.created_at).scalar_subquery().label("created_at"),
|
||||
).add_cte(links, touched)
|
||||
|
||||
|
||||
POST_MESSAGE = lambda_stmt(post_message, enable_tracking=False)
|
||||
|
||||
|
||||
def member_ids() -> Label[Sequence[UUID]]:
|
||||
return func.array(
|
||||
select(ChatMemberRow.user_id)
|
||||
.where(ChatMemberRow.chat_id == ChatRow.id)
|
||||
.order_by(ChatMemberRow.position)
|
||||
.correlate(ChatRow)
|
||||
.scalar_subquery(),
|
||||
type_=ARRAY(PGUUID(as_uuid=True)),
|
||||
).label("member_ids")
|
||||
|
||||
|
||||
def attachment_ids() -> Label[Sequence[UUID]]:
|
||||
return func.array(
|
||||
select(MessageAttachmentRow.attachment_id)
|
||||
.where(MessageAttachmentRow.message_id == MessageRow.id)
|
||||
.order_by(MessageAttachmentRow.position)
|
||||
.correlate(MessageRow)
|
||||
.scalar_subquery(),
|
||||
type_=ARRAY(PGUUID(as_uuid=True)),
|
||||
).label("attachment_ids")
|
||||
|
||||
|
||||
def chat_of(row: RowMapping) -> Chat:
|
||||
return Chat(
|
||||
chat_id=row["id"],
|
||||
title=ChatTitle(row["title"]),
|
||||
member_ids=row["member_ids"],
|
||||
created_at=row["created_at"],
|
||||
last_message_at=row.get("last_message_at"),
|
||||
)
|
||||
|
||||
|
||||
def message_of(row: Record) -> Message:
|
||||
def message_of(row: RowMapping) -> Message:
|
||||
return Message(
|
||||
id=row["id"],
|
||||
chat_id=row["chat_id"],
|
||||
sender_id=row["sender_id"],
|
||||
text=MessageText(row["text"]),
|
||||
created_at=row["created_at"],
|
||||
attachment_ids=tuple(row["attachment_ids"]),
|
||||
created_at=row["created_at"],
|
||||
)
|
||||
|
||||
|
||||
@@ -125,54 +269,110 @@ def page[ItemT](rows: Sequence[ItemT], limit: int) -> tuple[list[ItemT], bool]:
|
||||
|
||||
|
||||
class PostgresChatRepository:
|
||||
__slots__ = ("_connection", "_seen")
|
||||
__slots__ = ("_seen", "_session")
|
||||
|
||||
def __init__(self, connection: Connection, seen: list[EventSource]) -> None:
|
||||
self._connection = connection
|
||||
def __init__(self, session: DatabaseSession, seen: list[EventSource]) -> None:
|
||||
self._session = session
|
||||
self._seen = seen
|
||||
|
||||
async def add(self, chat: Chat) -> None:
|
||||
await self._connection.execute(INSERT_CHAT, chat.id, chat.title.value, chat.created_at)
|
||||
await self._session.execute(
|
||||
insert(ChatRow).values(id=chat.id, title=chat.title.value, created_at=chat.created_at)
|
||||
)
|
||||
try:
|
||||
await self._connection.execute(
|
||||
INSERT_MEMBERS, chat.id, list(chat.member_ids), chat.created_at
|
||||
await self._session.execute(
|
||||
insert(ChatMemberRow),
|
||||
[
|
||||
{
|
||||
"chat_id": chat.id,
|
||||
"user_id": member_id,
|
||||
"position": position,
|
||||
"chat_created_at": chat.created_at,
|
||||
}
|
||||
for position, member_id in enumerate(chat.member_ids, 1)
|
||||
],
|
||||
)
|
||||
except ForeignKeyViolationError as error:
|
||||
except IntegrityError as error:
|
||||
if getattr(error.orig, "sqlstate", None) != FOREIGN_KEY_VIOLATED:
|
||||
raise
|
||||
raise InvalidChatData("поле member_ids содержит неизвестного пользователя") from error
|
||||
self._seen.append(chat)
|
||||
|
||||
async def get(self, chat_id: UUID) -> Chat | None:
|
||||
row = await self._connection.fetchrow(LOCK_CHAT, chat_id)
|
||||
if row is None:
|
||||
return None
|
||||
chat = chat_of(row)
|
||||
self._seen.append(chat)
|
||||
return chat
|
||||
|
||||
async def receipt(
|
||||
self, chat_id: UUID, sender_id: UUID, key: str, since: datetime
|
||||
class PostgresMessageLog:
|
||||
__slots__ = ("_attachments", "_database")
|
||||
|
||||
def __init__(self, database: Database, attachments: AttachmentStates) -> None:
|
||||
self._database = database
|
||||
self._attachments = attachments
|
||||
|
||||
async def post(
|
||||
self, message: Message, key: str, fingerprint: bytes, since: datetime
|
||||
) -> Receipt | None:
|
||||
row = await self._connection.fetchrow(RECEIPT, chat_id, sender_id, key, since)
|
||||
return None if row is None else Receipt(key, row["fingerprint"], message_of(row))
|
||||
|
||||
async def append(self, receipt: Receipt) -> None:
|
||||
message = receipt.message
|
||||
try:
|
||||
await self._connection.execute(
|
||||
APPEND_MESSAGE,
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
message.text.value,
|
||||
message.created_at,
|
||||
receipt.key,
|
||||
receipt.fingerprint,
|
||||
list(message.attachment_ids),
|
||||
chat_id, sender_id = message.chat_id, message.sender_id
|
||||
async with self._database.session() as session:
|
||||
try:
|
||||
row = (
|
||||
(
|
||||
await session.execute(
|
||||
POST_MESSAGE,
|
||||
{
|
||||
"message_id": message.id,
|
||||
"chat_id": chat_id,
|
||||
"sender_id": sender_id,
|
||||
"text": message.text.value,
|
||||
"stamp": message.created_at,
|
||||
"key": key,
|
||||
"fingerprint": fingerprint,
|
||||
"since": since,
|
||||
"attachment_ids": list(message.attachment_ids),
|
||||
},
|
||||
)
|
||||
)
|
||||
.mappings()
|
||||
.first()
|
||||
)
|
||||
except IntegrityError as error:
|
||||
cause = getattr(error.orig, "__cause__", None)
|
||||
if getattr(cause, "constraint_name", None) != "message_attachments_attachment_fkey":
|
||||
raise
|
||||
raise UnknownAttachment("вложение не найдено в этом чате") from error
|
||||
if row is None or not row["member"]:
|
||||
return None
|
||||
if row["created_at"] is not None:
|
||||
if message.attachment_ids and await self._attachments.unusable(
|
||||
chat_id, message.attachment_ids
|
||||
):
|
||||
raise AttachmentUnavailable("вложение не обработано и не может быть отправлено")
|
||||
await session.commit()
|
||||
return Receipt(key, fingerprint, replace(message, created_at=row["created_at"]))
|
||||
known = (
|
||||
(
|
||||
await session.execute(
|
||||
select(
|
||||
IdempotencyKeyRow.fingerprint,
|
||||
MessageRow.id,
|
||||
MessageRow.chat_id,
|
||||
MessageRow.sender_id,
|
||||
MessageRow.text,
|
||||
MessageRow.created_at,
|
||||
attachment_ids(),
|
||||
)
|
||||
.join(MessageRow, MessageRow.id == IdempotencyKeyRow.message_id)
|
||||
.where(
|
||||
IdempotencyKeyRow.chat_id == chat_id,
|
||||
IdempotencyKeyRow.user_id == sender_id,
|
||||
IdempotencyKeyRow.key == key,
|
||||
IdempotencyKeyRow.created_at > since,
|
||||
)
|
||||
)
|
||||
)
|
||||
.mappings()
|
||||
.first()
|
||||
)
|
||||
except ForeignKeyViolationError as error:
|
||||
if getattr(error, "constraint_name", None) != ATTACHMENT_FKEY:
|
||||
raise
|
||||
raise UnknownAttachment("вложение не найдено в этом чате") from error
|
||||
if known is None:
|
||||
raise Unavailable("ключ идемпотентности занят незавершённой записью")
|
||||
return Receipt(key, known["fingerprint"], message_of(known))
|
||||
|
||||
|
||||
class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
|
||||
@@ -180,7 +380,7 @@ class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
|
||||
|
||||
@property
|
||||
def chats(self) -> PostgresChatRepository:
|
||||
return PostgresChatRepository(self.connection, self.seen)
|
||||
return PostgresChatRepository(self.session, self.seen)
|
||||
|
||||
|
||||
class PostgresChatDirectory:
|
||||
@@ -190,30 +390,62 @@ class PostgresChatDirectory:
|
||||
self._database = database
|
||||
|
||||
async def chat_for_member(self, chat_id: UUID, user_id: UUID) -> Chat | None:
|
||||
async with self._database.connection() as connection:
|
||||
row = await connection.fetchrow(CHAT_OF_MEMBER, chat_id, user_id)
|
||||
async with self._database.session() as session:
|
||||
row = (
|
||||
(
|
||||
await session.execute(
|
||||
select(ChatRow.id, ChatRow.title, ChatRow.created_at, member_ids())
|
||||
.select_from(ChatMemberRow)
|
||||
.join(ChatRow, ChatRow.id == ChatMemberRow.chat_id)
|
||||
.where(ChatMemberRow.chat_id == chat_id, ChatMemberRow.user_id == user_id)
|
||||
)
|
||||
)
|
||||
.mappings()
|
||||
.first()
|
||||
)
|
||||
return None if row is None else chat_of(row)
|
||||
|
||||
async def chats_of(
|
||||
self, user_id: UUID, *, after: HistoryKey | None, limit: int
|
||||
) -> tuple[list[Chat], bool]:
|
||||
async with self._database.connection() as connection:
|
||||
if after is None:
|
||||
rows = await connection.fetch(CHATS_FIRST, user_id, limit + 1)
|
||||
else:
|
||||
rows = await connection.fetch(
|
||||
CHATS_AFTER, user_id, after[0], UUID(int=after[1]), limit + 1
|
||||
)
|
||||
statement = (
|
||||
select(ChatRow.id, ChatRow.title, ChatRow.created_at, member_ids())
|
||||
.select_from(ChatMemberRow)
|
||||
.join(ChatRow, ChatRow.id == ChatMemberRow.chat_id)
|
||||
.where(ChatMemberRow.user_id == user_id)
|
||||
.order_by(ChatMemberRow.chat_created_at, ChatMemberRow.chat_id)
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if after is not None:
|
||||
statement = statement.where(
|
||||
tuple_(ChatMemberRow.chat_created_at, ChatMemberRow.chat_id)
|
||||
> tuple_(literal(after[0]), literal(UUID(int=after[1])))
|
||||
)
|
||||
async with self._database.session() as session:
|
||||
rows = (await session.execute(statement)).mappings().all()
|
||||
return page([chat_of(row) for row in rows], limit)
|
||||
|
||||
async def history(
|
||||
self, chat_id: UUID, *, after: HistoryKey | None, limit: int
|
||||
) -> tuple[list[Message], bool]:
|
||||
async with self._database.connection() as connection:
|
||||
if after is None:
|
||||
rows = await connection.fetch(HISTORY_FIRST, chat_id, limit + 1)
|
||||
else:
|
||||
rows = await connection.fetch(
|
||||
HISTORY_AFTER, chat_id, after[0], UUID(int=after[1]), limit + 1
|
||||
)
|
||||
statement = (
|
||||
select(
|
||||
MessageRow.id,
|
||||
MessageRow.chat_id,
|
||||
MessageRow.sender_id,
|
||||
MessageRow.text,
|
||||
MessageRow.created_at,
|
||||
attachment_ids(),
|
||||
)
|
||||
.where(MessageRow.chat_id == chat_id)
|
||||
.order_by(MessageRow.created_at, MessageRow.id)
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if after is not None:
|
||||
statement = statement.where(
|
||||
tuple_(MessageRow.created_at, MessageRow.id)
|
||||
> tuple_(literal(after[0]), literal(UUID(int=after[1])))
|
||||
)
|
||||
async with self._database.session() as session:
|
||||
rows = (await session.execute(statement)).mappings().all()
|
||||
return page([message_of(row) for row in rows], limit)
|
||||
|
||||
Reference in New Issue
Block a user