Files
mtusi2026lab7-safronov/src/core/repos/attachment.py
T
ricoromaandClaude Opus 5.5 089d78609d chore: port lab 6 solution into the lab 7 skeleton
Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065.
Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public
tests, README, REPORT and evidence of lab 6 are not carried over; infra
and scripts of the lab 7 skeleton stay as they are.
Makefile is the lab 6 one with the lab 7 skeleton part restored
(HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore
are taken from lab 6 because both skeletons have the same files;
.env.example is the lab 6 one without changes.
The compose project, image and CI prefix are renamed to lab7, and
references to the previous lab now name lab6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 03:59:04 +03:00

640 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Метаданные вложений в PostgreSQL.
Строка пишется в статусе `pending` до записи объекта и переводится в
`ready` после неё (design change `attachments`, решение 1). Видимость
`pending` решает сервис: repo отдаёт строку как есть. С лабы 5 (design
change `async-attachments`, решения 1–3) `pending` становится `queued`
вместе с заданием, а `processing`, `ready` и `failed` ставит worker;
`updated_at` пишется через `greatest`: часы консольного API и worker
расходятся, а CHECK `updated_at >= created_at` иначе ронял бы запись.
Незавершённые
загрузки выбирает, блокирует, помечает и удаляет уборщик (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,
func,
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.core.ports.attachment import AbstractAttachmentRepository
from src.infra.db.models import Attachment
from src.schemas import dataclasses
from src.schemas.enums import (
AttachmentErrorCode,
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,
Attachment.staging_key,
Attachment.error_code,
)
def _to_dto(row: Row) -> dataclasses.AttachmentFullDTO:
fields = dict(row._mapping)
fields["content_type"] = ImageType(fields["content_type"])
fields["status"] = AttachmentStatus(fields["status"])
if fields["error_code"] is not None:
fields["error_code"] = AttachmentErrorCode(fields["error_code"])
return dataclasses.AttachmentFullDTO(**fields)
def _later_of_now(now: datetime) -> ColumnElement[datetime]:
return func.greatest(now, Attachment.updated_at)
# очистка staging (design change pipeline-reliability, решение 9)
_STAGING_COLUMNS = (
Attachment.id,
Attachment.object_key,
Attachment.created_at,
Attachment.staging_key,
Attachment.status,
Attachment.updated_at,
)
def _staging_condition(
status: AttachmentStatus,
updated_before: datetime | None,
) -> tuple[ColumnElement[bool], ...]:
# статус — константа: первая колонка индекса, план без параметра
condition = (
Attachment.staging_key.is_not(None),
Attachment.status == literal(status.value, literal_execute=True),
)
if updated_before is None:
return condition
return (*condition, Attachment.updated_at < updated_before)
def _to_staging_candidate(row: Row) -> dataclasses.AttachmentInListDTO:
fields = dict(row._mapping)
fields["status"] = AttachmentStatus(fields["status"])
return dataclasses.AttachmentInListDTO(**fields)
# незавершённые загрузки для уборщика (design change upload-consistency,
# решение 3): условия совпадают с частичным индексом
# ix_attachments_pending_created_at
_STALE_COLUMNS = (
Attachment.id,
Attachment.object_key,
Attachment.created_at,
Attachment.staging_key,
)
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,
)
def _array(values: list, item_type: TypeEngine) -> BindParameter:
# один параметр-массив вместо списка параметров IN: план не зависит от
# длины страницы (до 1000)
return bindparam(None, values, type_=ARRAY(item_type))
class SqlAlchemyAttachmentRepository(AbstractAttachmentRepository):
def __init__(self, session: AsyncSession) -> None:
self._session = session
async def insert_attachment(
self,
*,
attachment: dataclasses.AttachmentFullDTO,
) -> dataclasses.AttachmentFullDTO:
"""Строка вложения со всеми колонками DTO."""
await self._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,
staging_key=attachment.staging_key,
status=attachment.status.value,
created_at=attachment.created_at,
updated_at=attachment.updated_at,
),
)
return attachment
async def mark_queued(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> dataclasses.AttachmentFullDTO | None:
"""`pending` → `queued`; `None` — строки `pending` нет или уборщик уже
пометил её к уборке.
Вставка пишет `created_at` и `updated_at` одним значением, а уборщик
до удаления объекта сдвигает `updated_at` (`mark_removing`): `queued`
становится только непомеченная строка (design change
`upload-consistency`, «Уточнения apply», п. 16). `updated_at` растёт:
строка, вернувшаяся в `pending` отменой, больше не переводится.
"""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status == AttachmentStatus.PENDING.value,
Attachment.updated_at == Attachment.created_at,
)
.values(
status=AttachmentStatus.QUEUED.value,
updated_at=_later_of_now(updated_at),
)
.returning(*_ATTACHMENT_COLUMNS)
)
row = (await self._session.execute(statement)).one_or_none()
return None if row is None else _to_dto(row)
async def mark_processing(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
"""`queued` или `processing` (прежняя попытка потеряна) → `processing`.
`ready` и `failed` не трогаются; `False` — условие не выполнено."""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status.in_(
(
AttachmentStatus.QUEUED.value,
AttachmentStatus.PROCESSING.value,
),
),
)
.values(
status=AttachmentStatus.PROCESSING.value,
updated_at=_later_of_now(updated_at),
)
.returning(Attachment.id)
)
return (
await self._session.execute(statement)
).one_or_none() is not None
async def return_to_queued(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
"""Временная ошибка: `processing` → `queued`."""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status == AttachmentStatus.PROCESSING.value,
)
.values(
status=AttachmentStatus.QUEUED.value,
updated_at=_later_of_now(updated_at),
)
.returning(Attachment.id)
)
return (
await self._session.execute(statement)
).one_or_none() is not None
async def return_group_to_queued(
self,
*,
attachment_ids: Collection[UUID],
updated_at: datetime,
) -> int:
"""Истёкшие аренды пакета: `processing` → `queued`; вызывает relay в
той же транзакции, что и возврат заданий."""
statement = (
update(Attachment)
.where(
Attachment.id == any_(_array(list(attachment_ids), Uuid())),
Attachment.status == AttachmentStatus.PROCESSING.value,
)
.values(
status=AttachmentStatus.QUEUED.value,
updated_at=_later_of_now(updated_at),
)
.returning(Attachment.id)
)
return len((await self._session.execute(statement)).all())
async def replay_failed(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
"""Replay: `failed` → `queued`, `error_code` NULL. `False` — условие
уже не выполняется."""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status == AttachmentStatus.FAILED.value,
)
.values(
status=AttachmentStatus.QUEUED.value,
error_code=None,
updated_at=_later_of_now(updated_at),
)
.returning(Attachment.id)
)
return (
await self._session.execute(statement)
).one_or_none() is not None
async def lock_attachment(
self,
*,
attachment_id: UUID,
) -> dataclasses.AttachmentFullDTO | None:
"""Строка под `FOR NO KEY UPDATE`: отправка сообщения со ссылкой на
вложение берёт `FOR KEY SHARE` и не ждёт (design change
`pipeline-reliability`, решение 9)."""
statement = (
select(*_ATTACHMENT_COLUMNS)
.where(Attachment.id == attachment_id)
.with_for_update(key_share=True)
)
row = (await self._session.execute(statement)).one_or_none()
return None if row is None else _to_dto(row)
async def get_staging_candidates(
self,
*,
status: AttachmentStatus,
updated_before: datetime | None,
after: tuple[datetime, UUID] | None,
limit: int,
) -> list[dataclasses.AttachmentInListDTO]:
"""Вложения этого статуса с объектом staging, keyset по `(updated_at,
id)` индекса `ix_attachments_staging_cleanup`, без блокировки."""
statement = (
select(*_STAGING_COLUMNS)
.where(*_staging_condition(status, updated_before))
.order_by(Attachment.updated_at, Attachment.id)
.limit(limit)
)
if after is not None:
statement = statement.where(
tuple_(Attachment.updated_at, Attachment.id) > tuple_(*after),
)
rows = (await self._session.execute(statement)).all()
return [_to_staging_candidate(row) for row in rows]
async def lock_staging_candidate(
self,
*,
attachment_id: UUID,
status: AttachmentStatus,
updated_before: datetime | None,
) -> dataclasses.AttachmentInListDTO | None:
"""Та же строка с теми же условиями под `FOR NO KEY UPDATE SKIP LOCKED`
до конца транзакции; вызов S3 под ней не держит отправку сообщения со
ссылкой на вложение. `None` — условия уже нет или строку держат."""
statement = (
select(*_STAGING_COLUMNS)
.where(
Attachment.id == attachment_id,
*_staging_condition(status, updated_before),
)
.with_for_update(key_share=True, skip_locked=True)
)
row = (await self._session.execute(statement)).one_or_none()
return None if row is None else _to_staging_candidate(row)
async def clear_staging_key(self, *, attachment_id: UUID) -> bool:
"""Объект staging убран; `updated_at` не меняется: метаданные готового
вложения те же."""
statement = (
update(Attachment)
.where(Attachment.id == attachment_id)
.values(staging_key=None)
.returning(Attachment.id)
)
return (
await self._session.execute(statement)
).one_or_none() is not None
async def commit_ready(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
"""`queued` или `processing` → `ready`; `False` — итог уже есть: готовое
вложение не откатывается и не меняет `updated_at`."""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status.in_(
(
AttachmentStatus.QUEUED.value,
AttachmentStatus.PROCESSING.value,
),
),
)
.values(
status=AttachmentStatus.READY.value,
updated_at=_later_of_now(updated_at),
)
.returning(Attachment.id)
)
return (
await self._session.execute(statement)
).one_or_none() is not None
async def commit_failed(
self,
*,
attachment_id: UUID,
error_code: AttachmentErrorCode,
updated_at: datetime,
) -> bool:
"""`queued` или `processing` → `failed` с кодом; `False` — итог уже
есть."""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status.in_(
(
AttachmentStatus.QUEUED.value,
AttachmentStatus.PROCESSING.value,
),
),
)
.values(
status=AttachmentStatus.FAILED.value,
error_code=error_code.value,
updated_at=_later_of_now(updated_at),
)
.returning(Attachment.id)
)
return (
await self._session.execute(statement)
).one_or_none() is not None
async def get_attachment(
self,
*,
attachment_id: UUID,
) -> dataclasses.AttachmentFullDTO | None:
statement = select(*_ATTACHMENT_COLUMNS).where(
Attachment.id == attachment_id,
)
row = (await self._session.execute(statement)).one_or_none()
return None if row is None else _to_dto(row)
async def get_attachments(
self,
*,
attachment_ids: Collection[UUID],
) -> list[dataclasses.AttachmentFullDTO]:
"""Найденные строки по первичному ключу, в любом порядке."""
statement = select(*_ATTACHMENT_COLUMNS).where(
Attachment.id.in_(attachment_ids),
)
rows = (await self._session.execute(statement)).all()
return [_to_dto(row) for row in rows]
async def get_stale_pending(
self,
*,
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 self._session.execute(statement)).all()
return [
dataclasses.AttachmentInListDTO(**row._mapping) for row in rows
]
async def lock_stale_pending(
self,
*,
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 self._session.execute(statement)).one_or_none()
return (
None
if row is None
else dataclasses.AttachmentInListDTO(**row._mapping)
)
async def mark_removing(
self,
*,
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 self._session.execute(statement)
).one_or_none() is not None
async def delete_attachment(self, *, attachment_id: UUID) -> bool:
"""Удалить строку вложения; `False` — строки не было."""
statement = (
delete(Attachment)
.where(Attachment.id == attachment_id)
.returning(Attachment.id)
)
return (
await self._session.execute(statement)
).one_or_none() is not None
# сверка bucket и БД (design change track2-reconciler, решения 3–5)
async def get_attachments_for_objects(
self,
*,
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 self._session.execute(statement)).all()
return [_to_dto(row) for row in rows]
async def get_ready_page(
self,
*,
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 self._session.execute(statement)).all()
return [_to_dto(row) for row in rows]
async def find_attachment_reference(
self,
*,
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 self._session.execute(statement)).all()
return [_to_dto(row) for row in rows]
async def mark_lost(
self,
*,
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 self._session.execute(statement)
).one_or_none() is not None
async def clear_lost(
self,
*,
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 self._session.execute(statement)
).one_or_none() is not None