chore: port lab 4 solution into the lab 5 skeleton

Source: mtusi2026lab4-safronov, solution/bvt2301-safronov, 2546deb.
Contracts, public tests and evidence of lab 4 are not carried over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-31 03:09:12 +03:00
co-authored by Claude Opus 5.5
parent 276dbdad8a
commit 04f859282d
479 changed files with 106103 additions and 24 deletions
+349
View File
@@ -0,0 +1,349 @@
"""Метаданные вложений в PostgreSQL.
Строка пишется в статусе `pending` до записи объекта и переводится в
`ready` после неё (design change `attachments`, решение 1). Видимость
`pending` решает сервис: repo отдаёт строку как есть. Незавершённые
загрузки выбирает, блокирует, помечает и удаляет уборщик (design change
`upload-consistency`, решение 3). Сверка bucket и БД выбирает строки
страницы списка S3 и строки `ready`, помечает потерянный оригинал
(`lost_at`) и снимает пометку (design change `track2-reconciler`, решения
3–5).
"""
from collections.abc import Collection
from datetime import datetime
from uuid import UUID
from sqlalchemy import (
BindParameter,
ColumnElement,
Row,
Text,
Uuid,
any_,
bindparam,
delete,
insert,
literal,
or_,
select,
tuple_,
update,
)
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.types import TypeEngine
from src.infra.db.models import Attachment
from src.schemas import dataclasses
from src.schemas.enums import AttachmentStatus, ImageType
_ATTACHMENT_COLUMNS = (
Attachment.id,
Attachment.chat_id,
Attachment.owner_id,
Attachment.filename,
Attachment.content_type,
Attachment.size_bytes,
Attachment.sha256,
Attachment.object_key,
Attachment.status,
Attachment.created_at,
Attachment.updated_at,
Attachment.lost_at,
)
def _to_dto(row: Row) -> dataclasses.AttachmentFullDTO:
fields = dict(row._mapping)
fields["content_type"] = ImageType(fields["content_type"])
fields["status"] = AttachmentStatus(fields["status"])
return dataclasses.AttachmentFullDTO(**fields)
async def insert_attachment(
db_session: AsyncSession,
*,
attachment: dataclasses.AttachmentFullDTO,
) -> dataclasses.AttachmentFullDTO:
"""Строка вложения со всеми колонками DTO."""
await db_session.execute(
insert(Attachment).values(
id=attachment.id,
chat_id=attachment.chat_id,
owner_id=attachment.owner_id,
filename=attachment.filename,
content_type=attachment.content_type.value,
size_bytes=attachment.size_bytes,
sha256=attachment.sha256,
object_key=attachment.object_key,
status=attachment.status.value,
created_at=attachment.created_at,
updated_at=attachment.updated_at,
),
)
return attachment
async def mark_ready(
db_session: AsyncSession,
*,
attachment_id: UUID,
updated_at: datetime,
) -> dataclasses.AttachmentFullDTO | None:
"""`pending` → `ready`; `None` — строки `pending` нет или уборщик уже
пометил её к уборке.
Вставка пишет `created_at` и `updated_at` одним значением, а уборщик
до удаления объекта сдвигает `updated_at` (`mark_removing`): `ready`
становится только непомеченная строка (design change
`upload-consistency`, «Уточнения apply», п. 16).
"""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status == AttachmentStatus.PENDING.value,
Attachment.updated_at == Attachment.created_at,
)
.values(status=AttachmentStatus.READY.value, updated_at=updated_at)
.returning(*_ATTACHMENT_COLUMNS)
)
row = (await db_session.execute(statement)).one_or_none()
return None if row is None else _to_dto(row)
async def get_attachment(
db_session: AsyncSession,
*,
attachment_id: UUID,
) -> dataclasses.AttachmentFullDTO | None:
statement = select(*_ATTACHMENT_COLUMNS).where(
Attachment.id == attachment_id,
)
row = (await db_session.execute(statement)).one_or_none()
return None if row is None else _to_dto(row)
async def get_attachments(
db_session: AsyncSession,
*,
attachment_ids: Collection[UUID],
) -> list[dataclasses.AttachmentFullDTO]:
"""Найденные строки по первичному ключу, в любом порядке."""
statement = select(*_ATTACHMENT_COLUMNS).where(
Attachment.id.in_(attachment_ids),
)
rows = (await db_session.execute(statement)).all()
return [_to_dto(row) for row in rows]
# незавершённые загрузки для уборщика (design change upload-consistency,
# решение 3): условия совпадают с частичным индексом
# ix_attachments_pending_created_at
_STALE_COLUMNS = (Attachment.id, Attachment.object_key, Attachment.created_at)
def _stale_pending(older_than: datetime) -> tuple[ColumnElement[bool], ...]:
# статус — константой в тексте запроса, а не параметром: условие
# частичного индекса планировщик доказывает только по константе, и
# общий план подготовленного выражения asyncpg иначе индекс не взял бы
return (
Attachment.status
== literal(AttachmentStatus.PENDING.value, literal_execute=True),
Attachment.created_at < older_than,
)
async def get_stale_pending(
db_session: AsyncSession,
*,
older_than: datetime,
after: tuple[datetime, UUID] | None,
limit: int,
) -> list[dataclasses.AttachmentInListDTO]:
"""Строки `pending` старше `older_than` по `(created_at, id)` после
`after` — keyset по частичному индексу, без блокировки."""
statement = (
select(*_STALE_COLUMNS)
.where(*_stale_pending(older_than))
.order_by(Attachment.created_at, Attachment.id)
.limit(limit)
)
if after is not None:
statement = statement.where(
tuple_(Attachment.created_at, Attachment.id) > tuple_(*after),
)
rows = (await db_session.execute(statement)).all()
return [dataclasses.AttachmentInListDTO(**row._mapping) for row in rows]
async def lock_stale_pending(
db_session: AsyncSession,
*,
attachment_id: UUID,
older_than: datetime,
) -> dataclasses.AttachmentInListDTO | None:
"""Та же строка под `FOR UPDATE SKIP LOCKED` до конца транзакции.
`None` — строки уже нет, она стала `ready` или её держит другой
процесс (`mark_ready` загрузки, второй уборщик).
"""
statement = (
select(*_STALE_COLUMNS)
.where(Attachment.id == attachment_id, *_stale_pending(older_than))
.with_for_update(skip_locked=True)
)
row = (await db_session.execute(statement)).one_or_none()
return (
None
if row is None
else dataclasses.AttachmentInListDTO(**row._mapping)
)
async def mark_removing(
db_session: AsyncSession,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
"""Пометить строку к уборке: `updated_at` позже `created_at`, и
`mark_ready` её больше не переведёт в `ready`. `False` — строки нет.
Вызывается под блокировкой `lock_stale_pending`: `created_at` строки
раньше порога прохода, а `updated_at` — время уборщика после него.
"""
statement = (
update(Attachment)
.where(Attachment.id == attachment_id)
.values(updated_at=updated_at)
.returning(Attachment.id)
)
return (await db_session.execute(statement)).one_or_none() is not None
async def delete_attachment(
db_session: AsyncSession,
*,
attachment_id: UUID,
) -> bool:
"""Удалить строку вложения; `False` — строки не было."""
statement = (
delete(Attachment)
.where(Attachment.id == attachment_id)
.returning(Attachment.id)
)
return (await db_session.execute(statement)).one_or_none() is not None
# сверка bucket и БД (design change track2-reconciler, решения 3–5)
async def get_attachments_for_objects(
db_session: AsyncSession,
*,
attachment_ids: Collection[UUID],
object_keys: Collection[str],
) -> list[dataclasses.AttachmentFullDTO]:
"""Строки страницы списка S3 одним выражением: `id = ANY(:ids) OR
object_key = ANY(:keys)`. `ids` — из стандартных ключей
`<id>/original`, `keys` — только нестандартные ключи: по `id` выборка
в 15 раз дешевле, чем по тексту ключа (design, Context)."""
statement = select(*_ATTACHMENT_COLUMNS).where(
or_(
Attachment.id == any_(_array(list(attachment_ids), Uuid())),
Attachment.object_key == any_(_array(list(object_keys), Text())),
),
)
rows = (await db_session.execute(statement)).all()
return [_to_dto(row) for row in rows]
async def get_ready_page(
db_session: AsyncSession,
*,
after: UUID | None,
limit: int,
) -> list[dataclasses.AttachmentFullDTO]:
"""Строки `ready` keyset по `id` после `after` (Index Scan
`pk_attachments`, статус — фильтр)."""
statement = (
select(*_ATTACHMENT_COLUMNS)
.where(Attachment.status == AttachmentStatus.READY.value)
.order_by(Attachment.id)
.limit(limit)
)
if after is not None:
statement = statement.where(Attachment.id > after)
rows = (await db_session.execute(statement)).all()
return [_to_dto(row) for row in rows]
async def find_attachment_reference(
db_session: AsyncSession,
*,
attachment_id: UUID,
object_key: str,
) -> list[dataclasses.AttachmentFullDTO]:
"""Строки, из-за которых объект нельзя удалить: строка этого `id` или
любая строка, которая ссылается на этот ключ (до двух строк)."""
statement = select(*_ATTACHMENT_COLUMNS).where(
or_(
Attachment.id == attachment_id,
Attachment.object_key == object_key,
),
)
rows = (await db_session.execute(statement)).all()
return [_to_dto(row) for row in rows]
async def mark_lost(
db_session: AsyncSession,
*,
attachment_id: UUID,
object_key: str,
lost_at: datetime,
) -> bool:
"""Пометить оригинал потерянным: только `ready`, ещё не помеченное, с
тем же ключом. `status` и `updated_at` не меняются. `False` — условие
уже не выполняется."""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status == AttachmentStatus.READY.value,
Attachment.lost_at.is_(None),
Attachment.object_key == object_key,
)
.values(lost_at=lost_at)
.returning(Attachment.id)
)
return (await db_session.execute(statement)).one_or_none() is not None
async def clear_lost(
db_session: AsyncSession,
*,
attachment_id: UUID,
object_key: str,
) -> bool:
"""Снять пометку: оригинал снова есть. `False` — пометки уже нет или
ключ другой."""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.lost_at.is_not(None),
Attachment.object_key == object_key,
)
.values(lost_at=None)
.returning(Attachment.id)
)
return (await db_session.execute(statement)).one_or_none() is not None
def _array(values: list, item_type: TypeEngine) -> BindParameter:
# один параметр-массив вместо списка параметров IN: план не зависит от
# длины страницы (до 1000)
return bindparam(None, values, type_=ARRAY(item_type))