forked from mtusi2026/mtusi2026lab4
lab4: вложения в приватном S3 (SeaweedFS), метаданные в PostgreSQL
- compose: сервис s3 (SeaweedFS 4.46 по digest, volume s3data, внутренняя сеть storage,
web-интерфейсы только на 127.0.0.1 внутри контейнера), одноразовый s3-init;
- три пары ключей S3: admin (только bootstrap), api (Read+Write своего bucket),
reconciler (+List); bootstrap идемпотентен и проверяет приватность и права;
- миграция 0004: attachments (pending -> ready, случайный object_key), message_attachments,
post_message_v2 с проверкой вложений в той же транзакции;
- POST /chats/{id}/attachments: лимиты до чтения/декодирования, потоковая проверка PNG
(CRC + zlib до точного размера), JPEG через djpeg -strict, семафор загрузок;
- GET метаданных и /content (стриминг из S3, без redirect), readiness с S3,
HAProxy: деградированный режим без S3 через /health/ready/core;
- janitor незавершённых загрузок с grace period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
d916d09f7b
commit
335df4b2b2
+160
-12
@@ -6,6 +6,7 @@ import contextlib
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
@@ -14,15 +15,16 @@ from typing import Any
|
||||
from starlette.applications import Starlette
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse, Response
|
||||
from starlette.responses import JSONResponse, Response, StreamingResponse
|
||||
from starlette.routing import Route
|
||||
from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Send
|
||||
|
||||
from . import authhdr, cursor, docs, passwords, repo, validation
|
||||
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 .sessions import SessionStore, build_store
|
||||
from .storage import ObjectMissing, Storage
|
||||
from .timefmt import rfc3339
|
||||
|
||||
log = logging.getLogger("messenger")
|
||||
@@ -126,6 +128,10 @@ def sessions_of(request: Request) -> SessionStore:
|
||||
return request.app.state.sessions
|
||||
|
||||
|
||||
def storage_of(request: Request) -> Storage:
|
||||
return request.app.state.storage
|
||||
|
||||
|
||||
async def authenticate(request: Request) -> str:
|
||||
"""User id of a valid Bearer session, otherwise 401. X-User-Id is ignored since lab 2.
|
||||
|
||||
@@ -206,15 +212,32 @@ async def live(request: Request) -> JSONResponse:
|
||||
|
||||
|
||||
async def ready(request: Request) -> JSONResponse:
|
||||
"""200 only if the mandatory synchronous path can be served: PostgreSQL and,
|
||||
with SESSION_STORE=valkey, Valkey answer. 503 while draining after SIGTERM."""
|
||||
"""200 only if the WHOLE mandatory synchronous path can be served: PostgreSQL, Valkey
|
||||
(SESSION_STORE=valkey) and, since lab 4, the S3 bucket (upload/download of attachments)
|
||||
answer. 503 while draining after SIGTERM. HAProxy routes to such replicas first."""
|
||||
if request.app.state.draining:
|
||||
raise Unavailable("Сервер завершает работу")
|
||||
db_ok, store_ok = await asyncio.gather(db_of(request).ping(), sessions_of(request).ping())
|
||||
db_ok, store_ok, s3_ok = await asyncio.gather(db_of(request).ping(), sessions_of(request).ping(),
|
||||
storage_of(request).ping())
|
||||
if not db_ok:
|
||||
raise Unavailable("PostgreSQL недоступен")
|
||||
if not store_ok:
|
||||
raise Unavailable("Хранилище сессий недоступно")
|
||||
if not s3_ok:
|
||||
raise Unavailable("Хранилище файлов (S3) недоступно")
|
||||
return ok({"status": "ok"})
|
||||
|
||||
|
||||
async def ready_core(request: Request) -> JSONResponse:
|
||||
"""Not in the contract: readiness WITHOUT S3, for the load balancer's degraded mode only.
|
||||
If S3 is down for every replica, /health/ready is 503 everywhere; HAProxy then routes to
|
||||
replicas that are at least core-ready, so chats and messages keep working while every
|
||||
attachment request answers 503 itself (see infra/haproxy/haproxy.cfg)."""
|
||||
if request.app.state.draining:
|
||||
raise Unavailable("Сервер завершает работу")
|
||||
db_ok, store_ok = await asyncio.gather(db_of(request).ping(), sessions_of(request).ping())
|
||||
if not (db_ok and store_ok):
|
||||
raise Unavailable("PostgreSQL или хранилище сессий недоступно")
|
||||
return ok({"status": "ok"})
|
||||
|
||||
|
||||
@@ -288,12 +311,12 @@ async def get_chat(request: Request) -> JSONResponse:
|
||||
|
||||
|
||||
def parse_message(data: dict[str, Any]) -> tuple[str, list[str]]:
|
||||
"""`text` is required and a string (also with attachments); `attachment_ids`, if present, an
|
||||
array of 0-10 unique UUIDs. "" or whitespace-only text is allowed only with attachments."""
|
||||
validation.check_fields(data, {"text"}, frozenset({"attachment_ids"}))
|
||||
text = validation.text_field(data, "text", 4000)
|
||||
attachment_ids = validation.attachment_ids_field(data)
|
||||
if attachment_ids:
|
||||
# Lab 3 has no attachments: every referenced ID is unknown (lab 4 semantics: 404).
|
||||
raise NotFound("Вложение не найдено")
|
||||
text = validation.text_field(data, "text", 4000, min_len=0 if attachment_ids else 1,
|
||||
allow_blank=bool(attachment_ids))
|
||||
return text, attachment_ids
|
||||
|
||||
|
||||
@@ -309,7 +332,7 @@ async def create_message(request: Request) -> JSONResponse:
|
||||
key = idempotency_key(request)
|
||||
text, attachment_ids = parse_message(await read_json(request))
|
||||
result = await repo.post_message(db, user_id, chat_id, key, request_fingerprint(text, attachment_ids), text,
|
||||
settings.idempotency_ttl_seconds)
|
||||
settings.idempotency_ttl_seconds, attachment_ids)
|
||||
else:
|
||||
try:
|
||||
key = idempotency_key(request)
|
||||
@@ -321,7 +344,7 @@ async def create_message(request: Request) -> JSONResponse:
|
||||
# Membership check, key claim, chat clock and message: one SQL call, one transaction.
|
||||
result = await repo.post_message_single_call(db, user_id, chat_id, key,
|
||||
request_fingerprint(text, attachment_ids), text,
|
||||
settings.idempotency_ttl_seconds)
|
||||
settings.idempotency_ttl_seconds, attachment_ids)
|
||||
if result.replayed:
|
||||
log.info("idempotent_replay", extra={"fields": {"request_id": request.state.request_id,
|
||||
"message_id": result.message.id}})
|
||||
@@ -340,10 +363,111 @@ async def list_messages(request: Request) -> JSONResponse:
|
||||
return ok({"items": [m.to_json() for m in items], "next_cursor": next_cursor})
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ attachments (lab 4)
|
||||
def fault(request: Request, point: str) -> None:
|
||||
"""Failure injection for the level 4 experiments (FAULT_POINTS, compose.faults.yaml only)."""
|
||||
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)."""
|
||||
settings: Settings = request.app.state.settings
|
||||
reader = attachments.BodyReader(request)
|
||||
try:
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
db = db_of(request)
|
||||
await repo.ensure_member(db, user_id, chat_id) # outsiders: 404 before anything about the body
|
||||
filename = validation.filename_param(validation.query_items(request.scope["query_string"]))
|
||||
declared = attachments.declared_type(request)
|
||||
attachments.declared_length(request, settings.max_upload_bytes)
|
||||
slots: asyncio.Semaphore = request.app.state.upload_slots
|
||||
try:
|
||||
await asyncio.wait_for(slots.acquire(), settings.upload_queue_timeout_seconds)
|
||||
except asyncio.TimeoutError:
|
||||
raise attachments.Busy("Слишком много одновременных загрузок, повторите позже") from None
|
||||
try:
|
||||
upload = await attachments.read_image(reader, settings, declared)
|
||||
finally:
|
||||
slots.release()
|
||||
except ApiError:
|
||||
# Early rejection: drop (not store) a bounded rest of the body so the client reads our error.
|
||||
await reader.discard(settings.max_upload_bytes + (1 << 20), timeout=5.0)
|
||||
raise
|
||||
attachment_id = uuid.uuid4()
|
||||
object_key = attachments.new_object_key()
|
||||
storage = storage_of(request)
|
||||
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()})
|
||||
fault(request, "after_s3_put")
|
||||
attachment = await attachments.mark_ready(db, attachment_id)
|
||||
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)
|
||||
|
||||
|
||||
async def get_attachment(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
attachment_id = path_uuid(request, "attachment_id")
|
||||
return ok((await attachments.get_visible(db_of(request), user_id, attachment_id)).to_json())
|
||||
|
||||
|
||||
def content_disposition(filename: str) -> str:
|
||||
"""RFC 6266/5987: ASCII fallback + UTF-8 name; the stored name itself is never interpreted."""
|
||||
from urllib.parse import quote
|
||||
fallback = "".join(c if 32 <= ord(c) < 127 and c not in '"\\%;' else "_" for c in filename)
|
||||
return f"attachment; filename=\"{fallback}\"; filename*=UTF-8''{quote(filename, safe='')}"
|
||||
|
||||
|
||||
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)."""
|
||||
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:
|
||||
await attachments.get_visible(db_of(request), user_id, attachment_id) # 404 for outsiders first
|
||||
raise NotFound("Такого варианта у вложения нет") from None
|
||||
attachment = await attachments.get_visible(db_of(request), user_id, attachment_id)
|
||||
if attachment.lost:
|
||||
raise NotFound("Оригинал вложения утрачен")
|
||||
try:
|
||||
size, chunks = await storage_of(request).open_stream(attachment.object_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:
|
||||
log.error("attachment_size_mismatch", extra={"fields": {"request_id": request.state.request_id,
|
||||
"attachment_id": attachment.id}})
|
||||
await chunks.aclose()
|
||||
raise Unavailable("Оригинал вложения временно недоступен")
|
||||
headers = {
|
||||
"Content-Length": str(size),
|
||||
"Content-Disposition": content_disposition(attachment.filename),
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "private, no-store",
|
||||
"ETag": '"' + attachment.sha256 + '"',
|
||||
}
|
||||
return StreamingResponse(chunks, media_type=attachment.content_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)
|
||||
|
||||
async def purge_loop() -> None:
|
||||
"""Housekeeping: expired Idempotency-Key rows (older than IDEMPOTENCY_TTL_SECONDS)."""
|
||||
@@ -356,6 +480,18 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
except ApiError:
|
||||
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).
|
||||
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)
|
||||
if removed:
|
||||
log.info("stale_uploads_removed", extra={"fields": {"count": removed}})
|
||||
except ApiError:
|
||||
pass # PostgreSQL or S3 unavailable right now; the rows stay pending for the next round
|
||||
|
||||
stats_log = logging.getLogger("messenger.stats")
|
||||
|
||||
async def stats_loop(every: float) -> None:
|
||||
@@ -376,12 +512,17 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
async def lifespan(app: Starlette):
|
||||
passwords.configure(settings.hash_concurrency)
|
||||
await db.open()
|
||||
await storage.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}})
|
||||
"message_write_path": settings.message_write_path, "s3_bucket": settings.s3_bucket,
|
||||
"upload_concurrency": settings.upload_concurrency, "pending_grace_s": settings.pending_grace_seconds,
|
||||
"fault_points": sorted(settings.fault_points)}})
|
||||
tasks = [asyncio.create_task(purge_loop())]
|
||||
if settings.janitor_interval_seconds > 0:
|
||||
tasks.append(asyncio.create_task(janitor_loop(settings.janitor_interval_seconds)))
|
||||
if settings.stats_log_seconds > 0:
|
||||
tasks.append(asyncio.create_task(stats_loop(settings.stats_log_seconds)))
|
||||
try:
|
||||
@@ -390,11 +531,13 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
await sessions.close()
|
||||
await storage.close()
|
||||
await db.close()
|
||||
|
||||
routes = [
|
||||
Route("/health/live", live, methods=["GET"]),
|
||||
Route("/health/ready", ready, methods=["GET"]),
|
||||
Route("/health/ready/core", ready_core, methods=["GET"]),
|
||||
Route("/api/v1/users", register_user, methods=["POST"]),
|
||||
Route("/api/v1/users/me", me, methods=["GET"]),
|
||||
Route("/api/v1/auth/sessions", create_session, methods=["POST"]),
|
||||
@@ -404,6 +547,9 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
Route("/api/v1/chats/{chat_id}", get_chat, methods=["GET"]),
|
||||
Route("/api/v1/chats/{chat_id}/messages", create_message, methods=["POST"]),
|
||||
Route("/api/v1/chats/{chat_id}/messages", list_messages, methods=["GET"]),
|
||||
Route("/api/v1/chats/{chat_id}/attachments", upload_attachment, methods=["POST"]),
|
||||
Route("/api/v1/attachments/{attachment_id}", get_attachment, methods=["GET"]),
|
||||
Route("/api/v1/attachments/{attachment_id}/content", download_attachment, methods=["GET"]),
|
||||
]
|
||||
if settings.docs_enabled: # Swagger UI for manual experiments, not part of the contract
|
||||
routes += [
|
||||
@@ -419,5 +565,7 @@ def create_app(settings: Settings | None = None) -> Starlette:
|
||||
app.state.settings = settings
|
||||
app.state.db = db
|
||||
app.state.sessions = sessions
|
||||
app.state.storage = storage
|
||||
app.state.upload_slots = asyncio.Semaphore(settings.upload_concurrency)
|
||||
app.state.draining = False
|
||||
return app
|
||||
|
||||
Reference in New Issue
Block a user