forked from mtusi2026/mtusi2026lab4
feat: compensate failed uploads and clean stale pending attachments
- upload: delete the stored object when ready fails before COMMIT or the pending row is gone (503 instead of 500); unknown COMMIT outcome keeps it - cleaner service (python -m src.cleaner): stale pending rows older than grace (900 s, must exceed 17 s live-upload bound) under FOR UPDATE SKIP LOCKED, object before row, own S3 user with read/delete only - shared session_scope for API and cleaner; early_stop process name - partial index on pending attachments, CREATE INDEX CONCURRENTLY - s3-bootstrap: cleaner user, policy and checks; make env_setup appends missing template variables to an existing .env - failure checks: cleaner on the failure stand, id-list hook actions, five new and three updated tests; driver upload-consistency - sync upload-consistency deltas into main specs (storage-consistency) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -88,9 +88,11 @@ class AttachmentService:
|
||||
Порядок проверок — спек «Порядок проверок загрузки»: членство
|
||||
(404), `Content-Type` (415), `Content-Length` (413), затем тело со
|
||||
счётчиком (413) и содержимое (415 или 413). Порядок записи
|
||||
(решение 1): строка `pending` с ключом объекта — commit, PUT,
|
||||
`ready` — commit. Отказ S3 или БД после строки `pending` — 503,
|
||||
строка остаётся до уборщика (`upload-consistency`).
|
||||
(design change `attachments`, решение 1): строка `pending` с
|
||||
ключом объекта — commit, PUT, `ready` — commit. Отказ S3 или БД
|
||||
после строки `pending` — 503, строка остаётся до уборщика;
|
||||
компенсация после записанного объекта — `_mark_ready` (design
|
||||
change `upload-consistency`, решение 1).
|
||||
"""
|
||||
started = time.monotonic()
|
||||
log = logger.bind(
|
||||
@@ -157,26 +159,26 @@ class AttachmentService:
|
||||
attachment=pending,
|
||||
)
|
||||
await db_session.commit()
|
||||
await attachment_object_repo.put_original(
|
||||
self.storage,
|
||||
key=pending.object_key,
|
||||
data=data,
|
||||
content_type=pending.content_type.value,
|
||||
)
|
||||
async with self.db_scope() as db_session:
|
||||
ready = await attachment_repo.mark_ready(
|
||||
db_session=db_session,
|
||||
attachment_id=attachment_id,
|
||||
updated_at=utcnow(),
|
||||
log = log.bind(attachment_id=attachment_id)
|
||||
try:
|
||||
await attachment_object_repo.put_original(
|
||||
self.storage,
|
||||
key=pending.object_key,
|
||||
data=data,
|
||||
content_type=pending.content_type.value,
|
||||
)
|
||||
await db_session.commit()
|
||||
if ready is None:
|
||||
# строку pending удалить некому, пока нет уборщика: ветку
|
||||
# переопределит change upload-consistency
|
||||
raise RuntimeError("Pending attachment disappeared before ready")
|
||||
except Exception:
|
||||
# объект не трогаем: при замороженном S3 удаление ждало бы ещё
|
||||
# срок вызова, а тело без ответа сервера не уходит (решение 1)
|
||||
log.warning("Attachment upload left pending", step="put")
|
||||
raise
|
||||
ready = await self._mark_ready(
|
||||
attachment_id=attachment_id,
|
||||
object_key=pending.object_key,
|
||||
log=log,
|
||||
)
|
||||
log.info(
|
||||
"Uploaded attachment",
|
||||
attachment_id=attachment_id,
|
||||
size_bytes=ready.size_bytes,
|
||||
content_type=ready.content_type,
|
||||
width=info.width,
|
||||
@@ -185,6 +187,71 @@ class AttachmentService:
|
||||
)
|
||||
return ready
|
||||
|
||||
async def _mark_ready(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
object_key: str,
|
||||
log: AbstractLogger,
|
||||
) -> dataclasses.AttachmentFullDTO:
|
||||
"""`pending` → `ready` после записанного объекта (решение 1).
|
||||
|
||||
Сбой до отправки COMMIT — вложение `ready` не станет: объект
|
||||
удаляется до ответа (без гарантии), строку убирает уборщик. Сбой
|
||||
на самом COMMIT — исход неизвестен, объект не трогается. Строки
|
||||
`pending` уже нет (её убрал уборщик: загрузка пережила grace) —
|
||||
объект удаляется, ответ 503.
|
||||
"""
|
||||
# True — COMMIT ушёл в PostgreSQL, и вложение могло стать ready
|
||||
commit_sent = False
|
||||
try:
|
||||
async with self.db_scope() as db_session:
|
||||
ready = await attachment_repo.mark_ready(
|
||||
db_session=db_session,
|
||||
attachment_id=attachment_id,
|
||||
updated_at=utcnow(),
|
||||
)
|
||||
commit_sent = ready is not None
|
||||
await db_session.commit()
|
||||
except Exception:
|
||||
# CancelledError сюда не попадает: при отмене задачи await
|
||||
# ненадёжен, остаток убирает уборщик
|
||||
step = "commit" if commit_sent else "ready"
|
||||
log.warning("Attachment upload left pending", step=step)
|
||||
if not commit_sent:
|
||||
await self._compensate(object_key=object_key, log=log)
|
||||
raise
|
||||
if ready is None:
|
||||
log.error("Pending attachment was removed before ready")
|
||||
await self._compensate(object_key=object_key, log=log)
|
||||
raise exceptions.ServiceUnavailable
|
||||
return ready
|
||||
|
||||
async def _compensate(
|
||||
self,
|
||||
*,
|
||||
object_key: str,
|
||||
log: AbstractLogger,
|
||||
) -> None:
|
||||
"""Удалить объект загрузки, которая не станет `ready`; без повторов.
|
||||
|
||||
Не удалось — `warning`, исходная ошибка загрузки уходит дальше, а
|
||||
объект вместе со строкой убирает уборщик.
|
||||
"""
|
||||
try:
|
||||
await attachment_object_repo.delete_original(
|
||||
self.storage,
|
||||
key=object_key,
|
||||
)
|
||||
except Exception as e:
|
||||
log.warning(
|
||||
"Attachment object kept for cleaner",
|
||||
object_key=object_key,
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
return
|
||||
log.info("Deleted attachment object", object_key=object_key)
|
||||
|
||||
async def _read_body(
|
||||
self,
|
||||
*,
|
||||
|
||||
Reference in New Issue
Block a user