feat: усилить reconciler для lab4

This commit is contained in:
2026-11-05 23:30:24 +03:00
parent a3bbdeef42
commit 1ad44408ba
11 changed files with 276 additions and 54 deletions
+11
View File
@@ -102,6 +102,17 @@ class S3Storage:
self._translate(error)
return ObjectStream(response)
async def exists(self, key: str) -> bool:
try:
await asyncio.to_thread(self._client.stat_object, self.bucket, key)
return True
except Exception as error:
try:
self._translate(error)
except FileNotFoundError:
return False
raise
async def remove(self, key: str) -> None:
try:
await asyncio.to_thread(self._client.remove_object, self.bucket, key)
+56 -11
View File
@@ -83,6 +83,16 @@ async def _load_attachments(
return tuple(AttachmentSnapshot(*row) for row in rows)
async def _metadata_key_exists(
sessions: async_sessionmaker[AsyncSession], object_key: str
) -> bool:
async with sessions() as session:
attachment_id = await session.scalar(
select(AttachmentRow.id).where(AttachmentRow.object_key == object_key).limit(1)
)
return attachment_id is not None
async def reconcile(
sessions: async_sessionmaker[AsyncSession],
storage: S3Storage,
@@ -113,29 +123,51 @@ async def reconcile(
)
removed = 0
race_protected = 0
for item in plan.orphan:
action = 'DELETE_ORPHAN' if apply else 'WOULD_DELETE_ORPHAN'
if not apply:
output(f'{action} key={item.key} modified={item.last_modified.isoformat()}')
continue
# PostgreSQL and S3 cannot share a transaction. Re-read the authoritative
# metadata immediately before a destructive action so a row created after
# the initial snapshot protects its object.
if await _metadata_key_exists(sessions, item.key):
output(f'SKIP_ORPHAN_METADATA_APPEARED key={item.key}')
race_protected += 1
continue
output(f'{action} key={item.key} modified={item.last_modified.isoformat()}')
if apply:
await storage.remove(item.key)
removed += 1
await storage.remove(item.key)
removed += 1
marked_failed = 0
for attachment in plan.missing:
action = 'MARK_MISSING' if apply else 'WOULD_MARK_MISSING'
output(
f'{action} attachment_id={attachment.id} key={attachment.object_key} '
f'updated={attachment.updated_at.isoformat()}'
)
if not apply:
output(
f'WOULD_MARK_MISSING attachment_id={attachment.id} '
f'key={attachment.object_key} updated={attachment.updated_at.isoformat()}'
)
continue
# The object may have been restored after list_objects(). Do not turn
# healthy metadata into failed based only on the earlier snapshot.
if await storage.exists(attachment.object_key):
output(
f'SKIP_MISSING_OBJECT_RESTORED attachment_id={attachment.id} '
f'key={attachment.object_key}'
)
race_protected += 1
continue
if apply and plan.missing:
async with sessions() as session:
async with session.begin():
result = await session.execute(
update(AttachmentRow)
.where(
AttachmentRow.id.in_([item.id for item in plan.missing]),
AttachmentRow.id == attachment.id,
AttachmentRow.object_key == attachment.object_key,
AttachmentRow.status == 'ready',
AttachmentRow.updated_at == attachment.updated_at,
)
.values(
status='failed',
@@ -143,7 +175,19 @@ async def reconcile(
updated_at=current_time,
)
)
marked_failed = result.rowcount or 0
changed = result.rowcount or 0
if changed:
output(
f'MARK_MISSING attachment_id={attachment.id} '
f'key={attachment.object_key} updated={attachment.updated_at.isoformat()}'
)
marked_failed += changed
else:
output(
f'SKIP_MISSING_METADATA_CHANGED attachment_id={attachment.id} '
f'key={attachment.object_key}'
)
race_protected += 1
_, peak_bytes = tracemalloc.get_traced_memory()
tracemalloc.stop()
@@ -157,6 +201,7 @@ async def reconcile(
'fresh_protected': len(plan.fresh_orphan) + len(plan.fresh_missing),
'removed': removed,
'marked_failed': marked_failed,
'race_protected': race_protected,
'grace_seconds': grace_seconds,
'elapsed_ms': round((time.perf_counter() - started) * 1000, 3),
'peak_memory_bytes': peak_bytes,