from collections.abc import AsyncIterator, Sequence from contextlib import asynccontextmanager from datetime import datetime from uuid import UUID 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 ( Base, Database, DatabaseSession, EventSource, PostgresUnitOfWork, ) 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", ) COLUMNS = select(AttachmentRow.__table__) def attachment_of(row: RowMapping) -> Attachment: return Attachment( id=row["id"], chat_id=row["chat_id"], owner_id=row["owner_id"], filename=Filename(row["filename"]), image=ImageInfo(ImageKind(row["content_type"]), row["width"], row["height"]), size_bytes=row["size_bytes"], sha256=row["sha256"], object_key=row["object_key"], status=AttachmentStatus(row["status"]), created_at=row["created_at"], updated_at=row["updated_at"], quarantine=Quarantine(row["quarantine_reason"]) if row["quarantine_reason"] else None, ) class PostgresAttachmentRepository: __slots__ = ("_seen", "_session") 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._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 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._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 is None: raise Unavailable("намерение загрузки уже снято уборкой") self._seen.append(attachment) 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: 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._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]: 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: return await self._one(COLUMNS.where(AttachmentRow.object_key == key)) async def claim(self, attachment_id: UUID) -> Attachment | None: 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._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): __slots__ = () @property def attachments(self) -> PostgresAttachmentRepository: return PostgresAttachmentRepository(self.session, self.seen) class PostgresAttachmentDirectory: __slots__ = ("_database",) def __init__(self, database: Database) -> None: self._database = database async def ready(self, attachment_id: UUID) -> Attachment | None: 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) class PostgresSingleRun: __slots__ = ("_database", "_key") def __init__(self, database: Database, key: int) -> None: self._database = database self._key = key @asynccontextmanager async def hold(self) -> AsyncIterator[bool]: 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.execute(select(func.pg_advisory_unlock(self._key)))