Forward-port lab3 SQLAlchemy and Alembic foundation

Carry source f591fa64e5 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)))