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:
+59
-34
@@ -22,7 +22,7 @@ from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Sen
|
||||
from . import attachments, authhdr, cursor, docs, passwords, repo, validation
|
||||
from .config import Settings
|
||||
from .db import Database
|
||||
from .errors import BASIC_CHALLENGE, ApiError, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable
|
||||
from .errors import BASIC_CHALLENGE, ApiError, Conflict, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable
|
||||
from .sessions import SessionStore, build_store
|
||||
from .storage import ObjectMissing, Storage
|
||||
from .timefmt import rfc3339
|
||||
@@ -132,6 +132,10 @@ def storage_of(request: Request) -> Storage:
|
||||
return request.app.state.storage
|
||||
|
||||
|
||||
def staging_of(request: Request) -> Storage:
|
||||
return request.app.state.staging
|
||||
|
||||
|
||||
async def authenticate(request: Request) -> str:
|
||||
"""User id of a valid Bearer session, otherwise 401. X-User-Id is ignored since lab 2.
|
||||
|
||||
@@ -363,16 +367,17 @@ async def list_messages(request: Request) -> JSONResponse:
|
||||
return ok({"items": [m.to_json() for m in items], "next_cursor": next_cursor})
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ attachments (lab 4)
|
||||
# ------------------------------------------------------------------ attachments (lab 4, lab 5)
|
||||
def fault(request: Request, point: str) -> None:
|
||||
"""Failure injection for the level 4 experiments (FAULT_POINTS, compose.faults.yaml only)."""
|
||||
"""Failure injection for the experiments (FAULT_POINTS of the api service, compose variable
|
||||
API_FAULT_POINTS; empty in normal runs)."""
|
||||
if point in request.app.state.settings.fault_points:
|
||||
log.warning("fault_injected", extra={"fields": {"request_id": request.state.request_id, "point": point}})
|
||||
raise Unavailable("Внедрённый отказ: " + point)
|
||||
|
||||
|
||||
async def upload_attachment(request: Request) -> JSONResponse:
|
||||
"""POST /chats/{chat_id}/attachments?filename=...: raw PNG/JPEG -> 201 ready (attachments.py)."""
|
||||
"""POST /chats/{chat_id}/attachments?filename=...: raw PNG/JPEG -> 202 queued (attachments.py)."""
|
||||
settings: Settings = request.app.state.settings
|
||||
reader = attachments.BodyReader(request)
|
||||
slots: asyncio.Semaphore = request.app.state.upload_slots
|
||||
@@ -406,23 +411,25 @@ async def upload_attachment(request: Request) -> JSONResponse:
|
||||
|
||||
async def store_upload(request: Request, db: Database, chat_id: str, user_id: str, filename: str,
|
||||
upload: attachments.Upload) -> JSONResponse:
|
||||
"""intent (pending) -> S3 PUT -> ready -> 201 (order and failure analysis: docs/CONSISTENCY.md)."""
|
||||
"""intent (pending) -> staging PUT -> queued + job + outbox -> 202 (docs/PIPELINE.md).
|
||||
No resize here: the worker does it; a stopped worker only delays `ready`."""
|
||||
settings: Settings = request.app.state.settings
|
||||
attachment_id = uuid.uuid4()
|
||||
object_key = attachments.new_object_key()
|
||||
storage = storage_of(request)
|
||||
staging_key = attachments.new_staging_key()
|
||||
await attachments.create_intent(db, attachment_id, chat_id, user_id, filename, upload.info, len(upload.data),
|
||||
upload.sha256, object_key)
|
||||
await storage.put(object_key, upload.data, upload.info.content_type,
|
||||
{"attachment-id": str(attachment_id), "sha256": upload.sha256.hex()})
|
||||
upload.sha256, staging_key)
|
||||
await staging_of(request).put(staging_key, upload.data, upload.info.content_type,
|
||||
{"attachment-id": str(attachment_id), "sha256": upload.sha256.hex()})
|
||||
fault(request, "after_s3_put")
|
||||
attachment = await attachments.mark_ready(db, attachment_id)
|
||||
attachment = await attachments.enqueue(db, attachment_id, settings)
|
||||
if attachment is None:
|
||||
raise Unavailable("Загрузка не завершена, повторите запрос")
|
||||
fault(request, "after_ready_commit")
|
||||
log.info("attachment_created", extra={"fields": {"request_id": request.state.request_id,
|
||||
"attachment_id": attachment.id, "chat_id": chat_id,
|
||||
"size": attachment.size_bytes, "type": attachment.content_type}})
|
||||
return ok(attachment.to_json(), 201)
|
||||
fault(request, "after_enqueue_commit")
|
||||
log.info("attachment_queued", extra={"fields": {"request_id": request.state.request_id,
|
||||
"attachment_id": attachment.id, "chat_id": chat_id,
|
||||
"size": attachment.size_bytes, "type": attachment.content_type,
|
||||
"pipeline_version": settings.pipeline_version}})
|
||||
return ok(attachment.to_json(), 202)
|
||||
|
||||
|
||||
async def get_attachment(request: Request) -> JSONResponse:
|
||||
@@ -439,46 +446,60 @@ def content_disposition(filename: str) -> str:
|
||||
|
||||
|
||||
async def download_attachment(request: Request) -> Response:
|
||||
"""Original bytes through the authorized API: no redirect, no public S3 URL. Streamed from
|
||||
S3 in 64 KiB chunks (memory per download does not depend on the file size)."""
|
||||
"""Original or variant bytes through the authorized API: no redirect, no public S3 URL.
|
||||
queued/processing/failed -> 409 (not ready); a variant a ready attachment lacks -> 404.
|
||||
Streamed from S3 in 64 KiB chunks (memory per download does not depend on the file size)."""
|
||||
user_id = await authenticate(request)
|
||||
attachment_id = path_uuid(request, "attachment_id")
|
||||
query = validation.query_items(request.scope["query_string"])
|
||||
try:
|
||||
validation.variant_param(query)
|
||||
except validation.NotFoundVariant:
|
||||
variant = validation.variant_param(query)
|
||||
except ApiError:
|
||||
await attachments.get_visible(db_of(request), user_id, attachment_id) # 404 for outsiders first
|
||||
raise NotFound("Такого варианта у вложения нет") from None
|
||||
raise
|
||||
attachment = await attachments.get_visible(db_of(request), user_id, attachment_id)
|
||||
if attachment.status != "ready":
|
||||
raise Conflict("Обработка вложения не удалась" if attachment.status == "failed" else "Вложение ещё не готово")
|
||||
if attachment.lost:
|
||||
raise NotFound("Оригинал вложения утрачен")
|
||||
if variant == "original":
|
||||
key, size_expected, media_type, etag = (attachment.object_key, attachment.size_bytes,
|
||||
attachment.content_type, attachment.sha256)
|
||||
name = attachment.filename
|
||||
else:
|
||||
found = attachment.variant(variant)
|
||||
if found is None:
|
||||
raise NotFound("Такого варианта у вложения нет")
|
||||
key, size_expected, media_type, etag = found.object_key, found.size_bytes, found.content_type, found.sha256
|
||||
stem = attachment.filename.rsplit(".", 1)[0] or "image"
|
||||
name = stem + "-" + variant + (".webp" if media_type == "image/webp" else ".jpg")
|
||||
try:
|
||||
size, chunks = await storage_of(request).open_stream(attachment.object_key)
|
||||
size, chunks = await storage_of(request).open_stream(key)
|
||||
except ObjectMissing:
|
||||
# A ready row without its object: data loss, reported by the reconciler (quarantine).
|
||||
log.error("attachment_object_missing", extra={"fields": {"request_id": request.state.request_id,
|
||||
"attachment_id": attachment.id}})
|
||||
raise NotFound("Оригинал вложения утрачен") from None
|
||||
if size != attachment.size_bytes:
|
||||
"attachment_id": attachment.id, "variant": variant}})
|
||||
raise Unavailable("Файл вложения временно недоступен") from None
|
||||
if size != size_expected:
|
||||
log.error("attachment_size_mismatch", extra={"fields": {"request_id": request.state.request_id,
|
||||
"attachment_id": attachment.id}})
|
||||
"attachment_id": attachment.id, "variant": variant}})
|
||||
await chunks.aclose()
|
||||
raise Unavailable("Оригинал вложения временно недоступен")
|
||||
raise Unavailable("Файл вложения временно недоступен")
|
||||
headers = {
|
||||
"Content-Length": str(size),
|
||||
"Content-Disposition": content_disposition(attachment.filename),
|
||||
"Content-Disposition": content_disposition(name),
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "private, no-store",
|
||||
"ETag": '"' + attachment.sha256 + '"',
|
||||
"ETag": '"' + etag + '"',
|
||||
}
|
||||
return StreamingResponse(chunks, media_type=attachment.content_type, headers=headers)
|
||||
return StreamingResponse(chunks, media_type=media_type, headers=headers)
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None) -> Starlette:
|
||||
settings = settings or Settings.from_env()
|
||||
db = Database(settings)
|
||||
sessions = build_store(settings, db)
|
||||
storage = Storage(settings)
|
||||
storage = Storage(settings) # final bucket: Read
|
||||
staging = Storage(settings, bucket=settings.s3_staging_bucket) # staging bucket: Write (+ janitor DELETE)
|
||||
|
||||
async def purge_loop() -> None:
|
||||
"""Housekeeping: expired Idempotency-Key rows (older than IDEMPOTENCY_TTL_SECONDS)."""
|
||||
@@ -492,12 +513,12 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
pass # database unavailable right now; next round
|
||||
|
||||
async def janitor_loop(every: float) -> None:
|
||||
"""Level 4 cleanup: intents of failed uploads older than PENDING_GRACE_SECONDS (attachments.py).
|
||||
"""Cleanup of intents of failed uploads older than PENDING_GRACE_SECONDS (attachments.py).
|
||||
Every replica runs it; the advisory lock lets one round run at a time."""
|
||||
while True:
|
||||
await asyncio.sleep(every * (0.5 + random.random()))
|
||||
try:
|
||||
removed = await attachments.clean_stale_pending(db, storage, settings.pending_grace_seconds)
|
||||
removed = await attachments.clean_stale_pending(db, staging, settings.pending_grace_seconds)
|
||||
if removed:
|
||||
log.info("stale_uploads_removed", extra={"fields": {"count": removed}})
|
||||
except ApiError:
|
||||
@@ -524,11 +545,13 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
passwords.configure(settings.hash_concurrency)
|
||||
await db.open()
|
||||
await storage.open()
|
||||
await staging.open()
|
||||
log.info("dependencies_configured", extra={"fields": {
|
||||
"session_store": sessions.name, "session_ttl_s": settings.session_ttl_seconds,
|
||||
"db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds,
|
||||
"instance_id": settings.instance_id, "drain_s": settings.drain_seconds,
|
||||
"message_write_path": settings.message_write_path, "s3_bucket": settings.s3_bucket,
|
||||
"s3_staging_bucket": settings.s3_staging_bucket, "pipeline_version": settings.pipeline_version,
|
||||
"upload_concurrency": settings.upload_concurrency, "verify_concurrency": settings.image_verify_concurrency,
|
||||
"pending_grace_s": settings.pending_grace_seconds,
|
||||
"fault_points": sorted(settings.fault_points)}})
|
||||
@@ -543,6 +566,7 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
await sessions.close()
|
||||
await staging.close()
|
||||
await storage.close()
|
||||
await db.close()
|
||||
|
||||
@@ -578,6 +602,7 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
app.state.db = db
|
||||
app.state.sessions = sessions
|
||||
app.state.storage = storage
|
||||
app.state.staging = staging
|
||||
app.state.upload_slots = asyncio.Semaphore(settings.upload_concurrency)
|
||||
app.state.verify_slots = asyncio.Semaphore(settings.image_verify_concurrency)
|
||||
app.state.draining = False
|
||||
|
||||
Reference in New Issue
Block a user