Carry over the lab 3 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack, HAProxy and k6 configuration, migrations, hooks, evidence and level 4 scripts and the CI job from the lab 3 solution commit 61c0c28, merge the lab 3 Makefile targets into the lab 4 skeleton Makefile without touching its targets, and append the lab 3 solution variables to the skeleton .env.example. The package and the application follow the contract version 1.4.0, and the image and the throwaway test containers are tagged lab4 so they do not collide with a lab 3 stand on the same host. This is the starting point of the lab 4 cycle: lint, own tests and the offline skeleton check pass before any lab 4 change. 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
b0f463ac5c
commit
bf8e4e3cd1
@@ -0,0 +1,201 @@
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import ForeignKeyViolationError, Record
|
||||
|
||||
from messenger.messaging.domain.errors import InvalidChatData
|
||||
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.infrastructure.postgres import (
|
||||
Connection,
|
||||
Database,
|
||||
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
|
||||
"""
|
||||
RECEIPT = """
|
||||
SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
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
|
||||
), 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 id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2
|
||||
"""
|
||||
HISTORY_AFTER = """
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4
|
||||
"""
|
||||
|
||||
|
||||
def chat_of(row: Record) -> 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:
|
||||
return Message(
|
||||
id=row["id"],
|
||||
chat_id=row["chat_id"],
|
||||
sender_id=row["sender_id"],
|
||||
text=MessageText(row["text"]),
|
||||
created_at=row["created_at"],
|
||||
)
|
||||
|
||||
|
||||
def page[ItemT](rows: Sequence[ItemT], limit: int) -> tuple[list[ItemT], bool]:
|
||||
return list(rows[:limit]), len(rows) > limit
|
||||
|
||||
|
||||
class PostgresChatRepository:
|
||||
__slots__ = ("_connection", "_seen")
|
||||
|
||||
def __init__(self, connection: Connection, seen: list[EventSource]) -> None:
|
||||
self._connection = connection
|
||||
self._seen = seen
|
||||
|
||||
async def add(self, chat: Chat) -> None:
|
||||
await self._connection.execute(INSERT_CHAT, chat.id, chat.title.value, chat.created_at)
|
||||
try:
|
||||
await self._connection.execute(
|
||||
INSERT_MEMBERS, chat.id, list(chat.member_ids), chat.created_at
|
||||
)
|
||||
except ForeignKeyViolationError as error:
|
||||
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
|
||||
) -> 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
|
||||
await self._connection.execute(
|
||||
APPEND_MESSAGE,
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
message.text.value,
|
||||
message.created_at,
|
||||
receipt.key,
|
||||
receipt.fingerprint,
|
||||
)
|
||||
|
||||
|
||||
class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def chats(self) -> PostgresChatRepository:
|
||||
return PostgresChatRepository(self.connection, self.seen)
|
||||
|
||||
|
||||
class PostgresChatDirectory:
|
||||
__slots__ = ("_database",)
|
||||
|
||||
def __init__(self, database: Database) -> None:
|
||||
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)
|
||||
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
|
||||
)
|
||||
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
|
||||
)
|
||||
return page([message_of(row) for row in rows], limit)
|
||||
Reference in New Issue
Block a user