Adopt async SQLAlchemy storage and verified Alembic migrations
Keep the message and idempotency receipt in one Core CTE statement with chat-first locking. Preserve rollback, bounded dependency failures, and domain ports. Replace the SQL runner with Alembic. Adopt legacy databases only after validating their journal and PostgreSQL schema, retain all data, and verify migrations on fresh and populated databases.
This commit is contained in:
@@ -1,85 +1,126 @@
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import Record
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
LargeBinary,
|
||||
UniqueConstraint,
|
||||
delete,
|
||||
literal,
|
||||
select,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from messenger.identity.domain.errors import UsernameAlreadyTaken
|
||||
from messenger.identity.domain.models import Session, User
|
||||
from messenger.identity.domain.values import DisplayName, Username
|
||||
from messenger.shared.infrastructure.postgres import Connection, Database, PostgresUnitOfWork
|
||||
|
||||
INSERT_USER = """
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (username) DO NOTHING
|
||||
RETURNING true
|
||||
"""
|
||||
USER_BY_ID = """
|
||||
SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1
|
||||
"""
|
||||
USER_BY_USERNAME = """
|
||||
SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1
|
||||
"""
|
||||
INSERT_SESSION = """
|
||||
WITH expired AS (DELETE FROM sessions WHERE user_id = $2 AND expires_at <= $3)
|
||||
INSERT INTO sessions (token_hash, user_id, created_at, expires_at) VALUES ($1, $2, $3, $4)
|
||||
"""
|
||||
DELETE_SESSION = "DELETE FROM sessions WHERE token_hash = $1"
|
||||
ACTIVE_SESSION = """
|
||||
SELECT token_hash, user_id, created_at, expires_at
|
||||
FROM sessions
|
||||
WHERE token_hash = $1 AND expires_at > $2
|
||||
"""
|
||||
from messenger.shared.infrastructure.postgres import (
|
||||
Base,
|
||||
Database,
|
||||
DatabaseSession,
|
||||
PostgresUnitOfWork,
|
||||
)
|
||||
|
||||
|
||||
def user_of(row: Record | None) -> User | None:
|
||||
class UserRow(Base):
|
||||
__tablename__ = "users"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("username", name="users_username_key"),
|
||||
CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'", name="users_username_format"),
|
||||
CheckConstraint(
|
||||
"char_length(display_name) BETWEEN 1 AND 100", name="users_display_name_check"
|
||||
),
|
||||
CheckConstraint("password_hash LIKE '$argon2id$%'", name="users_password_hash_check"),
|
||||
)
|
||||
|
||||
id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
username: Mapped[str]
|
||||
display_name: Mapped[str]
|
||||
password_hash: Mapped[str]
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class SessionRow(Base):
|
||||
__tablename__ = "sessions"
|
||||
__table_args__ = (
|
||||
CheckConstraint("octet_length(token_hash) = 32", name="sessions_token_hash_check"),
|
||||
CheckConstraint("expires_at > created_at", name="sessions_check"),
|
||||
Index("sessions_user_idx", "user_id"),
|
||||
)
|
||||
|
||||
token_hash: Mapped[bytes] = mapped_column(LargeBinary, primary_key=True)
|
||||
user_id: Mapped[UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
def user_of(row: UserRow | None) -> User | None:
|
||||
if row is None:
|
||||
return None
|
||||
return User(
|
||||
id=row["id"],
|
||||
username=Username(row["username"]),
|
||||
display_name=DisplayName(row["display_name"]),
|
||||
created_at=row["created_at"],
|
||||
password_hash=row["password_hash"],
|
||||
id=row.id,
|
||||
username=Username(row.username),
|
||||
display_name=DisplayName(row.display_name),
|
||||
created_at=row.created_at,
|
||||
password_hash=row.password_hash,
|
||||
)
|
||||
|
||||
|
||||
class PostgresUserRepository:
|
||||
__slots__ = ("_connection",)
|
||||
__slots__ = ("_session",)
|
||||
|
||||
def __init__(self, connection: Connection) -> None:
|
||||
self._connection = connection
|
||||
def __init__(self, session: DatabaseSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def add(self, user: User) -> None:
|
||||
inserted = await self._connection.fetchval(
|
||||
INSERT_USER,
|
||||
user.id,
|
||||
user.username.value,
|
||||
user.display_name.value,
|
||||
user.password_hash,
|
||||
user.created_at,
|
||||
statement = (
|
||||
insert(UserRow)
|
||||
.values(
|
||||
id=user.id,
|
||||
username=user.username.value,
|
||||
display_name=user.display_name.value,
|
||||
password_hash=user.password_hash,
|
||||
created_at=user.created_at,
|
||||
)
|
||||
.on_conflict_do_nothing(index_elements=["username"])
|
||||
.returning(literal(True))
|
||||
)
|
||||
inserted = (await self._session.execute(statement)).scalar_one_or_none()
|
||||
if inserted is None:
|
||||
raise UsernameAlreadyTaken("username уже занят")
|
||||
|
||||
|
||||
class PostgresSessionRepository:
|
||||
__slots__ = ("_connection",)
|
||||
__slots__ = ("_session",)
|
||||
|
||||
def __init__(self, connection: Connection) -> None:
|
||||
self._connection = connection
|
||||
def __init__(self, session: DatabaseSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def add(self, session: Session) -> None:
|
||||
await self._connection.execute(
|
||||
INSERT_SESSION,
|
||||
session.token_hash,
|
||||
session.user_id,
|
||||
session.created_at,
|
||||
session.expires_at,
|
||||
expired = (
|
||||
delete(SessionRow)
|
||||
.where(
|
||||
SessionRow.user_id == session.user_id, SessionRow.expires_at <= session.created_at
|
||||
)
|
||||
.cte("expired")
|
||||
)
|
||||
await self._session.execute(
|
||||
insert(SessionRow)
|
||||
.values(
|
||||
token_hash=session.token_hash,
|
||||
user_id=session.user_id,
|
||||
created_at=session.created_at,
|
||||
expires_at=session.expires_at,
|
||||
)
|
||||
.add_cte(expired)
|
||||
)
|
||||
|
||||
async def remove(self, token_hash: bytes) -> None:
|
||||
await self._connection.execute(DELETE_SESSION, token_hash)
|
||||
await self._session.execute(delete(SessionRow).where(SessionRow.token_hash == token_hash))
|
||||
|
||||
|
||||
class PostgresIdentityUnitOfWork(PostgresUnitOfWork):
|
||||
@@ -87,11 +128,11 @@ class PostgresIdentityUnitOfWork(PostgresUnitOfWork):
|
||||
|
||||
@property
|
||||
def users(self) -> PostgresUserRepository:
|
||||
return PostgresUserRepository(self.connection)
|
||||
return PostgresUserRepository(self.session)
|
||||
|
||||
@property
|
||||
def sessions(self) -> PostgresSessionRepository:
|
||||
return PostgresSessionRepository(self.connection)
|
||||
return PostgresSessionRepository(self.session)
|
||||
|
||||
|
||||
class PostgresUserDirectory:
|
||||
@@ -101,12 +142,18 @@ class PostgresUserDirectory:
|
||||
self._database = database
|
||||
|
||||
async def find(self, user_id: UUID) -> User | None:
|
||||
async with self._database.connection() as connection:
|
||||
return user_of(await connection.fetchrow(USER_BY_ID, user_id))
|
||||
async with self._database.session() as session:
|
||||
row = (
|
||||
await session.execute(select(UserRow).where(UserRow.id == user_id))
|
||||
).scalar_one_or_none()
|
||||
return user_of(row)
|
||||
|
||||
async def find_by_username(self, username: str) -> User | None:
|
||||
async with self._database.connection() as connection:
|
||||
return user_of(await connection.fetchrow(USER_BY_USERNAME, username))
|
||||
async with self._database.session() as session:
|
||||
row = (
|
||||
await session.execute(select(UserRow).where(UserRow.username == username))
|
||||
).scalar_one_or_none()
|
||||
return user_of(row)
|
||||
|
||||
|
||||
class PostgresSessionDirectory:
|
||||
@@ -116,6 +163,20 @@ class PostgresSessionDirectory:
|
||||
self._database = database
|
||||
|
||||
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
|
||||
async with self._database.connection() as connection:
|
||||
row = await connection.fetchrow(ACTIVE_SESSION, token_hash, now)
|
||||
return None if row is None else Session(**dict(row))
|
||||
async with self._database.session() as session:
|
||||
row = (
|
||||
await session.execute(
|
||||
select(SessionRow).where(
|
||||
SessionRow.token_hash == token_hash,
|
||||
SessionRow.expires_at > now,
|
||||
)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
return Session(
|
||||
token_hash=row.token_hash,
|
||||
user_id=row.user_id,
|
||||
created_at=row.created_at,
|
||||
expires_at=row.expires_at,
|
||||
)
|
||||
|
||||
@@ -1,9 +1,34 @@
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import replace
|
||||
from datetime import datetime
|
||||
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,
|
||||
bindparam,
|
||||
func,
|
||||
insert,
|
||||
literal,
|
||||
select,
|
||||
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
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
@@ -11,86 +36,158 @@ 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)
|
||||
"""
|
||||
POST_MESSAGE = """
|
||||
WITH chat AS (
|
||||
SELECT c.id, GREATEST($5::timestamptz, c.last_message_at + interval '1 microsecond') AS stamp
|
||||
FROM chats c JOIN chat_members m ON m.chat_id = c.id AND m.user_id = $3
|
||||
WHERE c.id = $2
|
||||
FOR UPDATE OF c
|
||||
), receipt AS (
|
||||
INSERT INTO idempotency_keys (chat_id, user_id, key, fingerprint, message_id, created_at)
|
||||
SELECT id, $3, $6, $7, $1, stamp FROM chat
|
||||
ON CONFLICT (chat_id, user_id, key) DO UPDATE
|
||||
SET fingerprint = EXCLUDED.fingerprint,
|
||||
message_id = EXCLUDED.message_id,
|
||||
created_at = EXCLUDED.created_at
|
||||
WHERE idempotency_keys.created_at <= $8
|
||||
RETURNING created_at
|
||||
), message AS (
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT $1, $2, $3, $4, created_at FROM receipt
|
||||
RETURNING created_at
|
||||
), touched AS (
|
||||
UPDATE chats SET last_message_at = message.created_at FROM message WHERE chats.id = $2
|
||||
)
|
||||
SELECT EXISTS (SELECT FROM chat) AS member, (SELECT created_at FROM message) AS created_at
|
||||
"""
|
||||
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
|
||||
"""
|
||||
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
|
||||
"""
|
||||
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) BETWEEN 1 AND 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))
|
||||
|
||||
|
||||
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")
|
||||
)
|
||||
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(touched)
|
||||
|
||||
|
||||
POST_MESSAGE = post_message()
|
||||
|
||||
|
||||
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 chat_of(row: RowMapping) -> Chat:
|
||||
return Chat(
|
||||
chat_id=row["id"],
|
||||
title=ChatTitle(row["title"]),
|
||||
@@ -99,7 +196,7 @@ def chat_of(row: Record) -> Chat:
|
||||
)
|
||||
|
||||
|
||||
def message_of(row: Record) -> Message:
|
||||
def message_of(row: RowMapping) -> Message:
|
||||
return Message(
|
||||
id=row["id"],
|
||||
chat_id=row["chat_id"],
|
||||
@@ -114,19 +211,32 @@ 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)
|
||||
|
||||
@@ -141,23 +251,54 @@ class PostgresMessageLog:
|
||||
self, message: Message, key: str, fingerprint: bytes, since: datetime
|
||||
) -> Receipt | None:
|
||||
chat_id, sender_id = message.chat_id, message.sender_id
|
||||
async with self._database.connection() as connection:
|
||||
row = await connection.fetchrow(
|
||||
POST_MESSAGE,
|
||||
message.id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
message.text.value,
|
||||
message.created_at,
|
||||
key,
|
||||
fingerprint,
|
||||
since,
|
||||
async with self._database.session() as session:
|
||||
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,
|
||||
},
|
||||
)
|
||||
)
|
||||
.mappings()
|
||||
.first()
|
||||
)
|
||||
if row is None or not row["member"]:
|
||||
return None
|
||||
if row["created_at"] is not None:
|
||||
await session.commit()
|
||||
return Receipt(key, fingerprint, replace(message, created_at=row["created_at"]))
|
||||
known = await connection.fetchrow(RECEIPT, chat_id, sender_id, key, since)
|
||||
known = (
|
||||
(
|
||||
await session.execute(
|
||||
select(
|
||||
IdempotencyKeyRow.fingerprint,
|
||||
MessageRow.id,
|
||||
MessageRow.chat_id,
|
||||
MessageRow.sender_id,
|
||||
MessageRow.text,
|
||||
MessageRow.created_at,
|
||||
)
|
||||
.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()
|
||||
)
|
||||
if known is None:
|
||||
raise Unavailable("ключ идемпотентности занят незавершённой записью")
|
||||
return Receipt(key, known["fingerprint"], message_of(known))
|
||||
@@ -168,7 +309,7 @@ class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
|
||||
|
||||
@property
|
||||
def chats(self) -> PostgresChatRepository:
|
||||
return PostgresChatRepository(self.connection, self.seen)
|
||||
return PostgresChatRepository(self.session, self.seen)
|
||||
|
||||
|
||||
class PostgresChatDirectory:
|
||||
@@ -178,30 +319,61 @@ 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,
|
||||
)
|
||||
.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)
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
from importlib import resources
|
||||
|
||||
import asyncpg
|
||||
|
||||
from messenger.shared.config import PlatformSettings
|
||||
from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger
|
||||
|
||||
LOCK_KEY = 20_260_002
|
||||
JOURNAL = """
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
checksum text NOT NULL,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
class MigrationChangedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def migrations() -> list[tuple[str, str]]:
|
||||
folder = resources.files("messenger") / "migrations"
|
||||
found = (item for item in folder.iterdir() if item.name.endswith(".sql"))
|
||||
return sorted((item.name.removesuffix(".sql"), item.read_text()) for item in found)
|
||||
|
||||
|
||||
async def migrate(dsn: str) -> list[str]:
|
||||
connection = await asyncpg.connect(dsn, timeout=10)
|
||||
try:
|
||||
await connection.execute("SELECT pg_advisory_lock($1)", LOCK_KEY)
|
||||
await connection.execute(JOURNAL)
|
||||
applied = dict(await connection.fetch("SELECT version, checksum FROM schema_migrations"))
|
||||
done: list[str] = []
|
||||
for version, sql in migrations():
|
||||
checksum = hashlib.sha256(sql.encode()).hexdigest()
|
||||
if version in applied:
|
||||
if applied[version] != checksum:
|
||||
raise MigrationChangedError(version)
|
||||
continue
|
||||
async with connection.transaction():
|
||||
await connection.execute(sql)
|
||||
await connection.execute(
|
||||
"INSERT INTO schema_migrations (version, checksum) VALUES ($1, $2)",
|
||||
version,
|
||||
checksum,
|
||||
)
|
||||
done.append(version)
|
||||
return done
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
settings = PlatformSettings()
|
||||
logger = StructlogLogger(level=settings.log_level, allowed_fields=PLATFORM_FIELDS | {"version"})
|
||||
try:
|
||||
done = asyncio.run(migrate(settings.database_url.get_secret_value()))
|
||||
except MigrationChangedError as error:
|
||||
logger.error("migration.changed", version=str(error))
|
||||
raise SystemExit(1) from None
|
||||
for version in done:
|
||||
logger.info("migration.applied", version=version)
|
||||
logger.info("migration.completed", reason="up to date" if not done else "applied")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,46 +0,0 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL CONSTRAINT users_username_key UNIQUE
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash text NOT NULL CHECK (password_hash LIKE '$argon2id$%'),
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32),
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
CHECK (expires_at > created_at)
|
||||
);
|
||||
|
||||
CREATE INDEX sessions_user_idx ON sessions (user_id);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at timestamptz NOT NULL,
|
||||
last_message_at timestamptz
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position smallint NOT NULL CHECK (position BETWEEN 1 AND 100),
|
||||
chat_created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_created_at, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
created_at timestamptz NOT NULL,
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
|
||||
@@ -1,10 +0,0 @@
|
||||
CREATE TABLE idempotency_keys (
|
||||
chat_id uuid NOT NULL,
|
||||
user_id uuid NOT NULL,
|
||||
key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
fingerprint bytea NOT NULL CHECK (octet_length(fingerprint) = 32),
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id, key),
|
||||
FOREIGN KEY (chat_id, user_id) REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
@@ -1,32 +1,45 @@
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any, Protocol
|
||||
from typing import ClassVar, Protocol
|
||||
|
||||
import asyncpg
|
||||
from sqlalchemy import Text, make_url, select
|
||||
from sqlalchemy.exc import DBAPIError, IntegrityError, InterfaceError, OperationalError
|
||||
from sqlalchemy.exc import TimeoutError as PoolTimeout
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
FAILURES = (
|
||||
OSError,
|
||||
asyncpg.InterfaceError,
|
||||
asyncpg.PostgresConnectionError,
|
||||
asyncpg.exceptions.OperatorInterventionError,
|
||||
asyncpg.exceptions.InsufficientResourcesError,
|
||||
asyncpg.exceptions.LockNotAvailableError,
|
||||
)
|
||||
FAILURES = (OSError, InterfaceError, OperationalError, PoolTimeout, TimeoutError)
|
||||
|
||||
PING_TIMEOUT_SECONDS = 0.4
|
||||
|
||||
type Connection = asyncpg.Connection
|
||||
type DatabaseSession = AsyncSession
|
||||
|
||||
|
||||
class EventSource(Protocol):
|
||||
def collect_events(self) -> list[DomainEvent]: ...
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
type_annotation_map: ClassVar = {str: Text}
|
||||
|
||||
|
||||
def unavailable(error: BaseException) -> bool:
|
||||
if isinstance(error, IntegrityError):
|
||||
return False
|
||||
if isinstance(error, FAILURES):
|
||||
return True
|
||||
if isinstance(error, DBAPIError) and error.connection_invalidated:
|
||||
return True
|
||||
state = getattr(error.orig if isinstance(error, DBAPIError) else error, "sqlstate", None)
|
||||
return isinstance(state, str) and (state.startswith(("08", "53", "57")) or state == "55P03")
|
||||
|
||||
|
||||
class Database:
|
||||
__slots__ = ("_acquire_timeout", "_pool")
|
||||
__slots__ = ("_engine", "_sessions")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -37,75 +50,81 @@ class Database:
|
||||
acquire_timeout: float,
|
||||
command_timeout: float,
|
||||
) -> None:
|
||||
self._acquire_timeout = acquire_timeout
|
||||
self._pool = asyncpg.create_pool(
|
||||
dsn,
|
||||
min_size=0,
|
||||
max_size=max_size,
|
||||
timeout=connect_timeout,
|
||||
command_timeout=command_timeout,
|
||||
max_inactive_connection_lifetime=60,
|
||||
server_settings={
|
||||
"statement_timeout": str(int(command_timeout * 1000)),
|
||||
"lock_timeout": str(int(command_timeout * 1000)),
|
||||
"idle_in_transaction_session_timeout": "10000",
|
||||
self._engine = create_async_engine(
|
||||
make_url(dsn).set(drivername="postgresql+asyncpg"),
|
||||
pool_size=max_size,
|
||||
max_overflow=0,
|
||||
pool_timeout=acquire_timeout,
|
||||
pool_recycle=60,
|
||||
hide_parameters=True,
|
||||
connect_args={
|
||||
"timeout": connect_timeout,
|
||||
"command_timeout": command_timeout,
|
||||
"server_settings": {
|
||||
"statement_timeout": str(int(command_timeout * 1000)),
|
||||
"lock_timeout": str(int(command_timeout * 1000)),
|
||||
"idle_in_transaction_session_timeout": "10000",
|
||||
},
|
||||
},
|
||||
)
|
||||
self._sessions = async_sessionmaker(self._engine, expire_on_commit=False)
|
||||
|
||||
async def open(self) -> None:
|
||||
await self._pool
|
||||
pass
|
||||
|
||||
async def close(self) -> None:
|
||||
await self._pool.close()
|
||||
await self._engine.dispose()
|
||||
|
||||
@asynccontextmanager
|
||||
async def connection(self, wait: float | None = None) -> AsyncIterator[Connection]:
|
||||
async def session(self) -> AsyncIterator[DatabaseSession]:
|
||||
try:
|
||||
async with self._pool.acquire(timeout=wait or self._acquire_timeout) as connection:
|
||||
yield connection
|
||||
except FAILURES as error:
|
||||
async with self._sessions() as session:
|
||||
yield session
|
||||
except Exception as error:
|
||||
if not unavailable(error):
|
||||
raise
|
||||
raise Unavailable("PostgreSQL недоступен") from error
|
||||
|
||||
async def ping(self) -> None:
|
||||
async with self.connection(PING_TIMEOUT_SECONDS) as connection:
|
||||
await connection.fetchval("SELECT 1", timeout=PING_TIMEOUT_SECONDS)
|
||||
try:
|
||||
async with asyncio.timeout(PING_TIMEOUT_SECONDS):
|
||||
async with self.session() as session:
|
||||
await session.execute(select(1))
|
||||
except TimeoutError as error:
|
||||
raise Unavailable("PostgreSQL недоступен") from error
|
||||
|
||||
|
||||
class PostgresUnitOfWork:
|
||||
__slots__ = ("_committed", "_connection", "_database", "_events", "_transaction", "seen")
|
||||
__slots__ = ("_committed", "_database", "_events", "_session", "seen")
|
||||
|
||||
def __init__(self, database: Database) -> None:
|
||||
self._database = database
|
||||
self._connection: Connection | None = None
|
||||
self._transaction: Any = None
|
||||
self._session: DatabaseSession | None = None
|
||||
self._committed = False
|
||||
self._events: list[DomainEvent] = []
|
||||
self.seen: list[EventSource] = []
|
||||
|
||||
@property
|
||||
def connection(self) -> Connection:
|
||||
if self._connection is None:
|
||||
def session(self) -> DatabaseSession:
|
||||
if self._session is None:
|
||||
raise RuntimeError("репозиторий используется вне транзакции")
|
||||
return self._connection
|
||||
return self._session
|
||||
|
||||
@asynccontextmanager
|
||||
async def transaction(self) -> AsyncIterator[None]:
|
||||
async with self._database.connection() as connection:
|
||||
self._connection = connection
|
||||
self._transaction = connection.transaction()
|
||||
await self._transaction.start()
|
||||
async with self._database.session() as session:
|
||||
self._session = session
|
||||
self._committed = False
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if not self._committed:
|
||||
self._events.clear()
|
||||
await self._transaction.rollback()
|
||||
self.seen.clear()
|
||||
self._connection = None
|
||||
self._session = None
|
||||
|
||||
async def commit(self) -> None:
|
||||
await self._transaction.commit()
|
||||
await self.session.commit()
|
||||
self._committed = True
|
||||
for source in self.seen:
|
||||
self._events.extend(source.collect_events())
|
||||
|
||||
Reference in New Issue
Block a user