Reconcile attachment metadata with the bucket in one merge pass
StorageReconciler walks the sorted bucket listing and keyset pages of attachments ordered by object key side by side, so a pass is linear and keeps one page of each side in memory. An object without a row is deleted only when it is older than grace plus skew and a lookup by key right before the delete still finds no row; a ready row whose object is missing, has another size or, with the deep check, another digest is put in quarantine after a HEAD recheck and is never deleted; a stale intent is claimed with SKIP LOCKED and dropped object first; a quarantined row whose object matches again is released. Deep checks hash objects in a bounded task group, each action uses its own unit of work, and failures of single actions are counted instead of aborting. An advisory lock lets one pass run at a time. Content of a quarantined attachment answers 404 without touching S3, its metadata is unchanged. The storage port gains listing pages and HEAD, the repository keyset pages, lookup by key, claim and quarantine marking; the platform logger can write to another stream. The one-off entry point python -m messenger.attachments.entrypoints.reconcile is a dry run unless --apply is given, assembles the adapters with the API key of S3 and prints a JSON report with counts per class, samples and the cost of the pass to stdout while the journal goes to stderr. Tests run the reconciler against its own migrated database with every class, apply and repeat, the row that appears after the listing, the busy lock and the release, and check paged byte-order listing and HEAD against RustFS. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
62986245a2
commit
91731fd317
@@ -1,10 +1,12 @@
|
||||
from collections.abc import AsyncIterator, Sequence
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import ForeignKeyViolationError, Record
|
||||
|
||||
from messenger.attachments.domain.errors import ChatNotFound
|
||||
from messenger.attachments.domain.models import Attachment, AttachmentStatus
|
||||
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 (
|
||||
@@ -22,7 +24,7 @@ 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
|
||||
object_key, status, created_at, updated_at, quarantine_reason
|
||||
FROM attachments
|
||||
"""
|
||||
READY = COLUMNS + "WHERE id = $1 AND status = 'ready'"
|
||||
@@ -33,6 +35,15 @@ ABANDONED = (
|
||||
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED"""
|
||||
)
|
||||
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'
|
||||
"""
|
||||
|
||||
|
||||
def attachment_of(row: Record) -> Attachment:
|
||||
@@ -48,6 +59,7 @@ def attachment_of(row: Record) -> Attachment:
|
||||
status=AttachmentStatus(row["status"]),
|
||||
created_at=row["created_at"],
|
||||
updated_at=row["updated_at"],
|
||||
quarantine=Quarantine(row["quarantine_reason"]) if row["quarantine_reason"] else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -100,6 +112,21 @@ class PostgresAttachmentRepository:
|
||||
await self._connection.execute(REMOVE, attachment.id)
|
||||
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)]
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork):
|
||||
__slots__ = ()
|
||||
@@ -119,3 +146,21 @@ class PostgresAttachmentDirectory:
|
||||
async with self._database.connection() as connection:
|
||||
row = await connection.fetchrow(READY, attachment_id)
|
||||
return None if row is None else attachment_of(row)
|
||||
|
||||
|
||||
class PostgresSingleRun:
|
||||
__slots__ = ("_database", "_key")
|
||||
|
||||
def __init__(self, database: Database, key: int) -> None:
|
||||
self._database = database
|
||||
self._key = key
|
||||
|
||||
@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)
|
||||
try:
|
||||
yield held
|
||||
finally:
|
||||
if held:
|
||||
await connection.fetchval("SELECT pg_advisory_unlock($1)", self._key)
|
||||
|
||||
Reference in New Issue
Block a user