"""Сверка bucket и БД (design change `track2-reconciler`, решения 3, 4, 7 и 8). Сервис процесса уборщика (`src/cleaner/`), а не реплик API. Проход: 1. S3 → БД: страницы списка объектов под `<база>/attachments/`, на страницу — одно выражение к БД по `id` из стандартных ключей и по тексту нестандартных; каждый ключ — в множество `seen`; 2. БД → S3: keyset строк `ready` по `id`, ключа нет в `seen` — кандидат «метаданные без объекта»; 3. зависшие загрузки — кандидаты уборщика (`get_stale_pending`); 4. перепроверка каждого кандидата в БД и HEAD перед решением, в обоих режимах; отсутствие объекта — только после проверки, что bucket на месте; 5. предел изменений, затем, с `apply`, действия по порядку: зависшие загрузки (процедурой уборщика) → объекты без метаданных → пометки потерянных → снятия пометок. Каждое действие перед собой ещё раз перепроверяет своё условие. Удаляется только объект без строки и зависшая загрузка; строки `ready`, объекты, на которые ссылается строка, и чужие ключи — никогда. Отказ хранилища на шагах 1–4 прерывает проход без единого изменения, на шаге 5 — после текущего действия; каждое действие безопасно повторять. """ import time from collections import Counter from collections.abc import Callable from dataclasses import replace from datetime import datetime from types import MappingProxyType from uuid import UUID from src.core import exceptions from src.core.repos import attachment as attachment_repo from src.core.repos import attachment_object as attachment_object_repo from src.core.services.attachment import DbScope from src.core.services.attachment_cleanup import ( INTERRUPTED_BY_DATABASE, INTERRUPTED_BY_OBJECT_STORAGE, INTERRUPTED_BY_STOP, AttachmentCleanupService, ) from src.infra.logger import AbstractLogger, get_logger from src.infra.s3 import ObjectStorage, StoredObjectInfo from src.schemas import dataclasses from src.schemas.enums import ( AttachmentStatus, ReconcileAction, ReconcileFinding, ) from src.utils.constants import RECONCILE_FINDINGS_LOGGED_MAX from src.utils.utc import utcnow logger: AbstractLogger = get_logger().bind( module="attachment_reconcile_service", ) # классы, исправление которых — изменение под пределом `max_changes` LIMITED_KINDS = frozenset( { ReconcileFinding.ORPHAN_OBJECT, ReconcileFinding.MISSING_OBJECT, ReconcileFinding.SIZE_MISMATCH, ReconcileFinding.RESTORED_OBJECT, }, ) # порядок действий `apply` (решение 7); чужой объект действия не имеет ACTION_ORDER = ( ReconcileFinding.STALE_PENDING, ReconcileFinding.ORPHAN_OBJECT, ReconcileFinding.MISSING_OBJECT, ReconcileFinding.SIZE_MISMATCH, ReconcileFinding.RESTORED_OBJECT, ) # классы, у которых отсутствие объекта подтверждается: сначала — bucket NEEDS_BUCKET = frozenset( {ReconcileFinding.MISSING_OBJECT, ReconcileFinding.SIZE_MISMATCH}, ) def _never() -> bool: return False def _age_seconds(moment: datetime, *, now: datetime) -> int: return max(0, round((now - moment).total_seconds())) class _Stopped(Exception): """Сигнал остановки между страницами или действиями.""" class _Pass: """Счётчики и находки одного прохода.""" def __init__(self, *, apply: bool, now: datetime) -> None: self.apply = apply self.now = now self.listed_objects = 0 self.checked_rows = 0 self.fresh_objects = 0 self.fresh_rows = 0 self.lost_known = 0 self.seen: set[str] = set() self.candidates: list[dataclasses.ReconcileFindingDTO] = [] self.confirmed: list[dataclasses.ReconcileFindingDTO] = [] # индексы `confirmed`: исправленные и выбывшие на действии self.fixed: dict[int, ReconcileAction] = {} self.dropped: set[int] = set() self.refused = False self.logged = 0 self.unlogged = 0 def age(self, moment: datetime) -> int: return _age_seconds(moment, now=self.now) class AttachmentReconcileService: """Сверка объектов вложений своей базы с их метаданными. `db_scope` — фабрика короткой сессии процесса уборщика, `storage` — клиент S3 с ключами пользователя уборщика (список — только по префиксу вложений своей базы). Зависшие загрузки убирает `AttachmentCleanupService` тем же шагом, что сервис уборки. """ def __init__(self, db_scope: DbScope, storage: ObjectStorage) -> None: self.db_scope = db_scope self.storage = storage self.cleanup = AttachmentCleanupService( db_scope=db_scope, storage=storage, ) async def reconcile( self, *, older_than: datetime, apply: bool, max_changes: int, page_size: int, batch_size: int, stop_requested: Callable[[], bool] = _never, ) -> dataclasses.ReconcilePassDTO: """Один проход сверки; `older_than` — порог grace прохода. Без `apply` ничего не меняет. Отказ S3 или PostgreSQL прерывает проход (`interrupted_by`); сигнал (`stop_requested()`) — между страницами и действиями, текущий вызов доводится до конца. Отказ, пришедший уже после сигнала, считается остановкой. """ started = time.monotonic() log = logger.bind(method="reconcile", apply=apply) state = _Pass(apply=apply, now=utcnow()) interrupted_by: str | None = None try: await self._list_objects( state, older_than=older_than, page_size=page_size, stop_requested=stop_requested, ) await self._check_rows( state, older_than=older_than, page_size=page_size, stop_requested=stop_requested, ) await self._stale_pending( state, older_than=older_than, batch_size=batch_size, stop_requested=stop_requested, ) await self._recheck_all( state, older_than=older_than, stop_requested=stop_requested, ) if apply: await self._act( state, older_than=older_than, max_changes=max_changes, stop_requested=stop_requested, log=log, ) except _Stopped: interrupted_by = INTERRUPTED_BY_STOP except exceptions.ObjectStorageUnavailable: # причину уже записал клиент S3 (`object_storage`) interrupted_by = ( INTERRUPTED_BY_STOP if stop_requested() else INTERRUPTED_BY_OBJECT_STORAGE ) except exceptions.ServiceUnavailable: # причину уже записал `session_scope` (`database`) interrupted_by = ( INTERRUPTED_BY_STOP if stop_requested() else INTERRUPTED_BY_DATABASE ) return self._finish( state, interrupted_by=interrupted_by, duration_ms=round((time.monotonic() - started) * 1000), log=log, ) # --------------------------------------------------------- классификация async def _list_objects( self, state: _Pass, *, older_than: datetime, page_size: int, stop_requested: Callable[[], bool], ) -> None: """Шаг 1, S3 → БД: страницы списка и строки страницы одним выражением; классификация без новых вызовов S3.""" token: str | None = None while True: if stop_requested(): raise _Stopped page = await attachment_object_repo.list_originals( self.storage, token=token, max_keys=page_size, ) state.listed_objects += len(page.objects) parsed = { item.key: attachment_object_repo.parse_original_key( self.storage, key=item.key, ) for item in page.objects } ids = {value for value in parsed.values() if value is not None} keys = {key for key, value in parsed.items() if value is None} rows: list[dataclasses.AttachmentFullDTO] = [] if parsed: async with self.db_scope() as db_session: rows = await attachment_repo.get_attachments_for_objects( db_session=db_session, attachment_ids=ids, object_keys=keys, ) by_id = {row.id: row for row in rows} by_key = {row.object_key: row for row in rows} for item in page.objects: state.seen.add(item.key) attachment_id = parsed[item.key] row = ( by_id.get(attachment_id) if attachment_id is not None else by_key.get(item.key) ) if row is not None and row.object_key == item.key: self._row_with_object( state, row=row, stored=item, older_than=older_than, ) continue if _is_fresh(item, older_than=older_than): state.fresh_objects += 1 continue # нет строки — объект без метаданных; строка этого id с # другим ключом или ключ, которого API не пишет, — чужой kind = ( ReconcileFinding.ORPHAN_OBJECT if attachment_id is not None and row is None else ReconcileFinding.UNKNOWN_OBJECT ) state.candidates.append( dataclasses.ReconcileFindingDTO( kind=kind, object_key=item.key, attachment_id=attachment_id, age_seconds=_object_age(state, item), ), ) token = page.next_token if token is None: return def _row_with_object( self, state: _Pass, *, row: dataclasses.AttachmentFullDTO, stored: StoredObjectInfo, older_than: datetime, ) -> None: if row.status != AttachmentStatus.READY: # строка pending: объект её загрузки — дело уборщика return same_size = stored.size == row.size_bytes if row.lost_at is not None: if same_size: state.candidates.append( _finding( ReconcileFinding.RESTORED_OBJECT, row, state, stored_size=stored.size, ), ) else: state.lost_known += 1 return if same_size: return if row.updated_at >= older_than: state.fresh_rows += 1 return state.candidates.append( _finding( ReconcileFinding.SIZE_MISMATCH, row, state, stored_size=stored.size, ), ) async def _check_rows( self, state: _Pass, *, older_than: datetime, page_size: int, stop_requested: Callable[[], bool], ) -> None: """Шаг 2, БД → S3: строки `ready`, ключей которых нет в списке.""" after: UUID | None = None while True: if stop_requested(): raise _Stopped async with self.db_scope() as db_session: rows = await attachment_repo.get_ready_page( db_session=db_session, after=after, limit=page_size, ) for row in rows: state.checked_rows += 1 if row.object_key in state.seen: continue if row.lost_at is not None: state.lost_known += 1 elif row.updated_at >= older_than: state.fresh_rows += 1 else: state.candidates.append( _finding(ReconcileFinding.MISSING_OBJECT, row, state), ) if len(rows) < page_size: return after = rows[-1].id async def _stale_pending( self, state: _Pass, *, older_than: datetime, batch_size: int, stop_requested: Callable[[], bool], ) -> None: """Шаг 3: зависшие загрузки — те же кандидаты, что у уборщика.""" after: tuple[datetime, UUID] | None = None while True: if stop_requested(): raise _Stopped async with self.db_scope() as db_session: rows = await attachment_repo.get_stale_pending( db_session=db_session, older_than=older_than, after=after, limit=batch_size, ) state.candidates.extend( dataclasses.ReconcileFindingDTO( kind=ReconcileFinding.STALE_PENDING, object_key=row.object_key, attachment_id=row.id, age_seconds=state.age(row.created_at), ) for row in rows ) if len(rows) < batch_size: return after = (rows[-1].created_at, rows[-1].id) # ---------------------------------------------------------- перепроверка async def _recheck_all( self, state: _Pass, *, older_than: datetime, stop_requested: Callable[[], bool], ) -> None: """Шаг 4: каждый кандидат подтверждается в БД и S3 до решения; не подтвердился — выбывает без записи.""" if any(item.kind in NEEDS_BUCKET for item in state.candidates): await attachment_object_repo.probe_originals(self.storage) for candidate in state.candidates: if stop_requested(): raise _Stopped confirmed = await self._recheck( candidate, older_than=older_than, state=state, ) if confirmed is not None: state.confirmed.append(confirmed) async def _recheck( self, candidate: dataclasses.ReconcileFindingDTO, *, older_than: datetime, state: _Pass, ) -> dataclasses.ReconcileFindingDTO | None: kind = candidate.kind if kind in ( ReconcileFinding.STALE_PENDING, ReconcileFinding.UNKNOWN_OBJECT, ): # зависшую загрузку уборщик перепроверяет под блокировкой сам, # чужой объект сверка не трогает return candidate if kind == ReconcileFinding.ORPHAN_OBJECT: return await self._recheck_orphan( candidate, older_than=older_than, state=state, ) row = await self._get_row(candidate) if row is None or row.status != AttachmentStatus.READY: return None stored = await attachment_object_repo.head_original( self.storage, key=candidate.object_key, ) if kind == ReconcileFinding.RESTORED_OBJECT: if row.lost_at is None or stored is None: return None return candidate if stored.size == row.size_bytes else None if row.lost_at is not None: return None if stored is None: return _finding(ReconcileFinding.MISSING_OBJECT, row, state) if stored.size != row.size_bytes: return _finding( ReconcileFinding.SIZE_MISMATCH, row, state, stored_size=stored.size, ) return None async def _recheck_orphan( self, candidate: dataclasses.ReconcileFindingDTO, *, older_than: datetime, state: _Pass, ) -> dataclasses.ReconcileFindingDTO | None: """Строки с этим `id` или ключом нет, объект на месте и старше порога. Строка другого `id` ссылается на ключ — чужой объект.""" references = await self._references(candidate) if any( row.object_key == candidate.object_key and row.id != candidate.attachment_id for row in references ): return replace(candidate, kind=ReconcileFinding.UNKNOWN_OBJECT) if references: return None stored = await attachment_object_repo.head_original( self.storage, key=candidate.object_key, ) if stored is None or _is_fresh(stored, older_than=older_than): return None return replace(candidate, age_seconds=_object_age(state, stored)) async def _get_row( self, candidate: dataclasses.ReconcileFindingDTO, ) -> dataclasses.AttachmentFullDTO | None: if candidate.attachment_id is None: return None async with self.db_scope() as db_session: row = await attachment_repo.get_attachment( db_session=db_session, attachment_id=candidate.attachment_id, ) if row is None or row.object_key != candidate.object_key: return None return row async def _references( self, candidate: dataclasses.ReconcileFindingDTO, ) -> list[dataclasses.AttachmentFullDTO]: if candidate.attachment_id is None: return [] async with self.db_scope() as db_session: return await attachment_repo.find_attachment_reference( db_session=db_session, attachment_id=candidate.attachment_id, object_key=candidate.object_key, ) # -------------------------------------------------------------- действия async def _act( self, state: _Pass, *, older_than: datetime, max_changes: int, stop_requested: Callable[[], bool], log: AbstractLogger, ) -> None: """Шаг 5: предел изменений, затем действия по порядку решения 7.""" changes = sum(item.kind in LIMITED_KINDS for item in state.confirmed) if changes > max_changes: state.refused = True log.error( "Reconcile changes exceed limit", changes=changes, max_changes=max_changes, ) bucket_probed = False for kind in ACTION_ORDER: if state.refused and kind in LIMITED_KINDS: continue for index, finding in enumerate(state.confirmed): if finding.kind != kind: continue if stop_requested(): raise _Stopped if kind in NEEDS_BUCKET and not bucket_probed: # отсутствие объекта — снова только при живом bucket await attachment_object_repo.probe_originals(self.storage) bucket_probed = True action = await self._fix( finding, older_than=older_than, stop_requested=stop_requested, ) if action is None: state.dropped.add(index) continue state.fixed[index] = action self._record(state, finding, action=action, log=log) async def _fix( self, finding: dataclasses.ReconcileFindingDTO, *, older_than: datetime, stop_requested: Callable[[], bool], ) -> ReconcileAction | None: """Одно действие с перепроверкой непосредственно перед ним; `None` — условие уже не выполняется, ничего не изменено.""" kind = finding.kind if kind == ReconcileFinding.STALE_PENDING: removed = await self.cleanup.remove_stale_pending( attachment_id=finding.attachment_id, older_than=older_than, stop_requested=stop_requested, log=logger.bind(method="reconcile"), ) return ReconcileAction.REMOVED_PENDING if removed else None if kind == ReconcileFinding.ORPHAN_OBJECT: if await self._references(finding): return None await attachment_object_repo.delete_original( self.storage, key=finding.object_key, ) return ReconcileAction.DELETED_OBJECT stored = await attachment_object_repo.head_original( self.storage, key=finding.object_key, ) if kind == ReconcileFinding.RESTORED_OBJECT: if stored is None or stored.size != finding.size_bytes: return None async with self.db_scope() as db_session: cleared = await attachment_repo.clear_lost( db_session=db_session, attachment_id=finding.attachment_id, object_key=finding.object_key, ) await db_session.commit() return ReconcileAction.CLEARED_LOST if cleared else None # метаданные без объекта или другой размер: объекта по-прежнему нет # или размер по-прежнему другой if stored is not None and stored.size == finding.size_bytes: return None async with self.db_scope() as db_session: marked = await attachment_repo.mark_lost( db_session=db_session, attachment_id=finding.attachment_id, object_key=finding.object_key, lost_at=utcnow(), ) await db_session.commit() return ReconcileAction.MARKED_LOST if marked else None # ------------------------------------------------------------------ итог def _record( self, state: _Pass, finding: dataclasses.ReconcileFindingDTO, *, action: ReconcileAction | None, log: AbstractLogger, ) -> None: """Запись о расхождении: `info` с действием — исправлено, `warning` — осталось. Не больше `RECONCILE_FINDINGS_LOGGED_MAX` записей за проход, остальные — числом в итоге.""" if state.logged >= RECONCILE_FINDINGS_LOGGED_MAX: state.unlogged += 1 return state.logged += 1 fields: dict[str, object] = { "kind": finding.kind.value, "object_key": finding.object_key, "attachment_id": finding.attachment_id, "age_seconds": finding.age_seconds, } if ( finding.stored_size is not None and finding.stored_size != finding.size_bytes ): fields["size_bytes"] = finding.size_bytes fields["stored_size"] = finding.stored_size if action is None: log.warning("Found storage discrepancy", **fields) else: log.info( "Fixed storage discrepancy", action=action.value, **fields, ) def _finish( self, state: _Pass, *, interrupted_by: str | None, duration_ms: int, log: AbstractLogger, ) -> dataclasses.ReconcilePassDTO: remaining = [ finding for index, finding in enumerate(state.confirmed) if index not in state.fixed and index not in state.dropped ] for finding in remaining: self._record(state, finding, action=None, log=log) found = Counter( finding.kind for index, finding in enumerate(state.confirmed) if index not in state.dropped ) fixed = Counter(state.confirmed[index].kind for index in state.fixed) result = dataclasses.ReconcilePassDTO( apply=state.apply, listed_objects=state.listed_objects, checked_rows=state.checked_rows, found=MappingProxyType(dict(found)), fixed=MappingProxyType(dict(fixed)), remaining=len(remaining), fresh_objects=state.fresh_objects, fresh_rows=state.fresh_rows, lost_known=state.lost_known, refused=state.refused, unlogged=state.unlogged, interrupted_by=interrupted_by, duration_ms=duration_ms, ) fields = { "listed_objects": result.listed_objects, "checked_rows": result.checked_rows, "found": {kind.value: count for kind, count in found.items()}, "fixed": {kind.value: count for kind, count in fixed.items()}, "remaining": result.remaining, "fresh_objects": result.fresh_objects, "fresh_rows": result.fresh_rows, "lost_known": result.lost_known, "refused": result.refused, "unlogged": result.unlogged, "interrupted_by": result.interrupted_by, "duration_ms": result.duration_ms, } if result.remaining or result.refused or interrupted_by is not None: log.warning("Finished reconcile pass", **fields) else: log.info("Finished reconcile pass", **fields) return result def _is_fresh(stored: StoredObjectInfo, *, older_than: datetime) -> bool: """Объект записан или изменён не раньше порога; без времени — свежий: удалять без доказанного возраста нельзя.""" return stored.last_modified is None or stored.last_modified >= older_than def _object_age(state: _Pass, stored: StoredObjectInfo) -> int: return ( 0 if stored.last_modified is None else state.age(stored.last_modified) ) def _finding( kind: ReconcileFinding, row: dataclasses.AttachmentFullDTO, state: _Pass, *, stored_size: int | None = None, ) -> dataclasses.ReconcileFindingDTO: """Находка по строке: возраст — от перевода в `ready` (`updated_at`).""" return dataclasses.ReconcileFindingDTO( kind=kind, object_key=row.object_key, attachment_id=row.id, age_seconds=state.age(row.updated_at), size_bytes=row.size_bytes, stored_size=stored_size, )