Forward-port lab3 SQLAlchemy and Alembic foundation

Carry source f591fa64e525679a31c9db7f942d36c789e1a12f forward from 72a1e57. Preserve lab4 attachment transactions, reconciliation locks, quarantine, and existing schema data through verified legacy adoption. Keep report and evidence work in progress untouched.
This commit is contained in:
Artyom
2026-11-06 01:47:30 +03:00
parent dd4021b678
commit 8e4532f6f5
54 changed files with 3459 additions and 617 deletions
@@ -3,50 +3,96 @@ from contextlib import asynccontextmanager
from datetime import datetime
from uuid import UUID
from asyncpg import ForeignKeyViolationError, Record
from sqlalchemy import (
BigInteger,
CheckConstraint,
DateTime,
ForeignKeyConstraint,
Index,
Integer,
RowMapping,
Select,
Text,
UniqueConstraint,
delete,
func,
insert,
select,
update,
)
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Mapped, mapped_column
from messenger.attachments.domain.errors import ChatNotFound
from messenger.attachments.domain.models import Attachment, AttachmentStatus, Quarantine
from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind
from messenger.shared.application.errors import Unavailable
from messenger.shared.infrastructure.postgres import (
Connection,
Base,
Database,
DatabaseSession,
EventSource,
PostgresUnitOfWork,
)
INSERT = """
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
width, height, object_key, status, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
"""
MARK = "UPDATE attachments SET status = $2, updated_at = $3 WHERE id = $1 AND status = 'pending'"
COLUMNS = """
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height,
object_key, status, created_at, updated_at, quarantine_reason
FROM attachments
"""
READY = COLUMNS + "WHERE id = $1 AND status = 'ready'"
LOCK = COLUMNS + "WHERE id = $1 FOR UPDATE"
ABANDONED = (
COLUMNS
+ """WHERE status = 'pending' AND created_at < $1
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED"""
class AttachmentRow(Base):
__tablename__ = "attachments"
__table_args__ = (
CheckConstraint(
"char_length(filename) BETWEEN 1 AND 255", name="attachments_filename_check"
),
CheckConstraint(
"content_type IN ('image/png', 'image/jpeg')", name="attachments_content_type_check"
),
CheckConstraint("size_bytes BETWEEN 1 AND 10485760", name="attachments_size_bytes_check"),
CheckConstraint("sha256 ~ '^[0-9a-f]{64}$'", name="attachments_sha256_check"),
CheckConstraint("width > 0", name="attachments_width_check"),
CheckConstraint("height > 0", name="attachments_height_check"),
CheckConstraint("status IN ('pending', 'ready')", name="attachments_status_check"),
CheckConstraint(
"quarantine_reason IN ('missing', 'size_mismatch', 'sha_mismatch')",
name="attachments_quarantine_reason_check",
),
CheckConstraint(
"(quarantine_reason IS NULL) = (quarantined_at IS NULL)",
name="attachments_quarantine_check",
),
UniqueConstraint("object_key", name="attachments_object_key_key"),
UniqueConstraint("id", "chat_id", name="attachments_chat_key"),
ForeignKeyConstraint(
["chat_id", "owner_id"],
["chat_members.chat_id", "chat_members.user_id"],
name="attachments_owner_fkey",
),
)
id: Mapped[UUID] = mapped_column(primary_key=True)
chat_id: Mapped[UUID]
owner_id: Mapped[UUID]
filename: Mapped[str]
content_type: Mapped[str]
size_bytes: Mapped[int] = mapped_column(BigInteger)
sha256: Mapped[str]
width: Mapped[int] = mapped_column(Integer)
height: Mapped[int] = mapped_column(Integer)
object_key: Mapped[str] = mapped_column(Text(collation="C"))
status: Mapped[str]
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
quarantine_reason: Mapped[str | None]
quarantined_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
Index(
"attachments_pending_idx",
AttachmentRow.created_at,
postgresql_where=AttachmentRow.status == "pending",
)
REMOVE = "DELETE FROM attachments WHERE id = $1 AND status = 'pending'"
PAGE = COLUMNS + "WHERE object_key > $1 ORDER BY object_key LIMIT $2"
BY_KEY = COLUMNS + "WHERE object_key = $1"
CLAIM = LOCK + " SKIP LOCKED"
QUARANTINE = """
UPDATE attachments
SET quarantine_reason = $2::text,
quarantined_at = CASE WHEN $2::text IS NULL THEN NULL ELSE now() END
WHERE id = $1 AND status = 'ready'
"""
COLUMNS = select(AttachmentRow.__table__)
def attachment_of(row: Record) -> Attachment:
def attachment_of(row: RowMapping) -> Attachment:
return Attachment(
id=row["id"],
chat_id=row["chat_id"],
@@ -64,68 +110,94 @@ def attachment_of(row: Record) -> Attachment:
class PostgresAttachmentRepository:
__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, attachment: Attachment) -> None:
try:
await self._connection.execute(
INSERT,
attachment.id,
attachment.chat_id,
attachment.owner_id,
attachment.filename.value,
attachment.content_type,
attachment.size_bytes,
attachment.sha256,
attachment.image.width,
attachment.image.height,
attachment.object_key,
attachment.status.value,
attachment.created_at,
attachment.updated_at,
await self._session.execute(
insert(AttachmentRow).values(
id=attachment.id,
chat_id=attachment.chat_id,
owner_id=attachment.owner_id,
filename=attachment.filename.value,
content_type=attachment.content_type,
size_bytes=attachment.size_bytes,
sha256=attachment.sha256,
width=attachment.image.width,
height=attachment.image.height,
object_key=attachment.object_key,
status=attachment.status.value,
created_at=attachment.created_at,
updated_at=attachment.updated_at,
)
)
except ForeignKeyViolationError as error:
except IntegrityError as error:
if getattr(error.orig, "sqlstate", None) != "23503":
raise
raise ChatNotFound("чат не найден") from error
self._seen.append(attachment)
async def save(self, attachment: Attachment) -> None:
done = await self._connection.execute(
MARK, attachment.id, attachment.status.value, attachment.updated_at
done = await self._session.scalar(
update(AttachmentRow)
.where(AttachmentRow.id == attachment.id, AttachmentRow.status == "pending")
.values(status=attachment.status.value, updated_at=attachment.updated_at)
.returning(AttachmentRow.id)
)
if done == "UPDATE 0":
if done is None:
raise Unavailable("намерение загрузки уже снято уборкой")
self._seen.append(attachment)
async def lock(self, attachment_id: UUID) -> Attachment | None:
row = await self._connection.fetchrow(LOCK, attachment_id)
async def _one(self, statement: Select) -> Attachment | None:
row = (await self._session.execute(statement)).mappings().first()
return None if row is None else attachment_of(row)
async def lock(self, attachment_id: UUID) -> Attachment | None:
return await self._one(COLUMNS.where(AttachmentRow.id == attachment_id).with_for_update())
async def next_abandoned(self, before: datetime) -> Attachment | None:
row = await self._connection.fetchrow(ABANDONED, before)
return None if row is None else attachment_of(row)
return await self._one(
COLUMNS.where(AttachmentRow.status == "pending", AttachmentRow.created_at < before)
.order_by(AttachmentRow.created_at)
.limit(1)
.with_for_update(skip_locked=True)
)
async def remove(self, attachment: Attachment) -> None:
await self._connection.execute(REMOVE, attachment.id)
await self._session.execute(
delete(AttachmentRow).where(
AttachmentRow.id == attachment.id, AttachmentRow.status == "pending"
)
)
self._seen.append(attachment)
async def page_after(self, key: str, limit: int) -> Sequence[Attachment]:
return [attachment_of(row) for row in await self._connection.fetch(PAGE, key, limit)]
rows = await self._session.execute(
COLUMNS.where(AttachmentRow.object_key > key)
.order_by(AttachmentRow.object_key)
.limit(limit)
)
return [attachment_of(row) for row in rows.mappings()]
async def by_key(self, key: str) -> Attachment | None:
row = await self._connection.fetchrow(BY_KEY, key)
return None if row is None else attachment_of(row)
return await self._one(COLUMNS.where(AttachmentRow.object_key == key))
async def claim(self, attachment_id: UUID) -> Attachment | None:
row = await self._connection.fetchrow(CLAIM, attachment_id)
return None if row is None else attachment_of(row)
return await self._one(
COLUMNS.where(AttachmentRow.id == attachment_id).with_for_update(skip_locked=True)
)
async def mark(self, attachment: Attachment) -> None:
reason = None if attachment.quarantine is None else attachment.quarantine.value
await self._connection.execute(QUARANTINE, attachment.id, reason)
await self._session.execute(
update(AttachmentRow)
.where(AttachmentRow.id == attachment.id, AttachmentRow.status == "ready")
.values(quarantine_reason=reason, quarantined_at=None if reason is None else func.now())
)
class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork):
@@ -133,7 +205,7 @@ class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork):
@property
def attachments(self) -> PostgresAttachmentRepository:
return PostgresAttachmentRepository(self.connection, self.seen)
return PostgresAttachmentRepository(self.session, self.seen)
class PostgresAttachmentDirectory:
@@ -143,8 +215,18 @@ class PostgresAttachmentDirectory:
self._database = database
async def ready(self, attachment_id: UUID) -> Attachment | None:
async with self._database.connection() as connection:
row = await connection.fetchrow(READY, attachment_id)
async with self._database.session() as session:
row = (
(
await session.execute(
COLUMNS.where(
AttachmentRow.id == attachment_id, AttachmentRow.status == "ready"
)
)
)
.mappings()
.first()
)
return None if row is None else attachment_of(row)
@@ -157,10 +239,13 @@ class PostgresSingleRun:
@asynccontextmanager
async def hold(self) -> AsyncIterator[bool]:
async with self._database.connection() as connection:
held = await connection.fetchval("SELECT pg_try_advisory_lock($1)", self._key)
async with self._database.session() as session:
connection = await session.connection(
execution_options={"isolation_level": "AUTOCOMMIT"}
)
held = bool(await connection.scalar(select(func.pg_try_advisory_lock(self._key))))
try:
yield held
finally:
if held:
await connection.fetchval("SELECT pg_advisory_unlock($1)", self._key)
await connection.execute(select(func.pg_advisory_unlock(self._key)))
+121 -60
View File
@@ -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,
)
+343 -127
View File
@@ -1,9 +1,38 @@
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,
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.domain.keys import HistoryKey
@@ -11,97 +40,206 @@ 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
), links AS (
INSERT INTO message_attachments (message_id, position, chat_id, attachment_id)
SELECT $1, link.position - 1, $2, link.attachment_id
FROM message, unnest($9::uuid[]) WITH ORDINALITY AS link (attachment_id, position)
), 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
"""
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
"""
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"]),
@@ -110,14 +248,14 @@ 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"],
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"],
)
@@ -126,19 +264,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)
@@ -153,29 +304,62 @@ 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:
async with self._database.session() as session:
try:
row = await connection.fetchrow(
POST_MESSAGE,
message.id,
chat_id,
sender_id,
message.text.value,
message.created_at,
key,
fingerprint,
since,
list(message.attachment_ids),
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 ForeignKeyViolationError as error:
if getattr(error, "constraint_name", None) != ATTACHMENT_FKEY:
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:
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,
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()
)
if known is None:
raise Unavailable("ключ идемпотентности занят незавершённой записью")
return Receipt(key, known["fingerprint"], message_of(known))
@@ -186,7 +370,7 @@ class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
@property
def chats(self) -> PostgresChatRepository:
return PostgresChatRepository(self.connection, self.seen)
return PostgresChatRepository(self.session, self.seen)
class PostgresChatDirectory:
@@ -196,30 +380,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)
-70
View File
@@ -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()
-46
View File
@@ -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,37 +0,0 @@
ALTER TABLE messages
DROP CONSTRAINT messages_text_check,
ADD CONSTRAINT messages_text_check CHECK (char_length(text) <= 4000);
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
owner_id uuid NOT NULL,
filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
width integer NOT NULL CHECK (width > 0),
height integer NOT NULL CHECK (height > 0),
object_key text COLLATE "C" NOT NULL CONSTRAINT attachments_object_key_key UNIQUE,
status text NOT NULL CHECK (status IN ('pending', 'ready')),
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT attachments_chat_key UNIQUE (id, chat_id),
CONSTRAINT attachments_owner_fkey FOREIGN KEY (chat_id, owner_id)
REFERENCES chat_members (chat_id, user_id)
);
CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE status = 'pending';
CREATE TABLE message_attachments (
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
position smallint NOT NULL CHECK (position BETWEEN 0 AND 9),
chat_id uuid NOT NULL,
attachment_id uuid NOT NULL,
PRIMARY KEY (message_id, position),
UNIQUE (message_id, attachment_id),
CONSTRAINT message_attachments_attachment_fkey FOREIGN KEY (attachment_id, chat_id)
REFERENCES attachments (id, chat_id) ON DELETE RESTRICT
);
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);
@@ -1,6 +0,0 @@
ALTER TABLE attachments
ADD COLUMN quarantine_reason text
CHECK (quarantine_reason IN ('missing', 'size_mismatch', 'sha_mismatch')),
ADD COLUMN quarantined_at timestamptz,
ADD CONSTRAINT attachments_quarantine_check
CHECK ((quarantine_reason IS NULL) = (quarantined_at IS NULL));
+65 -45
View File
@@ -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,63 +50,71 @@ 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,
pool_pre_ping=True,
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
mark = len(self._events)
try:
@@ -101,12 +122,11 @@ class PostgresUnitOfWork:
finally:
if not self._committed:
del self._events[mark:]
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())