Compensate failed uploads and sweep abandoned intents

When the ready commit fails after the object was written, the upload
handler now locks the row, keeps it if it turned out ready, and
otherwise deletes the object first and the pending row second before
answering 503. A ready update that touches no row means the intent was
already swept, so it fails as unavailable and the object goes too;
a 201 without a row cannot happen.

Every worker runs an UploadSweeper that every 30 s removes pending
intents older than UPLOAD_GRACE_SECONDS (900 s, at least 60 s) one row
at a time under FOR UPDATE SKIP LOCKED over the partial pending index,
object first, and logs an audit event for each discard. Bodies are
buffered only inside one of UPLOAD_CONCURRENCY slots per worker and
released before the ready commit, and a client that disconnects in the
middle of a body becomes a 400 instead of an unhandled 500.

The tests run against a throwaway PostgreSQL: a trigger rejects the
ready commit and the compensation leaves neither row nor object, a
row removed during the write gives 503, a failed write stays until the
grace ends, fresh intents and an aged ready attachment in a message
survive a sweep, two concurrent sweeps share five intents exactly, the
background loop runs by itself, a second upload waits for the slot
without reading its body, and aborted and stalled bodies leave nothing.

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:
Artyom
2026-10-28 22:39:51 +03:00
co-authored by Claude Opus 5.5
parent 70a0c6065e
commit 0e4eb1738c
19 changed files with 538 additions and 33 deletions
@@ -1,5 +1,6 @@
from collections.abc import AsyncIterator
from dataclasses import dataclass
from datetime import timedelta
from uuid import UUID
from messenger.shared.application.commands import Command
@@ -12,3 +13,9 @@ class UploadAttachment(Command):
filename: str | None
content_type: str | None
body: AsyncIterator[bytes]
@dataclass(frozen=True, slots=True)
class SweepAbandonedUploads(Command):
grace: timedelta
limit: int
@@ -1,7 +1,8 @@
import asyncio
from collections.abc import AsyncIterator
from hashlib import sha256
from messenger.attachments.application.commands import UploadAttachment
from messenger.attachments.application.commands import SweepAbandonedUploads, UploadAttachment
from messenger.attachments.application.ports import (
AttachmentsUnitOfWork,
ChatMembership,
@@ -9,9 +10,13 @@ from messenger.attachments.application.ports import (
ObjectStorage,
)
from messenger.attachments.domain.errors import ChatNotFound, PayloadTooLarge
from messenger.attachments.domain.models import Attachment
from messenger.attachments.domain.models import Attachment, AttachmentStatus
from messenger.attachments.domain.values import Filename, ImageKind
from messenger.shared.application.ports import Clock, IdGenerator
from messenger.shared.application.ports import Clock, IdGenerator, Logger
class UploadSlots(asyncio.Semaphore):
pass
async def read_limited(body: AsyncIterator[bytes], limit: int) -> tuple[bytes, str]:
@@ -27,8 +32,27 @@ async def read_limited(body: AsyncIterator[bytes], limit: int) -> tuple[bytes, s
return b"".join(chunks), digest.hexdigest()
async def drop(
uow: AttachmentsUnitOfWork, storage: ObjectStorage, attachment: Attachment, reason: str
) -> None:
await storage.delete(attachment.object_key)
attachment.discard(reason)
await uow.attachments.remove(attachment)
await uow.commit()
class UploadAttachmentHandler:
__slots__ = ("_clock", "_ids", "_images", "_limit", "_membership", "_storage", "_uow")
__slots__ = (
"_clock",
"_ids",
"_images",
"_limit",
"_logger",
"_membership",
"_slots",
"_storage",
"_uow",
)
def __init__(
self,
@@ -40,6 +64,8 @@ class UploadAttachmentHandler:
clock: Clock,
ids: IdGenerator,
limit: int,
slots: UploadSlots,
logger: Logger,
) -> None:
self._uow = uow
self._membership = membership
@@ -48,12 +74,29 @@ class UploadAttachmentHandler:
self._clock = clock
self._ids = ids
self._limit = limit
self._slots = slots
self._logger = logger
async def __call__(self, command: UploadAttachment) -> Attachment:
if not await self._membership.is_member(command.chat_id, command.owner_id):
raise ChatNotFound("чат не найден")
filename = Filename(command.filename or "")
declared = ImageKind.declared(command.content_type)
async with self._slots:
attachment = await self._write(command, filename, declared)
attachment.store(self._clock.now())
try:
async with self._uow.transaction():
await self._uow.attachments.save(attachment)
await self._uow.commit()
except Exception:
await self._compensate(attachment)
raise
return attachment
async def _write(
self, command: UploadAttachment, filename: Filename, declared: ImageKind
) -> Attachment:
data, digest = await read_limited(command.body, self._limit)
image = await self._images.inspect(data, declared)
attachment = Attachment.stage(
@@ -70,8 +113,38 @@ class UploadAttachmentHandler:
await self._uow.attachments.add(attachment)
await self._uow.commit()
await self._storage.put(attachment.object_key, data, attachment.content_type)
attachment.store(self._clock.now())
async with self._uow.transaction():
await self._uow.attachments.save(attachment)
await self._uow.commit()
return attachment
async def _compensate(self, staged: Attachment) -> None:
try:
async with self._uow.transaction():
current = await self._uow.attachments.lock(staged.id)
if current is None:
await self._storage.delete(staged.object_key)
elif current.status is AttachmentStatus.PENDING:
await drop(self._uow, self._storage, current, "compensation")
except Exception as error:
self._logger.warning(
"attachment.compensation_failed",
attachment_id=str(staged.id),
error=type(error).__name__,
)
class SweepAbandonedUploadsHandler:
__slots__ = ("_clock", "_storage", "_uow")
def __init__(self, uow: AttachmentsUnitOfWork, storage: ObjectStorage, clock: Clock) -> None:
self._uow = uow
self._storage = storage
self._clock = clock
async def __call__(self, command: SweepAbandonedUploads) -> int:
before = self._clock.now() - command.grace
for swept in range(command.limit):
async with self._uow.transaction():
abandoned = await self._uow.attachments.next_abandoned(before)
if abandoned is None:
return swept
await drop(self._uow, self._storage, abandoned, "abandoned")
return command.limit
@@ -1,5 +1,6 @@
from collections.abc import AsyncIterator
from dataclasses import dataclass
from datetime import datetime
from typing import Protocol, runtime_checkable
from uuid import UUID
@@ -39,6 +40,12 @@ class AttachmentRepository(Protocol):
async def save(self, attachment: Attachment) -> None: ...
async def lock(self, attachment_id: UUID) -> Attachment | None: ...
async def next_abandoned(self, before: datetime) -> Attachment | None: ...
async def remove(self, attachment: Attachment) -> None: ...
@runtime_checkable
class AttachmentsUnitOfWork(UnitOfWork, Protocol):
+4
View File
@@ -18,3 +18,7 @@ class AttachmentsSettings(Settings):
max_upload_bytes: int = Field(default=UPLOAD_BYTES_MAX, ge=1, le=UPLOAD_BYTES_MAX)
max_image_pixels: int = Field(default=IMAGE_PIXELS_MAX, ge=1, le=IMAGE_PIXELS_MAX)
image_check_concurrency: int = Field(default=2, ge=1, le=16)
upload_concurrency: int = Field(default=3, ge=1, le=64)
upload_grace_seconds: int = Field(default=900, ge=60)
upload_sweep_interval_seconds: float = Field(default=30.0, gt=0)
upload_sweep_batch: int = Field(default=100, ge=1, le=10_000)
@@ -23,3 +23,7 @@ class ChatNotFound(AttachmentError):
class AttachmentNotFound(AttachmentError):
pass
class UploadAborted(AttachmentError):
pass
@@ -11,3 +11,11 @@ class AttachmentStored(DomainEvent):
owner_id: UUID
size_bytes: int
name: str = field(init=False, default="attachment.stored")
@dataclass(frozen=True, slots=True)
class AttachmentDiscarded(DomainEvent):
attachment_id: UUID
chat_id: UUID
reason: str
name: str = field(init=False, default="attachment.discarded")
+6 -1
View File
@@ -3,7 +3,7 @@ from datetime import datetime
from enum import StrEnum
from uuid import UUID
from messenger.attachments.domain.events import AttachmentStored
from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentStored
from messenger.attachments.domain.values import Filename, ImageInfo
from messenger.shared.domain.events import DomainEvent
@@ -73,6 +73,11 @@ class Attachment:
)
)
def discard(self, reason: str) -> None:
self._events.append(
AttachmentDiscarded(attachment_id=self.id, chat_id=self.chat_id, reason=reason)
)
def collect_events(self) -> list[DomainEvent]:
events, self._events = self._events, []
return events
@@ -4,11 +4,13 @@ from messenger.attachments.domain.errors import (
InvalidFilename,
PayloadTooLarge,
UnsupportedImage,
UploadAborted,
)
from messenger.shared.domain.errors import DomainError
ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
InvalidFilename: ("invalid_request", 400),
UploadAborted: ("invalid_request", 400),
ChatNotFound: ("not_found", 404),
AttachmentNotFound: ("not_found", 404),
PayloadTooLarge: ("payload_too_large", 413),
+12 -1
View File
@@ -1,14 +1,17 @@
import re
from collections.abc import AsyncIterator
from typing import Annotated, Literal
from uuid import UUID
from dishka.integrations.fastapi import FromDishka, inject
from fastapi import APIRouter, Query, Request, status
from fastapi.responses import StreamingResponse
from starlette.requests import ClientDisconnect
from messenger.attachments.application.bus import AttachmentsCommandBus
from messenger.attachments.application.commands import UploadAttachment
from messenger.attachments.application.queries import GetAttachment, OpenAttachment
from messenger.attachments.domain.errors import UploadAborted
from messenger.attachments.entrypoints.schemas import AttachmentOut
from messenger.shared.entrypoints.actor import Actor
@@ -19,6 +22,14 @@ uploads_router = APIRouter(prefix="/api/v1/chats/{chat_id}/attachments", tags=["
attachments_router = APIRouter(prefix="/api/v1/attachments", tags=["attachments"])
async def body_of(request: Request) -> AsyncIterator[bytes]:
try:
async for chunk in request.stream():
yield chunk
except ClientDisconnect as error:
raise UploadAborted("клиент оборвал загрузку до конца тела") from error
@uploads_router.post("", status_code=status.HTTP_201_CREATED)
@inject
async def upload_attachment(
@@ -34,7 +45,7 @@ async def upload_attachment(
chat_id=chat_id,
filename=filename,
content_type=request.headers.get("content-type"),
body=request.stream(),
body=body_of(request),
)
)
return AttachmentOut.of(attachment)
+26 -5
View File
@@ -3,8 +3,12 @@ from collections.abc import AsyncIterator
from dishka import Provider, Scope, provide
from messenger.attachments.application.bus import AttachmentsCommandBus
from messenger.attachments.application.commands import UploadAttachment
from messenger.attachments.application.handlers import UploadAttachmentHandler
from messenger.attachments.application.commands import SweepAbandonedUploads, UploadAttachment
from messenger.attachments.application.handlers import (
SweepAbandonedUploadsHandler,
UploadAttachmentHandler,
UploadSlots,
)
from messenger.attachments.application.ports import (
AttachmentDirectory,
AttachmentsUnitOfWork,
@@ -52,6 +56,10 @@ class AttachmentsProvider(Provider):
def images(self, settings: AttachmentsSettings) -> ImageInspector:
return PillowImageInspector(settings.max_image_pixels, settings.image_check_concurrency)
@provide(scope=Scope.APP)
def slots(self, settings: AttachmentsSettings) -> UploadSlots:
return UploadSlots(settings.upload_concurrency)
@provide(scope=Scope.APP)
def directory(self, database: Database) -> AttachmentDirectory:
return PostgresAttachmentDirectory(database)
@@ -83,9 +91,22 @@ class AttachmentsProvider(Provider):
clock: Clock,
ids: IdGenerator,
settings: AttachmentsSettings,
slots: UploadSlots,
logger: Logger,
) -> AttachmentsCommandBus:
handler = UploadAttachmentHandler(
uow, membership, images, storage, clock=clock, ids=ids, limit=settings.max_upload_bytes
upload = UploadAttachmentHandler(
uow,
membership,
images,
storage,
clock=clock,
ids=ids,
limit=settings.max_upload_bytes,
slots=slots,
logger=logger,
)
handlers: dict[type[Command], CommandHandler] = {UploadAttachment: handler}
handlers: dict[type[Command], CommandHandler] = {
UploadAttachment: upload,
SweepAbandonedUploads: SweepAbandonedUploadsHandler(uow, storage, clock),
}
return AttachmentsCommandBus(handlers, uow, publisher)
@@ -1,7 +1,7 @@
from messenger.attachments.domain.events import AttachmentStored
from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentStored
from messenger.shared.application.ports import Logger
LOG_FIELDS = frozenset({"attachment_id", "chat_id", "actor_id", "size_bytes"})
LOG_FIELDS = frozenset({"attachment_id", "chat_id", "actor_id", "size_bytes", "count"})
class AttachmentsJournal:
@@ -18,3 +18,11 @@ class AttachmentsJournal:
actor_id=str(event.owner_id),
size_bytes=event.size_bytes,
)
async def on_attachment_discarded(self, event: AttachmentDiscarded) -> None:
self._logger.info(
"audit.attachment_discarded",
attachment_id=str(event.attachment_id),
chat_id=str(event.chat_id),
reason=event.reason,
)
@@ -0,0 +1,53 @@
import asyncio
from contextlib import suppress
from datetime import timedelta
from dishka import AsyncContainer
from messenger.attachments.application.bus import AttachmentsCommandBus
from messenger.attachments.application.commands import SweepAbandonedUploads
from messenger.attachments.config import AttachmentsSettings
from messenger.shared.application.ports import Logger
class UploadSweeper:
__slots__ = ("_command", "_container", "_interval", "_logger", "_task")
def __init__(
self, container: AsyncContainer, settings: AttachmentsSettings, logger: Logger
) -> None:
self._container = container
self._logger = logger
self._interval = settings.upload_sweep_interval_seconds
self._command = SweepAbandonedUploads(
grace=timedelta(seconds=settings.upload_grace_seconds),
limit=settings.upload_sweep_batch,
)
self._task: asyncio.Task[None] | None = None
def start(self) -> None:
self._task = asyncio.create_task(self._run())
async def stop(self) -> None:
if self._task is None:
return
self._task.cancel()
with suppress(asyncio.CancelledError):
await self._task
self._task = None
async def sweep(self) -> int:
async with self._container() as scope:
bus = await scope.get(AttachmentsCommandBus)
return await bus.execute(self._command)
async def _run(self) -> None:
while True:
await asyncio.sleep(self._interval)
try:
swept = await self.sweep()
except Exception as error:
self._logger.warning("attachments.sweep_failed", error=type(error).__name__)
continue
if swept:
self._logger.info("attachments.swept", count=swept)
@@ -1,3 +1,4 @@
from datetime import datetime
from uuid import UUID
from asyncpg import ForeignKeyViolationError, Record
@@ -5,6 +6,7 @@ from asyncpg import ForeignKeyViolationError, Record
from messenger.attachments.domain.errors import ChatNotFound
from messenger.attachments.domain.models import Attachment, AttachmentStatus
from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind
from messenger.shared.application.errors import Unavailable
from messenger.shared.infrastructure.postgres import (
Connection,
Database,
@@ -18,12 +20,19 @@ INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_byt
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'"
READY = """
COLUMNS = """
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height,
object_key, status, created_at, updated_at
FROM attachments
WHERE id = $1 AND status = 'ready'
"""
READY = COLUMNS + "WHERE id = $1 AND status = 'ready'"
LOCK = COLUMNS + "WHERE id = $1 FOR UPDATE"
ABANDONED = (
COLUMNS
+ """WHERE status = 'pending' AND created_at < $1
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED"""
)
REMOVE = "DELETE FROM attachments WHERE id = $1 AND status = 'pending'"
def attachment_of(row: Record) -> Attachment:
@@ -72,9 +81,23 @@ class PostgresAttachmentRepository:
self._seen.append(attachment)
async def save(self, attachment: Attachment) -> None:
await self._connection.execute(
done = await self._connection.execute(
MARK, attachment.id, attachment.status.value, attachment.updated_at
)
if done == "UPDATE 0":
raise Unavailable("намерение загрузки уже снято уборкой")
self._seen.append(attachment)
async def lock(self, attachment_id: UUID) -> Attachment | None:
row = await self._connection.fetchrow(LOCK, attachment_id)
return None if row is None else attachment_of(row)
async def next_abandoned(self, before: datetime) -> Attachment | None:
row = await self._connection.fetchrow(ABANDONED, before)
return None if row is None else attachment_of(row)
async def remove(self, attachment: Attachment) -> None:
await self._connection.execute(REMOVE, attachment.id)
self._seen.append(attachment)
+7 -1
View File
@@ -8,12 +8,13 @@ from fastapi import FastAPI
from messenger.attachments.application.ports import ChatMembership
from messenger.attachments.config import AttachmentsSettings
from messenger.attachments.domain.events import AttachmentStored
from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentStored
from messenger.attachments.entrypoints.errors import ERROR_CODES as ATTACHMENT_ERRORS
from messenger.attachments.entrypoints.http import UPLOAD_PATH, attachments_router, uploads_router
from messenger.attachments.entrypoints.ioc import AttachmentsProvider
from messenger.attachments.entrypoints.journal import LOG_FIELDS as ATTACHMENT_FIELDS
from messenger.attachments.entrypoints.journal import AttachmentsJournal
from messenger.attachments.entrypoints.sweeper import UploadSweeper
from messenger.identity.config import IdentitySettings
from messenger.identity.domain.events import SessionClosed, SessionOpened, UserRegistered
from messenger.identity.entrypoints.authentication import challenge_for, guard
@@ -76,6 +77,7 @@ def wire_events(bus: EventBus, logger: Logger) -> None:
attachments = AttachmentsJournal(logger)
bus.subscribe(AttachmentStored, attachments.on_attachment_stored)
bus.subscribe(AttachmentDiscarded, attachments.on_attachment_discarded)
def create_app(
@@ -102,16 +104,19 @@ def create_app(
FastapiProvider(),
*overrides,
)
sweeper = UploadSweeper(container, attachments, logger)
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
bus = await container.get(EventBus)
wire_events(bus, logger)
bus.start()
sweeper.start()
logger.info("service.started")
try:
yield
finally:
await sweeper.stop()
await bus.stop()
await container.close()
logger.info("service.stopped")
@@ -142,4 +147,5 @@ def create_app(
app.include_router(uploads_router)
app.include_router(attachments_router)
setup_dishka(container, app)
app.state.sweeper = sweeper
return app