lab5 API: upload 202 queued через staging + задание + outbox одной транзакцией

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Порядок: pending-намерение -> PUT в приватный staging bucket -> COMMIT queued + jobs + outbox
-> 202. Проверки 413/415 lab4 остаются синхронными. GET видит queued/processing/failed,
content: 409 до ready, варианты thumbnail/crop/optimized; к сообщению можно прикрепить
queued/processing, failed -> 409. API не связан с брокером.
This commit is contained in:
Alexey Bodanyuk
2026-10-31 16:12:52 +03:00
parent a633949919
commit 655f264104
6 changed files with 176 additions and 104 deletions
+86 -47
View File
@@ -1,26 +1,29 @@
"""Attachments (lab 4): metadata in PostgreSQL, original bytes in the private S3 bucket.
"""Attachments: metadata in PostgreSQL, bytes in private S3 buckets (lab 4), processed
asynchronously by the worker (lab 5, docs/PIPELINE.md).
Upload (POST /chats/{id}/attachments, raw PNG/JPEG body), in this order:
auth -> membership (404) -> filename / Content-Type / Content-Length (400/415/413)
-> upload slot (at most UPLOAD_CONCURRENCY bodies per replica, else 503 + Retry-After)
-> body in chunks: size limit, read deadline, format + pixel count from the first bytes
-> full integrity check (images.verify) -> SHA-256 / size known
-> INSERT row status='pending' with a fresh random object_key, COMMIT (intent)
-> PUT object to S3 (Content-MD5)
-> UPDATE status='ready' WHERE status='pending', COMMIT -> 201 ready.
-> full integrity check (images.verify) -> SHA-256 / size known (415 is decided HERE)
-> INSERT row status='pending' with a fresh random staging key, COMMIT (intent)
-> PUT the original into the STAGING bucket (Content-MD5)
-> ONE transaction: status 'pending' -> 'queued' + jobs row + outbox row, COMMIT
-> 202 queued.
Why 201 is honest: it is sent only after BOTH the object and the ready row are durable.
What a failure between the steps leaves behind, and who removes it (docs/CONSISTENCY.md):
What is durable at 202: the complete, verified original in the staging bucket (S3 confirmed the
PUT and its MD5), the metadata row, the job and the outbox row that makes the relay publish it.
A crash of the API after the answer loses nothing; a broker that is down only delays the publish.
* before the intent COMMIT: nothing (no object was written);
* after the intent, before/while PUT, before the ready COMMIT: a 'pending' row (+ maybe the
object). The client got 503 and may retry (a new attachment). The janitor (below) deletes the
object - idempotent, a missing key is fine - and then the row, once it is older than
PENDING_GRACE_SECONDS. Nothing is compensated in the request path: after a lost answer of
COMMIT we do not know whether the row is ready, and deleting the object could destroy a
ready attachment. Only the janitor decides, under a row lock, from the committed state;
* after the ready COMMIT (answer lost): a correct ready attachment the client does not know.
Failures between the steps (docs/PIPELINE.md, failure windows):
* before the intent COMMIT: nothing was written;
* after the intent, before/while PUT, or between PUT and the job COMMIT (FAULT_POINTS=after_s3_put):
a 'pending' row (+ maybe the staging object), invisible to everybody (404). The client got 503
and may retry (a new attachment). The janitor deletes the staging object - idempotent - and then
the row once it is older than PENDING_GRACE_SECONDS, deciding under the row lock;
* after the job COMMIT, answer lost (FAULT_POINTS=after_enqueue_commit): a correct queued
attachment the client does not know; the worker processes it as usual.
"""
from __future__ import annotations
@@ -36,11 +39,11 @@ import psycopg
from psycopg import errors as pg_errors
from starlette.requests import Request
from . import images
from . import images, jobs
from .config import Settings
from .db import Database
from .errors import ApiError, InvalidRequest, NotFound, PayloadTooLarge, Unavailable, UnsupportedMediaType
from .storage import OBJECT_PREFIX, Storage
from .storage import STAGING_PREFIX, Storage
from .timefmt import rfc3339
log = logging.getLogger("messenger.attachments")
@@ -48,6 +51,21 @@ log = logging.getLogger("messenger.attachments")
JANITOR_LOCK_ID = 2026_04 # advisory lock: one janitor round at a time across all replicas
@dataclass(frozen=True, slots=True)
class Variant:
name: str
content_type: str
size_bytes: int
width: int
height: int
sha256: str
object_key: str
def to_json(self) -> dict:
return {"name": self.name, "content_type": self.content_type, "size_bytes": self.size_bytes,
"width": self.width, "height": self.height, "sha256": self.sha256}
@dataclass(frozen=True, slots=True)
class Attachment:
id: str
@@ -57,100 +75,121 @@ class Attachment:
content_type: str
size_bytes: int
sha256: str
object_key: str
object_key: str | None # published original in the final bucket (None until the worker publishes it)
status: str
created_at: dt.datetime
updated_at: dt.datetime
lost: bool = False
error_code: str | None = None
published_version: int | None = None
variants: tuple[Variant, ...] = ()
def to_json(self) -> dict:
"""Public representation: no object key, no bucket, no internal state."""
"""Public representation: no object keys, no buckets, no job internals."""
return {"id": self.id, "chat_id": self.chat_id, "owner_id": self.owner_id, "filename": self.filename,
"content_type": self.content_type, "size_bytes": self.size_bytes, "sha256": self.sha256,
"status": "ready", "variants": [], "error_code": None,
"status": self.status, "variants": [v.to_json() for v in self.variants] if self.status == "ready" else [],
"error_code": self.error_code if self.status == "failed" else None,
"created_at": rfc3339(self.created_at), "updated_at": rfc3339(self.updated_at)}
def variant(self, name: str) -> Variant | None:
return next((v for v in self.variants if v.name == name), None)
COLUMNS = ("a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.object_key, "
"a.status, a.created_at, a.updated_at, a.lost_at IS NOT NULL")
"a.status, a.created_at, a.updated_at, a.lost_at IS NOT NULL, a.error_code, a.published_version")
def _attachment(row) -> Attachment:
def _attachment(row, variants: tuple[Variant, ...] = ()) -> Attachment:
return Attachment(str(row[0]), str(row[1]), str(row[2]), row[3], row[4], row[5], bytes(row[6]).hex(), row[7],
row[8], row[9], row[10], row[11])
row[8], row[9], row[10], row[11], row[12], row[13], variants)
def new_object_key() -> str:
def new_staging_key() -> str:
"""Server-generated, 128 random bits, unrelated to the attachment id and the filename."""
return OBJECT_PREFIX + secrets.token_hex(16)
return STAGING_PREFIX + secrets.token_hex(16)
# ------------------------------------------------------------------ SQL
async def create_intent(db: Database, attachment_id: uuid.UUID, chat_id: str, owner_id: str, filename: str,
info: images.ImageInfo, size: int, sha256: bytes, object_key: str) -> None:
info: images.ImageInfo, size: int, sha256: bytes, staging_key: str) -> None:
async def work(conn: psycopg.AsyncConnection) -> None:
await conn.execute(
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
"width, height, object_key, status) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'pending')",
"width, height, staging_key, staging_state, status) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'present', 'pending')",
(attachment_id, chat_id, owner_id, filename, info.content_type, size, sha256, info.width, info.height,
object_key))
staging_key))
try:
await db.run(work, transaction=False)
except pg_errors.ForeignKeyViolation:
raise NotFound("Чат не найден") from None
async def mark_ready(db: Database, attachment_id: uuid.UUID) -> Attachment | None:
"""pending -> ready. None if the row is no longer pending (the janitor removed a stale intent)."""
async def enqueue(db: Database, attachment_id: uuid.UUID, settings: Settings) -> Attachment | None:
"""pending -> queued + job + outbox row in ONE transaction (the durable handoff before 202).
None if the row is no longer pending (the janitor removed a stale intent)."""
async def work(conn: psycopg.AsyncConnection) -> Attachment | None:
cur = await conn.execute(
"UPDATE attachments a SET status = 'ready', updated_at = clock_timestamp() "
"UPDATE attachments a SET status = 'queued', updated_at = clock_timestamp() "
f"WHERE a.id = %s AND a.status = 'pending' RETURNING {COLUMNS}", (attachment_id,))
row = await cur.fetchone()
return _attachment(row) if row else None
return await db.run(work, transaction=False)
if row is None:
return None
await jobs.create_job(conn, attachment_id, settings.pipeline_version, "upload", settings.job_max_attempts,
"api:" + settings.instance_id)
return _attachment(row)
return await db.run(work)
async def get_visible(db: Database, user_id: str, attachment_id: str) -> Attachment:
"""A READY attachment of a chat the user is a member of; anything else is 404 (unknown,
foreign chat, unfinished upload) - existence of foreign objects is never revealed."""
"""An attachment of a chat the user is a member of, in any state but the invisible intent
'pending'; anything else is 404 (unknown, foreign chat, unfinished upload) - existence of
foreign objects is never revealed. A ready attachment comes with its published variants."""
async def work(conn: psycopg.AsyncConnection) -> Attachment:
cur = await conn.execute(
f"SELECT {COLUMNS} FROM attachments a "
"JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = %s "
"WHERE a.id = %s AND a.status = 'ready'", (user_id, attachment_id))
"WHERE a.id = %s AND a.status <> 'pending'", (user_id, attachment_id))
row = await cur.fetchone()
if row is None:
raise NotFound("Вложение не найдено")
return _attachment(row)
return await db.run(work, transaction=False)
variants: tuple[Variant, ...] = ()
if row[8] == "ready":
cur = await conn.execute(
"SELECT name, content_type, size_bytes, width, height, sha256, object_key FROM attachment_variants "
"WHERE attachment_id = %s AND pipeline_version = %s "
"ORDER BY array_position(ARRAY['thumbnail', 'crop', 'optimized'], name)", (row[0], row[13]))
variants = tuple(Variant(r[0], r[1], r[2], r[3], r[4], bytes(r[5]).hex(), r[6]) for r in await cur.fetchall())
return _attachment(row, variants)
# REPEATABLE READ is not needed: the variant rows of a published version never change.
return await db.run(work)
async def clean_stale_pending(db: Database, storage: Storage, grace_seconds: int, batch: int = 20) -> int:
"""Janitor round: remove intents of uploads that never became ready.
async def clean_stale_pending(db: Database, staging: Storage, grace_seconds: int, batch: int = 20) -> int:
"""Janitor round: remove intents of uploads that never got their job (no 202 was sent).
Under FOR UPDATE: an upload that is (impossibly) still running would block on the row in
mark_ready and then find it gone (-> 503), so a ready attachment can never lose its object.
Order: object first (idempotent), row second; a crash in between leaves the pending row and
the next round repeats. Only status='pending' rows older than the grace period are touched:
fresh uploads and ready/used attachments are never selected.
enqueue() and then find it gone (-> 503). Order: staging object first (idempotent), row second;
a crash in between leaves the pending row and the next round repeats. Only status='pending'
rows older than the grace period are touched: queued/processing/ready/failed never.
"""
async def work(conn: psycopg.AsyncConnection) -> int:
cur = await conn.execute("SELECT pg_try_advisory_xact_lock(%s)", (JANITOR_LOCK_ID,))
if not (await cur.fetchone())[0]:
return 0
cur = await conn.execute(
"SELECT id, object_key FROM attachments WHERE status = 'pending' "
"SELECT id, staging_key FROM attachments WHERE status = 'pending' "
"AND created_at < clock_timestamp() - make_interval(secs => %s) "
"ORDER BY created_at LIMIT %s FOR UPDATE SKIP LOCKED", (grace_seconds, batch))
rows = await cur.fetchall()
if not rows:
return 0
await asyncio.gather(*(storage.delete(key) for _, key in rows))
await asyncio.gather(*(staging.delete(key) for _, key in rows))
await conn.execute("DELETE FROM attachments WHERE id = ANY(%s) AND status = 'pending'",
([r[0] for r in rows],))
return len(rows)
return await db.run(work, deadline=storage.timeout + 5)
return await db.run(work, deadline=staging.timeout + 5)
# ------------------------------------------------------------------ request body