laba 5 mark 4
This commit is contained in:
@@ -0,0 +1,467 @@
|
||||
"""Attachments: durable upload to staging, queued metadata + outbox (lab5).
|
||||
|
||||
Upload, in this order (all checks before the bytes are stored):
|
||||
|
||||
1. filename (400) -> chat membership (404) -> Content-Type header (415)
|
||||
-> Content-Length (413 without reading the body);
|
||||
2. an upload slot: at most MAX_CONCURRENT_UPLOADS per replica, else 429;
|
||||
3. the body is read in chunks into a SpooledTemporaryFile (only
|
||||
UPLOAD_SPOOL_MEMORY_BYTES in RAM), counted and hashed on the fly; more
|
||||
than MAX_UPLOAD_BYTES -> 413, slower than UPLOAD_TIMEOUT_SECONDS -> 400;
|
||||
4. content validation in a thread (app.images): format by magic bytes,
|
||||
pixel limit from the header (413), integrity (415);
|
||||
5. upload intent COMMIT -> staging S3 PUT -> one transaction "delete intent +
|
||||
insert queued attachment + outbox" -> 202. Worker produces all variants.
|
||||
|
||||
Failure between S3 and PostgreSQL (the answer is 503 at once, cleanup runs
|
||||
in the background):
|
||||
- PUT failed or timed out: the outcome is unknown - S3 may still finish
|
||||
writing the object AFTER our DELETE. So the object is deleted best
|
||||
effort, but the intent is KEPT; the janitor deletes the object again
|
||||
after UPLOAD_GRACE_SECONDS and only then the intent;
|
||||
- COMMIT failed: the outcome is unknown too - COMMIT may have succeeded
|
||||
and only the answer was lost. Under the intent's row lock: no intent ->
|
||||
the row is committed, keep the object; else delete object, then intent;
|
||||
- the process died after PUT: the intent stays; the janitor deletes the
|
||||
object and the intent after UPLOAD_GRACE_SECONDS.
|
||||
So an object without a row exists only while its intent exists, and an
|
||||
object of a committed row is never deleted.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import tempfile
|
||||
import unicodedata
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import Request
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from app import repositories
|
||||
from app.config import settings
|
||||
from app.db import SessionLocal
|
||||
from app.errors import (
|
||||
ApiError,
|
||||
Conflict,
|
||||
InvalidRequest,
|
||||
NotFound,
|
||||
PayloadTooLarge,
|
||||
RateLimited,
|
||||
Unavailable,
|
||||
UnsupportedMediaType,
|
||||
)
|
||||
from app.images import InvalidImage, TooManyPixels, validate_image
|
||||
from app.storage import ObjectMissing, StorageUnavailable, storage
|
||||
|
||||
|
||||
logger = logging.getLogger("messenger.attachments")
|
||||
|
||||
ALLOWED_CONTENT_TYPES = {"image/png", "image/jpeg"}
|
||||
# Characters that can turn a display name into a path or hide its real
|
||||
# extension: separators, NUL/control characters, bidi overrides etc.
|
||||
FORBIDDEN_CATEGORIES = {"Cc", "Cf", "Cs", "Co", "Cn", "Zl", "Zp"}
|
||||
|
||||
upload_slots = asyncio.Semaphore(settings.max_concurrent_uploads)
|
||||
# Full integrity checks are CPU work too. In particular, progressive JPEG
|
||||
# retains decoder coefficients even with draft(); never run eight at once.
|
||||
validation_slot = asyncio.Semaphore(1)
|
||||
# Strong references to background compensation tasks (asyncio keeps only
|
||||
# weak ones); if the process dies first, the intent stays for the janitor.
|
||||
_compensations: set[asyncio.Task] = set()
|
||||
|
||||
|
||||
def _to_attachment(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"chat_id": row["chat_id"],
|
||||
"owner_id": row["owner_id"],
|
||||
"filename": row["filename"],
|
||||
"content_type": row["content_type"],
|
||||
"size_bytes": row["size_bytes"],
|
||||
"sha256": row["sha256"],
|
||||
"status": row["status"],
|
||||
"variants": [
|
||||
{key: value for key, value in variant.items() if key != "object_key"}
|
||||
for variant in _variants(row)
|
||||
],
|
||||
"error_code": row["error_code"],
|
||||
"created_at": row["created_at"],
|
||||
"updated_at": row["updated_at"],
|
||||
}
|
||||
|
||||
|
||||
def _variants(row: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
value = row.get("variants") or []
|
||||
return json.loads(value) if isinstance(value, str) else value
|
||||
|
||||
|
||||
def validate_filename(filename: str) -> str:
|
||||
if not 1 <= len(filename) <= 255 or not filename.strip():
|
||||
raise InvalidRequest("filename must be 1-255 characters, not blank.")
|
||||
|
||||
if "/" in filename or "\\" in filename:
|
||||
raise InvalidRequest("filename must not contain path separators.")
|
||||
|
||||
if any(unicodedata.category(ch) in FORBIDDEN_CATEGORIES for ch in filename):
|
||||
raise InvalidRequest("filename must not contain control characters.")
|
||||
|
||||
if filename.strip(". ") == "":
|
||||
raise InvalidRequest("filename must not be a relative path.")
|
||||
|
||||
return filename
|
||||
|
||||
|
||||
def declared_content_type(request: Request) -> str:
|
||||
raw = request.headers.get("Content-Type", "")
|
||||
media_type = raw.split(";", 1)[0].strip().lower()
|
||||
|
||||
if media_type not in ALLOWED_CONTENT_TYPES:
|
||||
raise UnsupportedMediaType(
|
||||
"Content-Type must be image/png or image/jpeg (raw bytes, not multipart)."
|
||||
)
|
||||
|
||||
return media_type
|
||||
|
||||
|
||||
def _too_large(message: str) -> PayloadTooLarge:
|
||||
error = PayloadTooLarge(message)
|
||||
# The rest of the body is not read: the connection cannot be reused.
|
||||
error.headers["Connection"] = "close"
|
||||
return error
|
||||
|
||||
|
||||
def check_declared_length(request: Request) -> None:
|
||||
raw = request.headers.get("Content-Length")
|
||||
if raw is None:
|
||||
return # chunked: the limit is enforced while reading
|
||||
|
||||
if not raw.isdigit():
|
||||
raise InvalidRequest("Invalid Content-Length.")
|
||||
|
||||
if int(raw) > settings.max_upload_bytes:
|
||||
raise _too_large("File is larger than 10 MiB.")
|
||||
|
||||
|
||||
async def _receive_body(request: Request, spool) -> tuple[int, str]:
|
||||
"""Stream the body into the spool; return (size, sha256)."""
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
|
||||
try:
|
||||
async with asyncio.timeout(settings.upload_timeout_seconds):
|
||||
async for chunk in request.stream():
|
||||
if not chunk:
|
||||
continue
|
||||
size += len(chunk)
|
||||
if size > settings.max_upload_bytes:
|
||||
raise _too_large("File is larger than 10 MiB.")
|
||||
digest.update(chunk)
|
||||
spool.write(chunk)
|
||||
except TimeoutError:
|
||||
raise ApiError(
|
||||
400,
|
||||
"invalid_request",
|
||||
"Upload was not completed in time.",
|
||||
{"Connection": "close"},
|
||||
) from None
|
||||
except ClientDisconnect:
|
||||
# Nobody will read this answer; nothing was stored anywhere.
|
||||
logger.info("upload interrupted by the client after %d bytes", size)
|
||||
raise InvalidRequest("Upload was interrupted.") from None
|
||||
|
||||
return size, digest.hexdigest()
|
||||
|
||||
|
||||
async def _acquire_slot() -> None:
|
||||
try:
|
||||
async with asyncio.timeout(settings.upload_slot_wait_seconds):
|
||||
await upload_slots.acquire()
|
||||
except TimeoutError:
|
||||
raise RateLimited("Too many concurrent uploads, retry later.", 2) from None
|
||||
|
||||
|
||||
async def _discard_after_failed_put(object_key: str) -> None:
|
||||
"""Best effort only; the intent stays for the janitor (late PUT)."""
|
||||
try:
|
||||
await storage.delete(object_key)
|
||||
except StorageUnavailable:
|
||||
logger.warning("compensation: S3 delete failed, janitor will retry")
|
||||
|
||||
|
||||
async def _compensate_failed_commit(object_key: str) -> None:
|
||||
"""Delete the object only if its upload really did not commit."""
|
||||
try:
|
||||
async with SessionLocal() as db:
|
||||
row = await repositories.lock_upload_intent(db, object_key)
|
||||
if row is None:
|
||||
# COMMIT succeeded after all (or the janitor finished it).
|
||||
await db.rollback()
|
||||
return
|
||||
if not row["committed"]:
|
||||
try:
|
||||
await storage.delete(object_key)
|
||||
except StorageUnavailable:
|
||||
await db.rollback()
|
||||
logger.warning("compensation: S3 delete failed, janitor will retry")
|
||||
return
|
||||
await repositories.delete_upload_intent(db, object_key)
|
||||
except Exception as exc:
|
||||
logger.warning("compensation failed, janitor will retry: %s", type(exc).__name__)
|
||||
|
||||
|
||||
async def upload_attachment(
|
||||
request: Request,
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
filename: str,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
validate_filename(filename)
|
||||
|
||||
chat = await repositories.get_accessible_chat(
|
||||
db, chat_id=chat_id, user_id=current_user["id"]
|
||||
)
|
||||
if chat is None:
|
||||
raise NotFound()
|
||||
# Do not keep a pooled connection idle in a transaction while the
|
||||
# client uploads up to 10 MiB.
|
||||
await db.rollback()
|
||||
|
||||
content_type = declared_content_type(request)
|
||||
check_declared_length(request)
|
||||
|
||||
await _acquire_slot()
|
||||
try:
|
||||
with tempfile.SpooledTemporaryFile(
|
||||
max_size=settings.upload_spool_memory_bytes
|
||||
) as spool:
|
||||
size, sha256 = await _receive_body(request, spool)
|
||||
if size == 0:
|
||||
raise InvalidRequest("Request body with image bytes is required.")
|
||||
|
||||
try:
|
||||
async with validation_slot:
|
||||
validation = asyncio.create_task(asyncio.to_thread(
|
||||
validate_image, spool, content_type, settings.max_image_pixels
|
||||
))
|
||||
try:
|
||||
info = await asyncio.shield(validation)
|
||||
except asyncio.CancelledError:
|
||||
# A thread cannot be killed: keep its spool and the
|
||||
# validation slot alive until it has really stopped.
|
||||
await asyncio.gather(validation, return_exceptions=True)
|
||||
raise
|
||||
except TooManyPixels:
|
||||
raise PayloadTooLarge("Image has more than 40 million pixels.") from None
|
||||
except InvalidImage as exc:
|
||||
raise UnsupportedMediaType(str(exc)) from None
|
||||
|
||||
return await _store(
|
||||
db,
|
||||
spool=spool,
|
||||
chat_id=chat_id,
|
||||
owner_id=current_user["id"],
|
||||
filename=filename,
|
||||
content_type=info.content_type,
|
||||
size=size,
|
||||
sha256=sha256,
|
||||
width=info.width,
|
||||
height=info.height,
|
||||
)
|
||||
finally:
|
||||
upload_slots.release()
|
||||
|
||||
|
||||
async def _store(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
spool,
|
||||
chat_id: UUID,
|
||||
owner_id: UUID,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
size: int,
|
||||
sha256: str,
|
||||
width: int,
|
||||
height: int,
|
||||
) -> dict[str, Any]:
|
||||
attachment_id = uuid4()
|
||||
# Server-generated random key, unrelated to the filename and to the
|
||||
# public attachment ID.
|
||||
object_key = f"staging/{uuid4().hex}"
|
||||
|
||||
await repositories.create_upload_intent(
|
||||
db, object_key=object_key, attachment_id=attachment_id, chat_id=chat_id
|
||||
)
|
||||
|
||||
try:
|
||||
await storage.put(object_key, spool, size, content_type)
|
||||
except StorageUnavailable as exc:
|
||||
logger.warning("S3 PUT failed: %s", exc)
|
||||
_in_background(_discard_after_failed_put(object_key))
|
||||
raise Unavailable() from None
|
||||
|
||||
if settings.fault_injection == "crash_after_s3_put":
|
||||
logger.error("FAULT_INJECTION: process exits after S3 PUT, before COMMIT")
|
||||
os._exit(1)
|
||||
|
||||
try:
|
||||
if settings.fault_injection == "db_error_after_s3_put":
|
||||
raise ConnectionError("FAULT_INJECTION: database lost after S3 PUT")
|
||||
|
||||
row = await repositories.finalize_attachment(
|
||||
db,
|
||||
attachment_id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=owner_id,
|
||||
filename=filename,
|
||||
content_type=content_type,
|
||||
size_bytes=size,
|
||||
sha256=sha256,
|
||||
width=width,
|
||||
height=height,
|
||||
object_key=object_key,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("attachment COMMIT failed after S3 PUT: %s", type(exc).__name__)
|
||||
_in_background(_compensate_failed_commit(object_key))
|
||||
raise Unavailable() from None
|
||||
|
||||
if row is None:
|
||||
# The janitor already claimed this intent (upload slower than the
|
||||
# grace period): the object is (being) deleted, report a failure.
|
||||
logger.warning("upload intent expired before COMMIT")
|
||||
raise Unavailable()
|
||||
|
||||
return _to_attachment(row)
|
||||
|
||||
|
||||
async def get_attachment(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
row = await repositories.get_accessible_attachment(
|
||||
db, attachment_id=attachment_id, user_id=current_user["id"]
|
||||
)
|
||||
if row is None:
|
||||
raise NotFound()
|
||||
return _to_attachment(row)
|
||||
|
||||
|
||||
async def open_attachment_content(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
variant: str,
|
||||
current_user: dict[str, Any],
|
||||
) -> tuple[AsyncIterator[bytes], dict[str, str]]:
|
||||
"""Authorize in PostgreSQL, then stream the bytes from S3 (no redirect)."""
|
||||
row = await repositories.get_accessible_attachment(
|
||||
db, attachment_id=attachment_id, user_id=current_user["id"]
|
||||
)
|
||||
if row is None:
|
||||
raise NotFound()
|
||||
await db.rollback()
|
||||
|
||||
if row["status"] != "ready":
|
||||
raise Conflict("Attachment content is not ready.")
|
||||
|
||||
content = row
|
||||
if variant != "original":
|
||||
content = next((item for item in _variants(row) if item["name"] == variant), None)
|
||||
if content is None:
|
||||
raise NotFound()
|
||||
|
||||
try:
|
||||
chunks, length = await storage.open_download(content["object_key"])
|
||||
except StorageUnavailable as exc:
|
||||
logger.warning("S3 GET failed: %s", exc)
|
||||
raise Unavailable() from None
|
||||
except ObjectMissing:
|
||||
# Metadata says "ready" but the bytes are gone: an inconsistency,
|
||||
# not a user error (logged as ERROR).
|
||||
logger.error("object of attachment %s is missing in S3", attachment_id)
|
||||
raise
|
||||
|
||||
if length != content["size_bytes"]:
|
||||
logger.error("object of attachment %s has a wrong size", attachment_id)
|
||||
raise ObjectMissing(content["object_key"])
|
||||
|
||||
headers = {
|
||||
"Content-Type": content["content_type"],
|
||||
"Content-Length": str(length),
|
||||
"Content-Disposition": "inline; filename*=UTF-8''"
|
||||
+ quote(row["filename"], safe=""),
|
||||
"ETag": f'"{content["sha256"]}"',
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
}
|
||||
return chunks, headers
|
||||
|
||||
|
||||
def _in_background(compensation) -> None:
|
||||
"""Do not keep the client waiting for compensation: with S3 down each
|
||||
attempt takes up to S3_OPERATION_TIMEOUT_SECONDS, and the answer is 503
|
||||
anyway."""
|
||||
task = asyncio.create_task(compensation)
|
||||
_compensations.add(task)
|
||||
task.add_done_callback(_compensations.discard)
|
||||
|
||||
|
||||
# --- Janitor ----------------------------------------------------------------
|
||||
|
||||
async def cleanup_stale_uploads(grace_seconds: int, limit: int = 100) -> int:
|
||||
"""Delete objects of upload intents older than the grace period.
|
||||
|
||||
One intent per transaction: lock it (SKIP LOCKED), delete the object in
|
||||
S3 (idempotent), delete the intent, COMMIT. If S3 is down, roll back and
|
||||
stop: the intent stays and the next run retries.
|
||||
"""
|
||||
cleaned = 0
|
||||
for _ in range(limit):
|
||||
async with SessionLocal() as db:
|
||||
row = await repositories.lock_stale_intent(db, grace_seconds)
|
||||
if row is None:
|
||||
await db.rollback()
|
||||
break
|
||||
|
||||
if not row["committed"]:
|
||||
try:
|
||||
await storage.delete(row["object_key"])
|
||||
except StorageUnavailable:
|
||||
await db.rollback()
|
||||
logger.warning("janitor: S3 unavailable, will retry")
|
||||
break
|
||||
|
||||
await repositories.delete_upload_intent(db, row["object_key"])
|
||||
cleaned += 1
|
||||
logger.warning(
|
||||
"janitor: removed abandoned upload %s (object %s)",
|
||||
row["object_key"],
|
||||
"kept, row committed" if row["committed"] else "deleted",
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
async def janitor_loop() -> None:
|
||||
while True:
|
||||
# Jitter: replicas do not all wake up at the same moment.
|
||||
await asyncio.sleep(settings.janitor_interval_seconds * random.uniform(0.8, 1.2))
|
||||
try:
|
||||
await cleanup_stale_uploads(settings.upload_grace_seconds)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.warning("janitor run failed: %s", type(exc).__name__)
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
"""Valkey session cache.
|
||||
|
||||
PostgreSQL is the source of truth for sessions. Valkey only keeps a short
|
||||
lived copy of "token hash -> user" to avoid a SQL lookup on every request:
|
||||
|
||||
- key: messenger:session:<sha256(token)>, the raw token is never stored;
|
||||
- value TTL: min(SESSION_CACHE_TTL_SECONDS, remaining session lifetime),
|
||||
and expires_at is checked again on every read;
|
||||
- logout writes a "revoked" tombstone (SET ... EX, overwrite), while cache
|
||||
population uses SET ... NX, so a concurrent request cannot resurrect a
|
||||
revoked session in the cache;
|
||||
- any Valkey error or timeout is a cache miss: requests go to PostgreSQL and
|
||||
the cache is skipped for CACHE_RETRY_AFTER_SECONDS. After such an error,
|
||||
and on every API process start, the cache is flushed before its next use,
|
||||
because an invalidation may have been lost while Valkey was unreachable
|
||||
(also by a previous API process).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from redis.asyncio import ConnectionPool, Redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
logger = logging.getLogger("messenger.cache")
|
||||
|
||||
KEY_PREFIX = "messenger:session:"
|
||||
REVOKED = "revoked"
|
||||
|
||||
|
||||
class Revoked:
|
||||
"""Marker returned when the cache knows the session was revoked."""
|
||||
|
||||
|
||||
REVOKED_SESSION = Revoked()
|
||||
|
||||
|
||||
def _key(token_hash: str) -> str:
|
||||
return KEY_PREFIX + token_hash
|
||||
|
||||
|
||||
def _serialize(user: dict[str, Any], expires_at: datetime) -> str:
|
||||
return json.dumps(
|
||||
{
|
||||
"id": str(user["id"]),
|
||||
"username": user["username"],
|
||||
"display_name": user["display_name"],
|
||||
"created_at": user["created_at"].isoformat(),
|
||||
"expires_at": expires_at.isoformat(),
|
||||
},
|
||||
separators=(",", ":"),
|
||||
)
|
||||
|
||||
|
||||
def _deserialize(raw: str) -> tuple[dict[str, Any], datetime]:
|
||||
payload = json.loads(raw)
|
||||
user = {
|
||||
"id": UUID(payload["id"]),
|
||||
"username": payload["username"],
|
||||
"display_name": payload["display_name"],
|
||||
"created_at": datetime.fromisoformat(payload["created_at"]),
|
||||
}
|
||||
return user, datetime.fromisoformat(payload["expires_at"])
|
||||
|
||||
|
||||
class SessionCache:
|
||||
def __init__(self, url: str | None) -> None:
|
||||
self._client: Redis | None = None
|
||||
self._unavailable_until = 0.0
|
||||
# A process never trusts a cache it has not flushed itself: an
|
||||
# earlier process may have lost an invalidation (logout while
|
||||
# Valkey was unreachable) and that knowledge died with it.
|
||||
# Cleared only after a successful FLUSHDB.
|
||||
self._needs_flush = True
|
||||
|
||||
if url:
|
||||
pool = ConnectionPool.from_url(
|
||||
url,
|
||||
max_connections=settings.cache_max_connections,
|
||||
socket_timeout=settings.cache_timeout_seconds,
|
||||
socket_connect_timeout=settings.cache_timeout_seconds,
|
||||
decode_responses=True,
|
||||
)
|
||||
self._client = Redis(connection_pool=pool)
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return self._client is not None
|
||||
|
||||
async def _run(self, operation):
|
||||
"""Run one cache operation; return (ok, result)."""
|
||||
if self._client is None:
|
||||
return False, None
|
||||
|
||||
if time.monotonic() < self._unavailable_until:
|
||||
return False, None
|
||||
|
||||
try:
|
||||
async with asyncio.timeout(settings.cache_timeout_seconds * 2):
|
||||
if self._needs_flush:
|
||||
await self._client.flushdb()
|
||||
self._needs_flush = False
|
||||
logger.warning("session cache flushed before use")
|
||||
return True, await operation(self._client)
|
||||
except (RedisError, OSError, TimeoutError) as exc:
|
||||
self._unavailable_until = (
|
||||
time.monotonic() + settings.cache_retry_after_seconds
|
||||
)
|
||||
self._needs_flush = True
|
||||
logger.warning(
|
||||
"session cache unavailable, falling back to PostgreSQL: %s",
|
||||
type(exc).__name__,
|
||||
)
|
||||
return False, None
|
||||
|
||||
async def get(
|
||||
self,
|
||||
token_hash: str,
|
||||
) -> dict[str, Any] | Revoked | None:
|
||||
ok, raw = await self._run(lambda client: client.get(_key(token_hash)))
|
||||
|
||||
if not ok or raw is None:
|
||||
return None
|
||||
|
||||
if raw == REVOKED:
|
||||
return REVOKED_SESSION
|
||||
|
||||
try:
|
||||
user, expires_at = _deserialize(raw)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return None
|
||||
|
||||
if expires_at <= datetime.now(timezone.utc):
|
||||
return None
|
||||
|
||||
return user
|
||||
|
||||
async def put(
|
||||
self,
|
||||
token_hash: str,
|
||||
user: dict[str, Any],
|
||||
expires_at: datetime,
|
||||
) -> None:
|
||||
remaining = (expires_at - datetime.now(timezone.utc)).total_seconds()
|
||||
ttl = min(settings.session_cache_ttl_seconds, math.floor(remaining))
|
||||
|
||||
if ttl < 1:
|
||||
return
|
||||
|
||||
value = _serialize(user, expires_at)
|
||||
await self._run(
|
||||
lambda client: client.set(_key(token_hash), value, ex=ttl, nx=True)
|
||||
)
|
||||
|
||||
async def revoke(self, token_hash: str) -> None:
|
||||
await self._run(
|
||||
lambda client: client.set(
|
||||
_key(token_hash),
|
||||
REVOKED,
|
||||
ex=settings.session_cache_ttl_seconds,
|
||||
)
|
||||
)
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._client is not None:
|
||||
await self._client.aclose()
|
||||
|
||||
|
||||
session_cache = SessionCache(settings.cache_url)
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
import os
|
||||
import socket
|
||||
|
||||
|
||||
def read_value(name: str, default: str | None = None) -> str:
|
||||
file_name = os.getenv(f"{name}_FILE")
|
||||
|
||||
if file_name:
|
||||
return Path(file_name).read_text(encoding="utf-8").strip()
|
||||
|
||||
value = os.getenv(name, default)
|
||||
|
||||
if value is None:
|
||||
raise RuntimeError(f"{name} is required.")
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def read_positive_int(name: str, default: str) -> int:
|
||||
value = int(os.getenv(name, default))
|
||||
|
||||
if value < 1:
|
||||
raise RuntimeError(f"{name} must be positive.")
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def read_positive_float(name: str, default: str) -> float:
|
||||
value = float(os.getenv(name, default))
|
||||
|
||||
if value <= 0:
|
||||
raise RuntimeError(f"{name} must be positive.")
|
||||
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
app_host: str
|
||||
app_port: int
|
||||
database_url: str
|
||||
session_ttl_seconds: int
|
||||
# PostgreSQL connection pool and timeouts.
|
||||
db_pool_size: int
|
||||
db_max_overflow: int
|
||||
db_pool_timeout_seconds: float
|
||||
db_connect_timeout_seconds: float
|
||||
db_statement_timeout_ms: int
|
||||
# Valkey is a session cache; PostgreSQL stays the source of truth.
|
||||
cache_url: str | None
|
||||
session_cache_ttl_seconds: int
|
||||
cache_timeout_seconds: float
|
||||
cache_max_connections: int
|
||||
cache_retry_after_seconds: float
|
||||
# Lab3: X-Instance-Id is the container hostname (short Docker ID), stable
|
||||
# for the process lifetime; scripts/stop-one.sh maps it to a container.
|
||||
instance_id: str
|
||||
idempotency_ttl_seconds: int
|
||||
# Graceful shutdown: readiness answers 503 for shutdown_drain_seconds so
|
||||
# the LB drops this replica, then uvicorn closes the listener and waits
|
||||
# for in-flight requests up to shutdown_timeout_seconds.
|
||||
shutdown_drain_seconds: float
|
||||
shutdown_timeout_seconds: int
|
||||
# Lab4: attachments. Metadata lives in PostgreSQL, bytes in a private
|
||||
# S3 bucket; the API uses its own restricted credentials (not root).
|
||||
s3_endpoint: str
|
||||
s3_region: str
|
||||
s3_bucket: str
|
||||
s3_access_key_id: str
|
||||
s3_secret_access_key: str
|
||||
s3_object_prefix: str
|
||||
s3_connect_timeout_seconds: float
|
||||
s3_read_timeout_seconds: float
|
||||
# Deadline of one whole S3 call (DNS + retries included), below the LB
|
||||
# "timeout server" (10 s): a stopped S3 container makes Docker DNS hang
|
||||
# ~8 s per lookup, which connect_timeout does not cover.
|
||||
s3_operation_timeout_seconds: float
|
||||
# PUT gets operation timeout + size / this rate: 10 MiB under load is
|
||||
# slower than a HEAD. HAProxy allows 40 s for an upload POST.
|
||||
s3_put_min_bytes_per_second: int
|
||||
max_upload_bytes: int
|
||||
max_image_pixels: int
|
||||
# One upload may not take unlimited RAM/time: the body is spooled to a
|
||||
# temporary file (only upload_spool_memory_bytes stay in RAM), receiving
|
||||
# it is limited by upload_timeout_seconds, and at most
|
||||
# max_concurrent_uploads uploads per replica run at once.
|
||||
upload_spool_memory_bytes: int
|
||||
upload_timeout_seconds: float
|
||||
max_concurrent_uploads: int
|
||||
upload_slot_wait_seconds: float
|
||||
# Janitor: an upload intent older than upload_grace_seconds means the
|
||||
# request died between S3 PUT and COMMIT; its object is deleted.
|
||||
upload_grace_seconds: int
|
||||
janitor_interval_seconds: float
|
||||
# Experiments only (see REPORT.md): "" | crash_after_s3_put | db_error_after_s3_put
|
||||
fault_injection: str
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
session_store = os.getenv("SESSION_STORE", "postgres").lower()
|
||||
|
||||
if session_store not in {"postgres", "valkey", "redis"}:
|
||||
raise RuntimeError("SESSION_STORE must be postgres, valkey or redis.")
|
||||
|
||||
cache_url = None
|
||||
if session_store != "postgres":
|
||||
cache_url = read_value("CACHE_URL")
|
||||
|
||||
return Settings(
|
||||
app_host=os.getenv("APP_HOST", "0.0.0.0"),
|
||||
app_port=int(os.getenv("APP_PORT", "8080")),
|
||||
database_url=read_value("DATABASE_URL"),
|
||||
session_ttl_seconds=read_positive_int("SESSION_TTL_SECONDS", "3600"),
|
||||
db_pool_size=read_positive_int("DB_POOL_SIZE", "10"),
|
||||
db_max_overflow=int(os.getenv("DB_MAX_OVERFLOW", "5")),
|
||||
db_pool_timeout_seconds=read_positive_float("DB_POOL_TIMEOUT_SECONDS", "3"),
|
||||
db_connect_timeout_seconds=read_positive_float(
|
||||
"DB_CONNECT_TIMEOUT_SECONDS", "3"
|
||||
),
|
||||
db_statement_timeout_ms=read_positive_int("DB_STATEMENT_TIMEOUT_MS", "5000"),
|
||||
cache_url=cache_url,
|
||||
session_cache_ttl_seconds=read_positive_int(
|
||||
"SESSION_CACHE_TTL_SECONDS", "60"
|
||||
),
|
||||
cache_timeout_seconds=read_positive_float("CACHE_TIMEOUT_SECONDS", "0.25"),
|
||||
cache_max_connections=read_positive_int("CACHE_MAX_CONNECTIONS", "20"),
|
||||
cache_retry_after_seconds=read_positive_float(
|
||||
"CACHE_RETRY_AFTER_SECONDS", "5"
|
||||
),
|
||||
instance_id=os.getenv("INSTANCE_ID") or socket.gethostname(),
|
||||
idempotency_ttl_seconds=read_positive_int(
|
||||
"IDEMPOTENCY_TTL_SECONDS", "86400"
|
||||
),
|
||||
shutdown_drain_seconds=read_positive_float(
|
||||
"SHUTDOWN_DRAIN_SECONDS", "3"
|
||||
),
|
||||
shutdown_timeout_seconds=read_positive_int(
|
||||
"SHUTDOWN_TIMEOUT_SECONDS", "8"
|
||||
),
|
||||
s3_endpoint=read_value("S3_ENDPOINT", "http://s3:9000"),
|
||||
s3_region=os.getenv("S3_REGION", "us-east-1"),
|
||||
s3_bucket=read_value("S3_BUCKET", "messenger-attachments"),
|
||||
s3_access_key_id=read_value("S3_ACCESS_KEY_ID"),
|
||||
s3_secret_access_key=read_value("S3_SECRET_ACCESS_KEY"),
|
||||
s3_object_prefix=os.getenv("S3_OBJECT_PREFIX", "originals/"),
|
||||
s3_connect_timeout_seconds=read_positive_float(
|
||||
"S3_CONNECT_TIMEOUT_SECONDS", "2"
|
||||
),
|
||||
s3_read_timeout_seconds=read_positive_float(
|
||||
"S3_READ_TIMEOUT_SECONDS", "5"
|
||||
),
|
||||
s3_operation_timeout_seconds=read_positive_float(
|
||||
"S3_OPERATION_TIMEOUT_SECONDS", "6"
|
||||
),
|
||||
s3_put_min_bytes_per_second=read_positive_int(
|
||||
"S3_PUT_MIN_BYTES_PER_SECOND", "1048576"
|
||||
),
|
||||
max_upload_bytes=read_positive_int("MAX_UPLOAD_BYTES", "10485760"),
|
||||
max_image_pixels=read_positive_int("MAX_IMAGE_PIXELS", "40000000"),
|
||||
upload_spool_memory_bytes=read_positive_int(
|
||||
"UPLOAD_SPOOL_MEMORY_BYTES", "1048576"
|
||||
),
|
||||
upload_timeout_seconds=read_positive_float(
|
||||
"UPLOAD_TIMEOUT_SECONDS", "60"
|
||||
),
|
||||
max_concurrent_uploads=read_positive_int("MAX_CONCURRENT_UPLOADS", "8"),
|
||||
upload_slot_wait_seconds=read_positive_float(
|
||||
"UPLOAD_SLOT_WAIT_SECONDS", "10"
|
||||
),
|
||||
upload_grace_seconds=read_positive_int("UPLOAD_GRACE_SECONDS", "900"),
|
||||
janitor_interval_seconds=read_positive_float(
|
||||
"JANITOR_INTERVAL_SECONDS", "60"
|
||||
),
|
||||
fault_injection=os.getenv("FAULT_INJECTION", ""),
|
||||
)
|
||||
|
||||
|
||||
settings = load_settings()
|
||||
@@ -0,0 +1,57 @@
|
||||
from collections.abc import AsyncGenerator
|
||||
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncSession,
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
)
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
database_url = settings.database_url.replace(
|
||||
"postgresql://",
|
||||
"postgresql+asyncpg://",
|
||||
1,
|
||||
)
|
||||
|
||||
# Bounded pool: at most db_pool_size + db_max_overflow connections per API
|
||||
# process. Waiting for a free connection, connecting and every statement are
|
||||
# limited, so an unavailable database produces a fast 503 instead of a hang.
|
||||
engine = create_async_engine(
|
||||
database_url,
|
||||
pool_pre_ping=True,
|
||||
pool_size=settings.db_pool_size,
|
||||
max_overflow=settings.db_max_overflow,
|
||||
pool_timeout=settings.db_pool_timeout_seconds,
|
||||
pool_recycle=1800,
|
||||
connect_args={
|
||||
"timeout": settings.db_connect_timeout_seconds,
|
||||
"command_timeout": settings.db_statement_timeout_ms / 1000 + 1,
|
||||
"server_settings": {
|
||||
"statement_timeout": str(settings.db_statement_timeout_ms),
|
||||
"idle_in_transaction_session_timeout": "10000",
|
||||
"application_name": "messenger-api",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
SessionLocal = async_sessionmaker(
|
||||
bind=engine,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with SessionLocal() as session:
|
||||
yield session
|
||||
|
||||
|
||||
async def check_database_ready() -> bool:
|
||||
try:
|
||||
async with engine.connect() as connection:
|
||||
await connection.exec_driver_sql("SELECT 1")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
"""
|
||||
FastAPI dependencies for Lab2:
|
||||
- Bearer authentication;
|
||||
- pagination query parameters.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, Query, Request, Security
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBasic, HTTPBearer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db import get_db
|
||||
from app.errors import Unauthorized
|
||||
from app.services import current_user_from_bearer_token
|
||||
|
||||
|
||||
# Security schemes make the "Authorize" button in /docs send real
|
||||
# Authorization headers. Errors keep the contract format: auto_error=False
|
||||
# and our own 401 responses.
|
||||
bearer_scheme = HTTPBearer(
|
||||
scheme_name="Bearer",
|
||||
auto_error=False,
|
||||
description="Opaque session token from POST /api/v1/auth/sessions.",
|
||||
)
|
||||
|
||||
|
||||
class BasicForDocs(HTTPBasic):
|
||||
"""Documents Basic auth; the header is parsed by app.security."""
|
||||
|
||||
async def __call__(self, request: Request) -> None: # type: ignore[override]
|
||||
return None
|
||||
|
||||
|
||||
basic_scheme = BasicForDocs(
|
||||
scheme_name="Basic",
|
||||
auto_error=False,
|
||||
description="Only for POST /api/v1/auth/sessions.",
|
||||
)
|
||||
|
||||
|
||||
async def require_user(
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Security(
|
||||
bearer_scheme
|
||||
),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict:
|
||||
if credentials is None or not credentials.credentials.strip():
|
||||
raise Unauthorized("Bearer")
|
||||
|
||||
return await current_user_from_bearer_token(
|
||||
db,
|
||||
credentials.credentials.strip(),
|
||||
)
|
||||
|
||||
|
||||
def pagination_params(
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
) -> tuple[int, Optional[str]]:
|
||||
return limit, cursor
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import re
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from uuid import uuid4
|
||||
|
||||
from app.config import settings
|
||||
from app.lifecycle import draining
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(
|
||||
self,
|
||||
status_code: int,
|
||||
code: str,
|
||||
message: str,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> None:
|
||||
self.status_code = status_code
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
class InvalidRequest(ApiError):
|
||||
def __init__(self, message: str = "Invalid request.") -> None:
|
||||
super().__init__(400, "invalid_request", message)
|
||||
|
||||
|
||||
class Unauthorized(ApiError):
|
||||
def __init__(self, scheme: str = "Bearer") -> None:
|
||||
if scheme == "Basic":
|
||||
challenge = 'Basic realm="messenger", charset="UTF-8"'
|
||||
else:
|
||||
challenge = 'Bearer realm="messenger"'
|
||||
|
||||
super().__init__(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Authentication is required.",
|
||||
{"WWW-Authenticate": challenge},
|
||||
)
|
||||
|
||||
|
||||
class NotFound(ApiError):
|
||||
def __init__(self, message: str = "Object not found.") -> None:
|
||||
super().__init__(404, "not_found", message)
|
||||
|
||||
|
||||
class Conflict(ApiError):
|
||||
def __init__(self, message: str = "Conflict.") -> None:
|
||||
super().__init__(409, "conflict", message)
|
||||
|
||||
|
||||
class Unavailable(ApiError):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(503, "unavailable", "Service is unavailable.")
|
||||
|
||||
|
||||
class PayloadTooLarge(ApiError):
|
||||
def __init__(self, message: str = "Payload is too large.") -> None:
|
||||
super().__init__(413, "payload_too_large", message)
|
||||
|
||||
|
||||
class UnsupportedMediaType(ApiError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Only PNG and JPEG images are accepted.",
|
||||
) -> None:
|
||||
super().__init__(415, "unsupported_media_type", message)
|
||||
|
||||
|
||||
class RateLimited(ApiError):
|
||||
def __init__(self, message: str, retry_after_seconds: int = 1) -> None:
|
||||
super().__init__(
|
||||
429,
|
||||
"rate_limited",
|
||||
message,
|
||||
{"Retry-After": str(retry_after_seconds)},
|
||||
)
|
||||
|
||||
# X-Request-Id from HAProxy (or the client) is reused only if it is short and
|
||||
# printable; anything else is replaced, so it cannot inject into logs.
|
||||
REQUEST_ID_PATTERN = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
||||
|
||||
|
||||
def incoming_request_id(request: Request) -> str:
|
||||
value = request.headers.get("X-Request-Id", "")
|
||||
if REQUEST_ID_PATTERN.fullmatch(value):
|
||||
return value
|
||||
return str(uuid4())
|
||||
|
||||
|
||||
def request_id(request: Request) -> str:
|
||||
return getattr(request.state, "request_id", str(uuid4()))
|
||||
|
||||
|
||||
def common_headers(request: Request) -> dict[str, str]:
|
||||
"""Headers of every API response, including errors (lab3: X-Instance-Id)."""
|
||||
headers = {
|
||||
"X-Request-Id": request_id(request),
|
||||
"X-Instance-Id": settings.instance_id,
|
||||
}
|
||||
if draining.is_set():
|
||||
# Ask HAProxy not to reuse the connection to a replica that is stopping.
|
||||
headers["Connection"] = "close"
|
||||
return headers
|
||||
|
||||
|
||||
async def api_error_handler(
|
||||
request: Request,
|
||||
exc: ApiError,
|
||||
) -> JSONResponse:
|
||||
rid = request_id(request)
|
||||
|
||||
headers = {
|
||||
**common_headers(request),
|
||||
**exc.headers,
|
||||
}
|
||||
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"error": {
|
||||
"code": exc.code,
|
||||
"message": exc.message,
|
||||
"request_id": rid,
|
||||
}
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Disposable, resource-limited image decoder. No app credentials/config.
|
||||
|
||||
Usage: python -m app.image_worker INPUT OUTPUT_DIR. Result is manifest.json.
|
||||
All input comes from a trusted staging object selected by the worker in PG.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import warnings
|
||||
|
||||
|
||||
def fit_size(width: int, height: int, limit: int) -> tuple[int, int]:
|
||||
largest = max(width, height)
|
||||
if largest <= limit:
|
||||
return width, height
|
||||
return max(1, width * limit // largest), max(1, height * limit // largest)
|
||||
|
||||
|
||||
def convert(source: Path, directory: Path) -> list[dict]:
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(source) as opened:
|
||||
if opened.format not in {"PNG", "JPEG"}:
|
||||
raise ValueError("invalid_image")
|
||||
if opened.width * opened.height > Image.MAX_IMAGE_PIXELS:
|
||||
raise ValueError("image_too_large")
|
||||
opened.load()
|
||||
oriented = ImageOps.exif_transpose(opened)
|
||||
# Detach metadata and use fixed output modes. The original file
|
||||
# itself is never rewritten; EXIF orientation affects variants only.
|
||||
image = oriented.convert("RGBA" if "A" in oriented.getbands() or
|
||||
"transparency" in oriented.info else "RGB")
|
||||
oriented.close()
|
||||
image.info.clear()
|
||||
if image.mode == "RGBA":
|
||||
rgb = Image.new("RGB", image.size, "white")
|
||||
rgb.paste(image, mask=image.getchannel("A"))
|
||||
else:
|
||||
rgb = image
|
||||
|
||||
variants = []
|
||||
|
||||
def save(name, result, filename, content_type, **options):
|
||||
path = directory / filename
|
||||
result.info.clear()
|
||||
result.save(path, **options)
|
||||
data = path.read_bytes()
|
||||
variants.append({"name": name, "filename": filename, "content_type": content_type,
|
||||
"width": result.width, "height": result.height,
|
||||
"size_bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()})
|
||||
if result is not rgb and result is not image:
|
||||
result.close()
|
||||
|
||||
save("thumbnail", rgb.resize(fit_size(*rgb.size, 256), Image.Resampling.LANCZOS),
|
||||
"thumbnail.jpg", "image/jpeg", format="JPEG", quality=85, optimize=True)
|
||||
save("crop", ImageOps.fit(rgb, (128, 128), method=Image.Resampling.LANCZOS,
|
||||
centering=(0.5, 0.5)),
|
||||
"crop.jpg", "image/jpeg", format="JPEG", quality=85, optimize=True)
|
||||
save("optimized", image.resize(fit_size(*image.size, 1280), Image.Resampling.LANCZOS),
|
||||
"optimized.webp", "image/webp", format="WEBP", quality=80, method=4)
|
||||
if rgb is not image:
|
||||
rgb.close()
|
||||
image.close()
|
||||
return variants
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# Linux container limits are inherited by every native decoder. Parent
|
||||
# enforces a wall timeout and kills/reaps this process on expiration.
|
||||
if sys.platform == "linux":
|
||||
import resource
|
||||
memory = int(os.getenv("WORKER_MEMORY_MB", "768")) * 1024 * 1024
|
||||
resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
|
||||
cpu = math.ceil(float(os.getenv("JOB_TIMEOUT_SECONDS", "30"))) + 1
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu))
|
||||
try:
|
||||
source, directory = Path(sys.argv[1]), Path(sys.argv[2])
|
||||
manifest = convert(source, directory)
|
||||
(directory / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
|
||||
return 0
|
||||
except MemoryError:
|
||||
return 21
|
||||
except Exception:
|
||||
return 20
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
"""Content-based validation of uploaded PNG/JPEG images.
|
||||
|
||||
The declared Content-Type is never trusted: the format is detected from the
|
||||
first bytes and must match it. Dimensions are read from the header and the
|
||||
pixel limit is applied BEFORE any decoding, so a small "pixel bomb" file
|
||||
cannot make the API allocate gigabytes.
|
||||
|
||||
- PNG is validated by our own streaming reader: critical chunks, CRC of every
|
||||
chunk, IHDR, and the IDAT zlib stream is decompressed in 64 KiB pieces.
|
||||
Scanline sizes and filter bytes (also in Adam7 passes) are checked without
|
||||
retaining any row. Memory stays O(64 KiB) for any image.
|
||||
- JPEG: Pillow reads the header (lazy open); then the image is decoded with
|
||||
draft() at 1/8 scale, which makes libjpeg read the whole entropy-coded
|
||||
stream (a truncated/corrupted file raises) while allocating only 1/64 of
|
||||
the full-size pixel buffer. Large progressive JPEGs can still retain DCT
|
||||
coefficients; the caller must bound concurrent validation and memory.
|
||||
Their entropy stream is checked as well: there is no header-only bypass.
|
||||
|
||||
The functions are synchronous (CPU work); call them via asyncio.to_thread.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
import zlib
|
||||
from dataclasses import dataclass
|
||||
from typing import BinaryIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
# Our own limit is applied before Pillow decodes anything.
|
||||
Image.MAX_IMAGE_PIXELS = None
|
||||
|
||||
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
JPEG_SIGNATURE = b"\xff\xd8\xff"
|
||||
CHUNK = 64 * 1024
|
||||
|
||||
|
||||
class InvalidImage(Exception):
|
||||
"""Not a PNG/JPEG, a corrupted file or a Content-Type mismatch (-> 415)."""
|
||||
|
||||
|
||||
class TooManyPixels(Exception):
|
||||
"""Decoded image would exceed MAX_IMAGE_PIXELS (-> 413)."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ImageInfo:
|
||||
content_type: str
|
||||
width: int
|
||||
height: int
|
||||
|
||||
|
||||
def sniff_content_type(head: bytes) -> str | None:
|
||||
if head.startswith(PNG_SIGNATURE):
|
||||
return "image/png"
|
||||
if head.startswith(JPEG_SIGNATURE):
|
||||
return "image/jpeg"
|
||||
return None
|
||||
|
||||
|
||||
def validate_image(
|
||||
file: BinaryIO,
|
||||
declared_content_type: str,
|
||||
max_pixels: int,
|
||||
) -> ImageInfo:
|
||||
file.seek(0)
|
||||
detected = sniff_content_type(file.read(len(PNG_SIGNATURE)))
|
||||
file.seek(0)
|
||||
|
||||
if detected is None:
|
||||
raise InvalidImage("Content is not a PNG or JPEG image.")
|
||||
|
||||
if detected != declared_content_type:
|
||||
raise InvalidImage("Content-Type does not match the image content.")
|
||||
|
||||
if detected == "image/png":
|
||||
width, height = _validate_png(file, max_pixels)
|
||||
else:
|
||||
width, height = _validate_jpeg(file, max_pixels)
|
||||
|
||||
return ImageInfo(detected, width, height)
|
||||
|
||||
|
||||
# --- PNG -------------------------------------------------------------------
|
||||
|
||||
# color type -> (channels, allowed bit depths)
|
||||
_PNG_COLOR_TYPES = {
|
||||
0: (1, {1, 2, 4, 8, 16}),
|
||||
2: (3, {8, 16}),
|
||||
3: (1, {1, 2, 4, 8}),
|
||||
4: (2, {8, 16}),
|
||||
6: (4, {8, 16}),
|
||||
}
|
||||
_ADAM7_PASSES = (
|
||||
(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4),
|
||||
(0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2),
|
||||
)
|
||||
|
||||
|
||||
def _read_exact(file: BinaryIO, size: int) -> bytes:
|
||||
data = file.read(size)
|
||||
if len(data) != size:
|
||||
raise InvalidImage("Image file is truncated.")
|
||||
return data
|
||||
|
||||
|
||||
def _png_scanlines(width: int, height: int, bits_per_pixel: int,
|
||||
interlace: int) -> list[tuple[int, int]]:
|
||||
"""At most seven (packed row bytes, row count) pairs; no row allocation."""
|
||||
if interlace == 0:
|
||||
return [((width * bits_per_pixel + 7) // 8, height)]
|
||||
passes = []
|
||||
for x0, y0, dx, dy in _ADAM7_PASSES:
|
||||
w = (width - x0 + dx - 1) // dx if width > x0 else 0
|
||||
h = (height - y0 + dy - 1) // dy if height > y0 else 0
|
||||
if w and h:
|
||||
passes.append(((w * bits_per_pixel + 7) // 8, h))
|
||||
return passes
|
||||
|
||||
|
||||
class _PngScanlines:
|
||||
"""Validate filter positions across arbitrary decompression boundaries."""
|
||||
def __init__(self, passes: list[tuple[int, int]]) -> None:
|
||||
self.passes = iter(passes)
|
||||
self.row_bytes, self.rows_left = next(self.passes)
|
||||
self.row_remaining = 0
|
||||
self.expected = sum((row_bytes + 1) * count for row_bytes, count in passes)
|
||||
self.produced = 0
|
||||
|
||||
def feed(self, data: bytes) -> None:
|
||||
self.produced += len(data)
|
||||
if self.produced > self.expected:
|
||||
raise InvalidImage("PNG image data is larger than IHDR declares.")
|
||||
position = 0
|
||||
while position < len(data):
|
||||
if self.row_remaining == 0:
|
||||
if self.rows_left == 0:
|
||||
try:
|
||||
self.row_bytes, self.rows_left = next(self.passes)
|
||||
except StopIteration:
|
||||
raise InvalidImage("PNG has too many scanlines.") from None
|
||||
if data[position] > 4:
|
||||
raise InvalidImage("Invalid PNG scanline filter.")
|
||||
position += 1
|
||||
self.rows_left -= 1
|
||||
self.row_remaining = self.row_bytes
|
||||
consumed = min(self.row_remaining, len(data) - position)
|
||||
self.row_remaining -= consumed
|
||||
position += consumed
|
||||
|
||||
|
||||
def _validate_png(file: BinaryIO, max_pixels: int) -> tuple[int, int]:
|
||||
_read_exact(file, len(PNG_SIGNATURE))
|
||||
|
||||
width = height = 0
|
||||
scanlines = None
|
||||
inflater = zlib.decompressobj()
|
||||
color_type = -1
|
||||
bit_depth = 0
|
||||
seen_plte = False
|
||||
palette_entries = 0
|
||||
seen_trns = False
|
||||
idat_state = "before" # before -> inside -> after
|
||||
first = True
|
||||
|
||||
while True:
|
||||
header = _read_exact(file, 8)
|
||||
length, chunk_type = struct.unpack(">I4s", header)
|
||||
|
||||
if length > 0x7FFFFFFF:
|
||||
raise InvalidImage("Invalid PNG chunk length.")
|
||||
|
||||
if first and chunk_type != b"IHDR":
|
||||
raise InvalidImage("PNG must start with IHDR.")
|
||||
if not all(65 <= ch <= 90 or 97 <= ch <= 122 for ch in chunk_type) \
|
||||
or not 65 <= chunk_type[2] <= 90:
|
||||
raise InvalidImage("Invalid PNG chunk type.")
|
||||
if chunk_type == b"IHDR" and (not first or length != 13):
|
||||
# Check before reading/buffering: an attacker cannot turn a
|
||||
# bogus multi-megabyte IHDR into a large allocation.
|
||||
raise InvalidImage("Invalid or duplicate PNG IHDR.")
|
||||
if chunk_type[0] < 97 and chunk_type not in {b"IHDR", b"PLTE", b"IDAT", b"IEND"}:
|
||||
raise InvalidImage("Unknown critical PNG chunk.")
|
||||
if chunk_type == b"IEND" and length != 0:
|
||||
raise InvalidImage("Invalid PNG IEND.")
|
||||
if chunk_type == b"PLTE":
|
||||
if seen_plte or seen_trns or idat_state != "before" or color_type in {0, 4} \
|
||||
or not 3 <= length <= 768 or length % 3:
|
||||
raise InvalidImage("Invalid PNG palette.")
|
||||
palette_entries = length // 3
|
||||
if color_type == 3 and palette_entries > 1 << bit_depth:
|
||||
raise InvalidImage("PNG palette exceeds its bit depth.")
|
||||
if chunk_type == b"tRNS":
|
||||
valid_length = ((color_type == 0 and length == 2) or
|
||||
(color_type == 2 and length == 6) or
|
||||
(color_type == 3 and seen_plte and 1 <= length <= palette_entries))
|
||||
if seen_trns or idat_state != "before" or not valid_length:
|
||||
raise InvalidImage("Invalid PNG transparency chunk.")
|
||||
seen_trns = True
|
||||
|
||||
crc = zlib.crc32(chunk_type)
|
||||
is_idat = chunk_type == b"IDAT"
|
||||
|
||||
if is_idat:
|
||||
if idat_state == "after":
|
||||
raise InvalidImage("PNG IDAT chunks are not consecutive.")
|
||||
if color_type == 3 and not seen_plte:
|
||||
raise InvalidImage("PNG palette image without PLTE.")
|
||||
idat_state = "inside"
|
||||
elif idat_state == "inside":
|
||||
idat_state = "after"
|
||||
|
||||
data = b""
|
||||
remaining = length
|
||||
while remaining:
|
||||
piece = _read_exact(file, min(CHUNK, remaining))
|
||||
remaining -= len(piece)
|
||||
crc = zlib.crc32(piece, crc)
|
||||
|
||||
if is_idat:
|
||||
_inflate_scanlines(inflater, piece, scanlines)
|
||||
elif chunk_type == b"IHDR":
|
||||
data += piece
|
||||
|
||||
(stored_crc,) = struct.unpack(">I", _read_exact(file, 4))
|
||||
if stored_crc != crc:
|
||||
raise InvalidImage("PNG chunk CRC mismatch.")
|
||||
|
||||
if first:
|
||||
first = False
|
||||
(width, height, bit_depth, color_type,
|
||||
compression, filter_method, interlace) = struct.unpack(">IIBBBBB", data)
|
||||
|
||||
if width == 0 or height == 0 or width > 0x7FFFFFFF or height > 0x7FFFFFFF:
|
||||
raise InvalidImage("Invalid PNG dimensions.")
|
||||
if width * height > max_pixels:
|
||||
# Before a single IDAT byte is decompressed.
|
||||
raise TooManyPixels()
|
||||
if color_type not in _PNG_COLOR_TYPES:
|
||||
raise InvalidImage("Invalid PNG color type.")
|
||||
channels, depths = _PNG_COLOR_TYPES[color_type]
|
||||
if bit_depth not in depths or compression != 0 or filter_method != 0 \
|
||||
or interlace not in (0, 1):
|
||||
raise InvalidImage("Invalid PNG IHDR.")
|
||||
scanlines = _PngScanlines(
|
||||
_png_scanlines(width, height, channels * bit_depth, interlace)
|
||||
)
|
||||
elif chunk_type == b"PLTE":
|
||||
seen_plte = True
|
||||
elif chunk_type == b"IEND":
|
||||
break
|
||||
|
||||
if idat_state == "before":
|
||||
raise InvalidImage("PNG has no image data.")
|
||||
|
||||
# decompress(max_length) drains every unconsumed_tail above. No flush()
|
||||
# is needed (and its output would not have a strict allocation bound).
|
||||
if not inflater.eof or scanlines.produced != scanlines.expected:
|
||||
raise InvalidImage("PNG image data is corrupted or truncated.")
|
||||
|
||||
return width, height
|
||||
|
||||
|
||||
def _inflate_scanlines(inflater, data: bytes, scanlines: _PngScanlines) -> None:
|
||||
"""Decompress at most 64 KiB at once, validate, then discard."""
|
||||
try:
|
||||
while data:
|
||||
if inflater.eof:
|
||||
raise InvalidImage("PNG has data after the end of the zlib stream.")
|
||||
out = inflater.decompress(data, CHUNK)
|
||||
scanlines.feed(out)
|
||||
if inflater.unused_data:
|
||||
raise InvalidImage("PNG has data after the end of the zlib stream.")
|
||||
data = inflater.unconsumed_tail
|
||||
except zlib.error:
|
||||
raise InvalidImage("PNG image data is corrupted.") from None
|
||||
|
||||
|
||||
# --- JPEG ------------------------------------------------------------------
|
||||
|
||||
def _validate_jpeg(file: BinaryIO, max_pixels: int) -> tuple[int, int]:
|
||||
try:
|
||||
with Image.open(file, formats=["JPEG"]) as image:
|
||||
width, height = image.size
|
||||
|
||||
if width < 1 or height < 1:
|
||||
raise InvalidImage("Invalid JPEG dimensions.")
|
||||
if width * height > max_pixels:
|
||||
# Header only: no pixel has been decoded yet.
|
||||
raise TooManyPixels()
|
||||
|
||||
image.draft("RGB", (max(1, width // 8), max(1, height // 8)))
|
||||
image.load()
|
||||
except (InvalidImage, TooManyPixels):
|
||||
raise
|
||||
except Exception:
|
||||
# Pillow raises OSError/SyntaxError/ValueError/... for broken data.
|
||||
raise InvalidImage("JPEG image is corrupted or truncated.") from None
|
||||
|
||||
return width, height
|
||||
|
||||
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
"""Transactional outbox relay, expired-lease recovery and staging janitor.
|
||||
|
||||
DB COMMIT and RabbitMQ publish cannot be one transaction. Keep outbox rows
|
||||
until a publisher confirm, accepting harmless duplicate delivery on crash.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.db import SessionLocal, engine
|
||||
from app.pipeline import (RETENTION_SECONDS, arm_from_env, broker_channel,
|
||||
crash_if_armed, envelope, publish, retry_or_fail)
|
||||
from app.storage import storage
|
||||
|
||||
logger = logging.getLogger("messenger.jobs")
|
||||
|
||||
|
||||
async def recover_leases() -> int:
|
||||
async with SessionLocal() as db:
|
||||
result = await db.execute(text("""
|
||||
SELECT * FROM attachments WHERE status='processing' AND lease_until<now()
|
||||
ORDER BY lease_until LIMIT 20 FOR UPDATE SKIP LOCKED
|
||||
"""))
|
||||
rows = list(result.mappings())
|
||||
for row in rows:
|
||||
await retry_or_fail(db, row, "lease_expired")
|
||||
await db.commit()
|
||||
if rows:
|
||||
logger.warning("recovered expired leases count=%s", len(rows))
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def cleanup_staging() -> None:
|
||||
# One object transaction at a time: S3's bounded deadline is shorter
|
||||
# than idle_in_transaction_session_timeout. Replay takes the same lock.
|
||||
for _ in range(10):
|
||||
async with SessionLocal() as db:
|
||||
# Failed retention may remove five objects. Keep its row lock
|
||||
# until all bounded deletes finish, so replay cannot race it.
|
||||
await db.execute(text("SET LOCAL idle_in_transaction_session_timeout='60s'"))
|
||||
result = await db.execute(text("""
|
||||
SELECT * FROM attachments
|
||||
WHERE staging_key IS NOT NULL AND NOT staging_deleted AND
|
||||
(status='ready' OR (status='failed' AND updated_at <
|
||||
now()-make_interval(secs => :retention)))
|
||||
ORDER BY updated_at LIMIT 1 FOR UPDATE SKIP LOCKED
|
||||
"""), {"retention": RETENTION_SECONDS})
|
||||
row = result.mappings().first()
|
||||
if row is None:
|
||||
await db.rollback()
|
||||
return
|
||||
await storage.delete(row["staging_key"])
|
||||
# Partial final objects of an exhausted job are no longer
|
||||
# useful after retention; ready objects are never deleted.
|
||||
if row["status"] == "failed":
|
||||
prefix = row["object_key"].rsplit("/", 1)[0]
|
||||
for suffix in ("original", "thumbnail.jpg", "crop.jpg", "optimized.webp"):
|
||||
await storage.delete(f"{prefix}/{suffix}")
|
||||
await db.execute(text("""
|
||||
UPDATE attachments SET staging_deleted=true WHERE id=:id
|
||||
"""), {"id": row["id"]})
|
||||
await db.commit()
|
||||
logger.info("staging cleaned attachment=%s", row["id"])
|
||||
|
||||
|
||||
async def relay_one(channel) -> bool:
|
||||
async with SessionLocal() as db:
|
||||
result = await db.execute(text("""
|
||||
SELECT o.*,a.pipeline_version FROM outbox o
|
||||
JOIN attachments a ON a.id=o.attachment_id
|
||||
WHERE o.published_at IS NULL AND o.available_at<=now()
|
||||
ORDER BY o.id LIMIT 1 FOR UPDATE OF o SKIP LOCKED
|
||||
"""))
|
||||
row = result.mappings().first()
|
||||
if row is None:
|
||||
await db.rollback()
|
||||
return False
|
||||
# The upload COMMIT already exists; the pending row is untouched
|
||||
# by this crash, so the restarted relay finds it automatically.
|
||||
await crash_if_armed("crash_after_commit_before_publish")
|
||||
await publish(channel, envelope(row))
|
||||
await db.execute(text("UPDATE outbox SET published_at=now() WHERE id=:id"),
|
||||
{"id": row["id"]})
|
||||
await db.commit()
|
||||
logger.info("published job=%s attempt=%s", row["job_id"], row["attempt"])
|
||||
return True
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
for name in ("aio_pika", "aiormq"):
|
||||
logging.getLogger(name).setLevel(logging.CRITICAL)
|
||||
await storage.start()
|
||||
connection = None
|
||||
try:
|
||||
await arm_from_env("PUBLISHER_FAULT")
|
||||
while True:
|
||||
try:
|
||||
connection, channel, _ = await broker_channel()
|
||||
last_maintenance = 0.0
|
||||
while True:
|
||||
now = asyncio.get_running_loop().time()
|
||||
if now - last_maintenance > 1:
|
||||
await recover_leases()
|
||||
try:
|
||||
await cleanup_staging()
|
||||
except Exception as exc:
|
||||
# Retention is best effort. S3 failure must not
|
||||
# starve outbox delivery or exhaustible retries.
|
||||
logger.warning("staging cleanup deferred: %s", type(exc).__name__)
|
||||
last_maintenance = now
|
||||
if not await relay_one(channel):
|
||||
await asyncio.sleep(0.25)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
# Exception text can contain connection URLs. Log type only.
|
||||
logger.warning("relay unavailable: %s", type(exc).__name__)
|
||||
if connection:
|
||||
await connection.close()
|
||||
connection = None
|
||||
await asyncio.sleep(1)
|
||||
finally:
|
||||
if connection:
|
||||
await connection.close()
|
||||
await storage.close()
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Process lifecycle state shared by the server and request handlers."""
|
||||
import threading
|
||||
|
||||
# Set on the first SIGTERM/SIGINT. While draining, /health/ready answers 503
|
||||
# and responses carry "Connection: close", but requests are still served.
|
||||
draining = threading.Event()
|
||||
+460
@@ -0,0 +1,460 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from uuid import UUID
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, Query, Request, Response, Security
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from sqlalchemy import exc as sa_exc
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.attachments import (
|
||||
get_attachment,
|
||||
janitor_loop,
|
||||
open_attachment_content,
|
||||
upload_attachment,
|
||||
)
|
||||
from app.cache import session_cache
|
||||
from app.db import check_database_ready, engine, get_db
|
||||
from app.deps import basic_scheme, pagination_params, require_user
|
||||
from app.errors import (
|
||||
ApiError,
|
||||
InvalidRequest,
|
||||
Unavailable,
|
||||
api_error_handler,
|
||||
common_headers,
|
||||
incoming_request_id,
|
||||
)
|
||||
from app.lifecycle import draining
|
||||
from app.models import (
|
||||
Attachment,
|
||||
Chat,
|
||||
ChatPage,
|
||||
CreateChat,
|
||||
CreateMessage,
|
||||
CreateUser,
|
||||
Health,
|
||||
Message,
|
||||
MessagePage,
|
||||
Session,
|
||||
User,
|
||||
)
|
||||
from app.storage import storage
|
||||
from app.services import (
|
||||
create_chat,
|
||||
create_message,
|
||||
create_user_session,
|
||||
get_chat,
|
||||
list_chats,
|
||||
list_messages,
|
||||
logout_current_session,
|
||||
register_user,
|
||||
)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||
await storage.start()
|
||||
janitor = asyncio.create_task(janitor_loop())
|
||||
yield
|
||||
janitor.cancel()
|
||||
await asyncio.gather(janitor, return_exceptions=True)
|
||||
await storage.close()
|
||||
await session_cache.close()
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger — лабораторная 5",
|
||||
version="1.5.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_request_id(request: Request, call_next):
|
||||
request.state.request_id = incoming_request_id(request)
|
||||
|
||||
response = await call_next(request)
|
||||
response.headers.update(common_headers(request))
|
||||
return response
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def handle_api_error(
|
||||
request: Request,
|
||||
exc: Exception,
|
||||
) -> JSONResponse:
|
||||
if not isinstance(exc, ApiError):
|
||||
raise exc
|
||||
|
||||
return await api_error_handler(request, exc)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_error_handler(
|
||||
request: Request,
|
||||
exc: StarletteHTTPException,
|
||||
) -> JSONResponse:
|
||||
# Unknown routes/methods: the contract error format instead of
|
||||
# FastAPI's default {"detail": ...}.
|
||||
if exc.status_code == 404:
|
||||
error = ApiError(404, "not_found", "Route not found.")
|
||||
else:
|
||||
error = ApiError(exc.status_code, "invalid_request", "Invalid request.")
|
||||
|
||||
return await api_error_handler(request, error)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(
|
||||
request: Request,
|
||||
_exc: RequestValidationError,
|
||||
) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={
|
||||
"error": {
|
||||
"code": "invalid_request",
|
||||
"message": "Invalid request.",
|
||||
"request_id": common_headers(request)["X-Request-Id"],
|
||||
}
|
||||
},
|
||||
headers=common_headers(request),
|
||||
)
|
||||
|
||||
|
||||
logger = logging.getLogger("messenger.api")
|
||||
|
||||
|
||||
def is_dependency_failure(exc: Exception) -> bool:
|
||||
"""PostgreSQL is unreachable, restarting, overloaded or timed out."""
|
||||
if isinstance(
|
||||
exc,
|
||||
(
|
||||
sa_exc.OperationalError,
|
||||
sa_exc.InterfaceError,
|
||||
sa_exc.TimeoutError, # connection pool exhausted
|
||||
OSError,
|
||||
TimeoutError,
|
||||
),
|
||||
):
|
||||
return True
|
||||
|
||||
return isinstance(exc, sa_exc.DBAPIError) and exc.connection_invalidated
|
||||
|
||||
|
||||
async def dependency_error_handler(
|
||||
request: Request,
|
||||
exc: Exception,
|
||||
) -> JSONResponse:
|
||||
if not is_dependency_failure(exc):
|
||||
return await unexpected_error_handler(request, exc)
|
||||
|
||||
logger.warning("database unavailable: %s", type(exc).__name__)
|
||||
return await api_error_handler(request, Unavailable())
|
||||
|
||||
|
||||
for _exc_class in (sa_exc.DBAPIError, sa_exc.TimeoutError, OSError, TimeoutError):
|
||||
app.add_exception_handler(_exc_class, dependency_error_handler)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unexpected_error_handler(
|
||||
request: Request,
|
||||
exc: Exception,
|
||||
) -> JSONResponse:
|
||||
headers = common_headers(request)
|
||||
# Only the type: SQL parameters and headers may contain secrets.
|
||||
logger.error("unexpected error: %s", type(exc).__name__)
|
||||
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
"error": {
|
||||
"code": "internal_error",
|
||||
"message": "Internal server error.",
|
||||
"request_id": headers["X-Request-Id"],
|
||||
}
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/health/live",
|
||||
response_model=Health,
|
||||
)
|
||||
async def liveness() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get(
|
||||
"/health/ready",
|
||||
response_model=Health,
|
||||
)
|
||||
async def readiness() -> dict[str, str]:
|
||||
# A draining replica reports "not ready" so HAProxy stops sending new
|
||||
# requests to it before the listener is closed.
|
||||
# S3 is deliberately NOT checked: without it only attachments degrade
|
||||
# (503), users/chats/messages keep working. If readiness depended on S3,
|
||||
# an S3 outage would take every replica out of the LB.
|
||||
if draining.is_set() or not await check_database_ready():
|
||||
raise Unavailable()
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/users",
|
||||
status_code=201,
|
||||
response_model=User,
|
||||
)
|
||||
async def register_user_route(
|
||||
payload: CreateUser,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await register_user(
|
||||
db,
|
||||
username=payload.username,
|
||||
display_name=payload.display_name,
|
||||
password=payload.password,
|
||||
)
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/auth/sessions",
|
||||
status_code=201,
|
||||
response_model=Session,
|
||||
)
|
||||
async def login(
|
||||
request: Request,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_basic: None = Security(basic_scheme),
|
||||
):
|
||||
# Contract: login takes only "Authorization: Basic", no request body.
|
||||
# Any body (malformed JSON, "{}", ...) is rejected before the password check.
|
||||
if await request.body():
|
||||
raise InvalidRequest("POST /auth/sessions does not accept a request body.")
|
||||
|
||||
return await create_user_session(
|
||||
db,
|
||||
request.headers.get("Authorization"),
|
||||
)
|
||||
|
||||
|
||||
@app.delete(
|
||||
"/api/v1/auth/sessions/current",
|
||||
status_code=204,
|
||||
)
|
||||
async def logout(
|
||||
request: Request,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_current_user: dict = Depends(require_user),
|
||||
) -> Response:
|
||||
_, _, token = request.headers["Authorization"].partition(" ")
|
||||
|
||||
await logout_current_session(
|
||||
db,
|
||||
token.strip(),
|
||||
)
|
||||
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/users/me",
|
||||
response_model=User,
|
||||
)
|
||||
async def current_user_route(
|
||||
current_user: dict = Depends(require_user),
|
||||
):
|
||||
return current_user
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats",
|
||||
status_code=201,
|
||||
response_model=Chat,
|
||||
)
|
||||
async def create_chat_route(
|
||||
payload: CreateChat,
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await create_chat(
|
||||
db,
|
||||
title=payload.title,
|
||||
member_ids=payload.member_ids,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/chats",
|
||||
response_model=ChatPage,
|
||||
)
|
||||
async def list_chats_route(
|
||||
page: tuple[int, str | None] = Depends(pagination_params),
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
limit, cursor = page
|
||||
|
||||
return await list_chats(
|
||||
db,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/chats/{chat_id}",
|
||||
response_model=Chat,
|
||||
)
|
||||
async def get_chat_route(
|
||||
chat_id: UUID,
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await get_chat(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats/{chat_id}/messages",
|
||||
status_code=201,
|
||||
response_model=Message,
|
||||
)
|
||||
async def create_message_route(
|
||||
chat_id: UUID,
|
||||
payload: CreateMessage,
|
||||
response: Response,
|
||||
idempotency_key: str | None = Header(
|
||||
default=None,
|
||||
alias="Idempotency-Key",
|
||||
),
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
message, replayed = await create_message(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
text_value=payload.text,
|
||||
attachment_ids=payload.attachment_ids,
|
||||
idempotency_key=idempotency_key,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
if replayed:
|
||||
response.headers["Idempotent-Replayed"] = "true"
|
||||
|
||||
return message
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/chats/{chat_id}/messages",
|
||||
response_model=MessagePage,
|
||||
)
|
||||
async def list_messages_route(
|
||||
chat_id: UUID,
|
||||
page: tuple[int, str | None] = Depends(pagination_params),
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
limit, cursor = page
|
||||
|
||||
return await list_messages(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
|
||||
UPLOAD_BODY = {
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
"description": "Raw image bytes, not multipart and not JSON/base64.",
|
||||
"content": {
|
||||
"image/png": {"schema": {"type": "string", "format": "binary"}},
|
||||
"image/jpeg": {"schema": {"type": "string", "format": "binary"}},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats/{chat_id}/attachments",
|
||||
status_code=202,
|
||||
response_model=Attachment,
|
||||
openapi_extra=UPLOAD_BODY,
|
||||
)
|
||||
async def upload_attachment_route(
|
||||
chat_id: UUID,
|
||||
request: Request,
|
||||
filename: str = Query(min_length=1, max_length=255),
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await upload_attachment(
|
||||
request,
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
filename=filename,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/attachments/{attachment_id}",
|
||||
response_model=Attachment,
|
||||
)
|
||||
async def get_attachment_route(
|
||||
attachment_id: UUID,
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await get_attachment(
|
||||
db,
|
||||
attachment_id=attachment_id,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/attachments/{attachment_id}/content",
|
||||
response_class=StreamingResponse,
|
||||
responses={200: {"content": {"image/png": {}, "image/jpeg": {}, "image/webp": {}}}},
|
||||
)
|
||||
async def download_attachment_route(
|
||||
attachment_id: UUID,
|
||||
# Known variant names are accepted so that a ready attachment without
|
||||
# that variant answers 404 (contract); any other value is 400.
|
||||
variant: Literal["original", "thumbnail", "crop", "optimized"] = Query(
|
||||
default="original"
|
||||
),
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
chunks, headers = await open_attachment_content(
|
||||
db,
|
||||
attachment_id=attachment_id,
|
||||
variant=variant,
|
||||
current_user=current_user,
|
||||
)
|
||||
return StreamingResponse(
|
||||
chunks,
|
||||
media_type=headers.pop("Content-Type"),
|
||||
headers=headers,
|
||||
)
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
|
||||
class ApiModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class CreateUser(ApiModel):
|
||||
username: str = Field(
|
||||
min_length=3,
|
||||
max_length=32,
|
||||
pattern=r"^[a-z0-9_]{3,32}$",
|
||||
)
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def username_is_not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("username must not contain only spaces.")
|
||||
return value
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def display_name_is_not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError(
|
||||
"display_name must not contain only spaces."
|
||||
)
|
||||
return value
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def password_is_not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("password must not contain only spaces.")
|
||||
return value
|
||||
|
||||
|
||||
class User(ApiModel):
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
@field_validator("created_at")
|
||||
@classmethod
|
||||
def user_time_is_utc(cls, value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
raise ValueError("created_at must include UTC timezone.")
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
class CreateChat(ApiModel):
|
||||
# Contract: 1-100 code points (lab2 allowed 255 by mistake).
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
# Contract: 1-100 members (minItems/maxItems in openapi.json).
|
||||
member_ids: list[UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def title_is_not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("title must not contain only spaces.")
|
||||
return value
|
||||
|
||||
|
||||
class Chat(ApiModel):
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: list[UUID]
|
||||
created_at: datetime
|
||||
|
||||
@field_validator("created_at")
|
||||
@classmethod
|
||||
def chat_time_is_utc(cls, value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
raise ValueError("created_at must include UTC timezone.")
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
class ChatPage(ApiModel):
|
||||
items: list[Chat]
|
||||
next_cursor: str | None = None
|
||||
|
||||
|
||||
class CreateMessage(ApiModel):
|
||||
# Lab4: text may be "" when the message carries attachments.
|
||||
text: str = Field(max_length=4000)
|
||||
# 0-10 unique IDs of attachments of the same chat; missing == [].
|
||||
attachment_ids: list[UUID] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator("attachment_ids")
|
||||
@classmethod
|
||||
def attachment_ids_are_unique(cls, value: list[UUID]) -> list[UUID]:
|
||||
if len(set(value)) != len(value):
|
||||
raise ValueError("attachment_ids must be unique.")
|
||||
return value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def text_or_attachments(self) -> "CreateMessage":
|
||||
if not self.attachment_ids and not self.text.strip():
|
||||
raise ValueError(
|
||||
"text must not be blank when there are no attachments."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class Message(ApiModel):
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
attachment_ids: list[UUID] = Field(default_factory=list)
|
||||
|
||||
@field_validator("created_at")
|
||||
@classmethod
|
||||
def message_time_is_utc(cls, value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
raise ValueError("created_at must include UTC timezone.")
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
class MessagePage(ApiModel):
|
||||
items: list[Message]
|
||||
next_cursor: str | None = None
|
||||
|
||||
|
||||
class Session(ApiModel):
|
||||
token: str = Field(min_length=1)
|
||||
token_type: Literal["Bearer"]
|
||||
expires_at: datetime
|
||||
user: User
|
||||
|
||||
@field_validator("expires_at")
|
||||
@classmethod
|
||||
def expiry_time_is_utc(cls, value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
raise ValueError("expires_at must include UTC timezone.")
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
class Variant(ApiModel):
|
||||
name: Literal["thumbnail", "crop", "optimized"]
|
||||
content_type: Literal["image/jpeg", "image/png", "image/webp"]
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
|
||||
|
||||
class Attachment(ApiModel):
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
content_type: Literal["image/png", "image/jpeg"]
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: Literal["queued", "processing", "ready", "failed"]
|
||||
variants: list[Variant]
|
||||
error_code: str | None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@field_validator("created_at", "updated_at")
|
||||
@classmethod
|
||||
def attachment_time_is_utc(cls, value: datetime) -> datetime:
|
||||
if value.tzinfo is None:
|
||||
raise ValueError("timestamps must include UTC timezone.")
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
class Health(ApiModel):
|
||||
status: Literal["ok"]
|
||||
|
||||
|
||||
class ErrorInner(ApiModel):
|
||||
code: str = Field(min_length=1)
|
||||
message: str = Field(min_length=1)
|
||||
request_id: str = Field(min_length=1)
|
||||
|
||||
|
||||
class Error(ApiModel):
|
||||
error: ErrorInner
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Explicit local operator commands; no new public HTTP endpoints."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.db import SessionLocal, engine
|
||||
from app.pipeline import event
|
||||
|
||||
POINTS = ("crash_after_commit_before_publish", "crash_after_objects_before_commit",
|
||||
"crash_after_commit_before_ack")
|
||||
|
||||
|
||||
async def run(args) -> None:
|
||||
try:
|
||||
async with SessionLocal() as db:
|
||||
if args.command == "fault":
|
||||
await db.execute(text("""
|
||||
INSERT INTO fault_injections(point,remaining) VALUES (:point,1)
|
||||
ON CONFLICT(point) DO UPDATE SET remaining=1,updated_at=now()
|
||||
"""), {"point": args.point})
|
||||
await db.commit()
|
||||
print(f"ARMED one-shot fault: {args.point}")
|
||||
return
|
||||
if args.command == "failed":
|
||||
result = await db.execute(text("""
|
||||
SELECT id,job_id,attempt,attempts_run,error_code,staging_deleted,updated_at
|
||||
FROM attachments WHERE status='failed' ORDER BY updated_at
|
||||
"""))
|
||||
print(json.dumps([dict(row) for row in result.mappings()], default=str, indent=2))
|
||||
return
|
||||
result = await db.execute(text("SELECT * FROM attachments WHERE id=:id FOR UPDATE"),
|
||||
{"id": args.attachment_id})
|
||||
row = result.mappings().first()
|
||||
if row is None or row["job_id"] is None:
|
||||
raise ValueError("Unknown asynchronous attachment")
|
||||
if args.command == "replay":
|
||||
if row["status"] == "ready":
|
||||
print("NO-OP: attachment is already ready")
|
||||
return
|
||||
if row["status"] != "failed":
|
||||
raise ValueError("Replay is allowed only for failed attachments")
|
||||
if row["staging_deleted"]:
|
||||
raise ValueError("Replay source expired; upload the original again")
|
||||
if not args.reason.strip() or len(args.reason) > 200:
|
||||
raise ValueError("Replay reason must have 1-200 characters")
|
||||
result = await db.execute(text("""
|
||||
UPDATE attachments SET status='queued',attempt=attempt+1,attempts_run=0,
|
||||
error_code=NULL,lease_token=NULL,lease_until=NULL,
|
||||
next_attempt_at=now(),updated_at=now() WHERE id=:id RETURNING *
|
||||
"""), {"id": row["id"]})
|
||||
row = result.mappings().one()
|
||||
await event(db, row, "operator_replay", args.reason)
|
||||
else:
|
||||
# Real duplicate envelope: same job ID and current attempt.
|
||||
# Ready effects are checked in PG by the worker and acked.
|
||||
await event(db, row, "operator_redeliver")
|
||||
await db.execute(text("""
|
||||
INSERT INTO outbox(job_id,attachment_id,attempt,available_at)
|
||||
SELECT job_id,id,attempt,GREATEST(now(),next_attempt_at)
|
||||
FROM attachments WHERE id=:id
|
||||
"""), {"id": row["id"]})
|
||||
await db.commit()
|
||||
print(f"QUEUED: {args.command} attachment={row['id']} job={row['job_id']}")
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
commands.add_parser("failed")
|
||||
fault = commands.add_parser("fault")
|
||||
fault.add_argument("point", choices=POINTS)
|
||||
replay = commands.add_parser("replay")
|
||||
replay.add_argument("attachment_id", type=UUID)
|
||||
replay.add_argument("--reason", required=True)
|
||||
redeliver = commands.add_parser("redeliver")
|
||||
redeliver.add_argument("attachment_id", type=UUID)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
asyncio.run(run(args))
|
||||
except ValueError as exc:
|
||||
parser.exit(2, f"REFUSED: {exc}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
"""Shared durable-job plumbing, deliberately separate from the HTTP API."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
import aio_pika
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.config import read_value
|
||||
from app.db import SessionLocal
|
||||
|
||||
logger = logging.getLogger("messenger.pipeline")
|
||||
QUEUE = "attachments"
|
||||
MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
|
||||
LEASE_SECONDS = int(os.getenv("JOB_LEASE_SECONDS", "120"))
|
||||
IMAGE_TIMEOUT = float(os.getenv("JOB_TIMEOUT_SECONDS", "30"))
|
||||
TOTAL_TIMEOUT = float(os.getenv("JOB_TOTAL_TIMEOUT_SECONDS", "90"))
|
||||
RETENTION_SECONDS = int(os.getenv("STAGING_RETENTION_SECONDS", "604800"))
|
||||
RETRY_BASE_SECONDS = float(os.getenv("RETRY_BASE_SECONDS", "1"))
|
||||
if (MAX_ATTEMPTS < 1 or not math.isfinite(IMAGE_TIMEOUT) or IMAGE_TIMEOUT <= 0
|
||||
or not 0 < TOTAL_TIMEOUT < LEASE_SECONDS):
|
||||
raise RuntimeError("Invalid job limits; total timeout must be below lease.")
|
||||
if not math.isfinite(RETRY_BASE_SECONDS) or RETRY_BASE_SECONDS <= 0:
|
||||
raise RuntimeError("RETRY_BASE_SECONDS must be finite and positive.")
|
||||
|
||||
|
||||
def retry_delay(attempts_run: int) -> float:
|
||||
# Equal jitter: never zero, capped exponential delay, one durable due date.
|
||||
upper = min(60.0, RETRY_BASE_SECONDS * 2 ** min(max(attempts_run - 1, 0), 10))
|
||||
return random.uniform(upper / 2, upper)
|
||||
|
||||
|
||||
async def broker_channel():
|
||||
connection = await aio_pika.connect_robust(read_value("BROKER_URL"), timeout=5)
|
||||
try:
|
||||
channel = await connection.channel(publisher_confirms=True, on_return_raises=True)
|
||||
await channel.set_qos(prefetch_count=1)
|
||||
dead = await channel.declare_exchange("attachments.dead", aio_pika.ExchangeType.FANOUT,
|
||||
durable=True)
|
||||
dlq = await channel.declare_queue("attachments.dlq", durable=True)
|
||||
await dlq.bind(dead)
|
||||
queue = await channel.declare_queue(
|
||||
QUEUE, durable=True, arguments={"x-dead-letter-exchange": "attachments.dead"}
|
||||
)
|
||||
return connection, channel, queue
|
||||
except BaseException:
|
||||
await connection.close()
|
||||
raise
|
||||
|
||||
|
||||
def envelope(row) -> dict:
|
||||
return {
|
||||
"schema_version": 1, "job_id": str(row["job_id"]),
|
||||
"type": "attachment.process.v1", "attachment_id": str(row["attachment_id"]),
|
||||
"pipeline_version": int(row.get("pipeline_version", 1)),
|
||||
"attempt": int(row["attempt"]),
|
||||
"created_at": row["created_at"].isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
def parse_envelope(raw: bytes) -> dict:
|
||||
job = json.loads(raw)
|
||||
required = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version",
|
||||
"attempt", "created_at"}
|
||||
if not isinstance(job, dict) or not required <= job.keys() or (
|
||||
job.keys() - required - {"traceparent", "tracestate"}
|
||||
):
|
||||
raise ValueError("invalid job fields")
|
||||
if type(job["schema_version"]) is not int or job["schema_version"] != 1 or job["type"] != "attachment.process.v1":
|
||||
raise ValueError("unsupported job schema")
|
||||
if type(job["attempt"]) is not int or job["attempt"] < 1:
|
||||
raise ValueError("invalid attempt")
|
||||
if type(job["pipeline_version"]) is not int or job["pipeline_version"] != 1:
|
||||
raise ValueError("unsupported pipeline")
|
||||
UUID(job["job_id"])
|
||||
UUID(job["attachment_id"])
|
||||
if datetime.fromisoformat(job["created_at"].replace("Z", "+00:00")).tzinfo is None:
|
||||
raise ValueError("job timestamp must include timezone")
|
||||
if "traceparent" in job and not re.fullmatch(
|
||||
r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}", job["traceparent"]
|
||||
):
|
||||
raise ValueError("invalid traceparent")
|
||||
if "tracestate" in job and (not isinstance(job["tracestate"], str) or
|
||||
len(job["tracestate"]) > 512):
|
||||
raise ValueError("invalid tracestate")
|
||||
return job
|
||||
|
||||
|
||||
async def publish(channel, job: dict) -> None:
|
||||
await channel.default_exchange.publish(
|
||||
aio_pika.Message(json.dumps(job).encode("utf-8"), content_type="application/json",
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
message_id=job["job_id"]),
|
||||
routing_key=QUEUE, mandatory=True, timeout=5,
|
||||
)
|
||||
|
||||
|
||||
async def event(db, row, name: str, detail: str = "") -> None:
|
||||
await db.execute(text("""
|
||||
INSERT INTO job_events(attachment_id,event,attempt,detail)
|
||||
VALUES (:id,:event,:attempt,:detail)
|
||||
"""), {"id": row["id"], "attempt": row["attempt"], "event": name, "detail": detail})
|
||||
|
||||
|
||||
async def arm_from_env(variable: str) -> None:
|
||||
point = os.getenv(variable, "")
|
||||
if point:
|
||||
async with SessionLocal() as db:
|
||||
await db.execute(text("""
|
||||
INSERT INTO fault_injections(point,remaining) VALUES (:point,1)
|
||||
ON CONFLICT (point) DO NOTHING
|
||||
"""), {"point": point})
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def crash_if_armed(point: str) -> None:
|
||||
async with SessionLocal() as db:
|
||||
result = await db.execute(text("""
|
||||
UPDATE fault_injections SET remaining=remaining-1,hits=hits+1,updated_at=now()
|
||||
WHERE point=:point AND remaining>0 RETURNING point
|
||||
"""), {"point": point})
|
||||
hit = result.first() is not None
|
||||
await db.commit()
|
||||
if hit:
|
||||
logger.error("FAULT: %s (one-shot durable hit)", point)
|
||||
os._exit(70)
|
||||
|
||||
|
||||
async def retry_or_fail(db, row, code: str, *, permanent: bool = False) -> None:
|
||||
"""Caller owns the attachment row lock. Commit before acking old delivery."""
|
||||
if permanent or row["attempts_run"] >= MAX_ATTEMPTS:
|
||||
final_code = code if permanent else "retry_exhausted"
|
||||
await db.execute(text("""
|
||||
UPDATE attachments SET status='failed',error_code=:code,
|
||||
lease_token=NULL,lease_until=NULL,updated_at=now()
|
||||
WHERE id=:id
|
||||
"""), {"id": row["id"], "code": final_code})
|
||||
await event(db, row, "failed", final_code)
|
||||
logger.warning("failed attachment=%s code=%s", row["id"], final_code)
|
||||
return
|
||||
delay = retry_delay(row["attempts_run"])
|
||||
await db.execute(text("""
|
||||
UPDATE attachments SET status='queued',error_code=NULL,attempt=attempt+1,
|
||||
lease_token=NULL,lease_until=NULL,
|
||||
next_attempt_at=now()+make_interval(secs => CAST(:delay AS double precision)),
|
||||
updated_at=now() WHERE id=:id
|
||||
"""), {"id": row["id"], "delay": delay})
|
||||
await db.execute(text("""
|
||||
INSERT INTO outbox(job_id,attachment_id,attempt,available_at)
|
||||
SELECT job_id,id,attempt,next_attempt_at FROM attachments WHERE id=:id
|
||||
"""), {"id": row["id"]})
|
||||
await event(db, row, "retry", f"{code}; delay={delay:.3f}s")
|
||||
logger.info("retry attachment=%s after=%.3fs", row["id"], delay)
|
||||
@@ -0,0 +1,718 @@
|
||||
"""PostgreSQL repository functions for MTUSI Messenger Lab4."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def create_user(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
username: str,
|
||||
display_name: str,
|
||||
password_hash: str,
|
||||
) -> dict[str, Any] | None:
|
||||
user_id = uuid4()
|
||||
try:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES (:id, :username, :display_name, :password_hash)
|
||||
RETURNING id, username, display_name, created_at
|
||||
"""
|
||||
),
|
||||
{
|
||||
"id": user_id,
|
||||
"username": username,
|
||||
"display_name": display_name,
|
||||
"password_hash": password_hash,
|
||||
},
|
||||
)
|
||||
await db.commit()
|
||||
return dict(result.mappings().one())
|
||||
except IntegrityError:
|
||||
await db.rollback()
|
||||
return None
|
||||
|
||||
|
||||
async def get_user_by_username(
|
||||
db: AsyncSession,
|
||||
username: str,
|
||||
) -> dict[str, Any] | None:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = :username
|
||||
"""
|
||||
),
|
||||
{"username": username},
|
||||
)
|
||||
row = result.mappings().first()
|
||||
return dict(row) if row is not None else None
|
||||
|
||||
|
||||
async def get_user_by_id(
|
||||
db: AsyncSession,
|
||||
user_id: UUID,
|
||||
) -> dict[str, Any] | None:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = :user_id
|
||||
"""
|
||||
),
|
||||
{"user_id": user_id},
|
||||
)
|
||||
row = result.mappings().first()
|
||||
return dict(row) if row is not None else None
|
||||
|
||||
|
||||
async def user_ids_that_exist(
|
||||
db: AsyncSession,
|
||||
member_ids: Iterable[UUID],
|
||||
) -> set[UUID]:
|
||||
values = list(member_ids)
|
||||
if not values:
|
||||
return set()
|
||||
|
||||
result = await db.execute(
|
||||
text("SELECT id FROM users WHERE id = ANY(CAST(:member_ids AS uuid[]))"),
|
||||
{"member_ids": values},
|
||||
)
|
||||
return {row.id for row in result}
|
||||
|
||||
|
||||
async def create_session(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: UUID,
|
||||
token_hash: str,
|
||||
expires_at: datetime,
|
||||
) -> None:
|
||||
await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO sessions (id, user_id, token_hash, expires_at)
|
||||
VALUES (:id, :user_id, :token_hash, :expires_at)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"id": uuid4(),
|
||||
"user_id": user_id,
|
||||
"token_hash": token_hash,
|
||||
"expires_at": expires_at,
|
||||
},
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def get_active_session_user(
|
||||
db: AsyncSession,
|
||||
token_hash: str,
|
||||
) -> dict[str, Any] | None:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT
|
||||
s.id AS session_id,
|
||||
s.token_hash,
|
||||
s.expires_at,
|
||||
u.id,
|
||||
u.username,
|
||||
u.display_name,
|
||||
u.created_at
|
||||
FROM sessions AS s
|
||||
JOIN users AS u ON u.id = s.user_id
|
||||
WHERE s.token_hash = :token_hash
|
||||
AND s.revoked_at IS NULL
|
||||
AND s.expires_at > now()
|
||||
"""
|
||||
),
|
||||
{"token_hash": token_hash},
|
||||
)
|
||||
row = result.mappings().first()
|
||||
return dict(row) if row is not None else None
|
||||
|
||||
|
||||
async def revoke_active_session(
|
||||
db: AsyncSession,
|
||||
token_hash: str,
|
||||
) -> bool:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
UPDATE sessions
|
||||
SET revoked_at = now()
|
||||
WHERE token_hash = :token_hash
|
||||
AND revoked_at IS NULL
|
||||
AND expires_at > now()
|
||||
"""
|
||||
),
|
||||
{"token_hash": token_hash},
|
||||
)
|
||||
await db.commit()
|
||||
return result.rowcount == 1
|
||||
|
||||
|
||||
async def create_chat_with_members(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
title: str,
|
||||
member_ids: Iterable[UUID],
|
||||
) -> dict[str, Any]:
|
||||
chat_id = uuid4()
|
||||
members = list(member_ids)
|
||||
|
||||
try:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO chats (id, title)
|
||||
VALUES (:id, :title)
|
||||
RETURNING id, title, created_at
|
||||
"""
|
||||
),
|
||||
{"id": chat_id, "title": title},
|
||||
)
|
||||
chat = dict(result.mappings().one())
|
||||
|
||||
await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
VALUES (:chat_id, :user_id)
|
||||
"""
|
||||
),
|
||||
[{"chat_id": chat_id, "user_id": user_id} for user_id in members],
|
||||
)
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
raise
|
||||
|
||||
chat["member_ids"] = members
|
||||
return chat
|
||||
|
||||
|
||||
async def get_accessible_chat(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> dict[str, Any] | None:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats AS c
|
||||
JOIN chat_members AS own_membership
|
||||
ON own_membership.chat_id = c.id
|
||||
AND own_membership.user_id = :user_id
|
||||
WHERE c.id = :chat_id
|
||||
"""
|
||||
),
|
||||
{"chat_id": chat_id, "user_id": user_id},
|
||||
)
|
||||
chat_row = result.mappings().first()
|
||||
if chat_row is None:
|
||||
return None
|
||||
|
||||
members_result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = :chat_id
|
||||
ORDER BY user_id ASC
|
||||
"""
|
||||
),
|
||||
{"chat_id": chat_id},
|
||||
)
|
||||
chat = dict(chat_row)
|
||||
chat["member_ids"] = [row.user_id for row in members_result]
|
||||
return chat
|
||||
|
||||
|
||||
async def list_chats_for_user(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: UUID,
|
||||
limit: int,
|
||||
cursor_created_at: datetime | None,
|
||||
cursor_id: UUID | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
query = """
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats AS c
|
||||
JOIN chat_members AS own_membership
|
||||
ON own_membership.chat_id = c.id
|
||||
AND own_membership.user_id = :user_id \
|
||||
"""
|
||||
params: dict[str, Any] = {
|
||||
"user_id": user_id,
|
||||
"limit_plus_one": limit + 1,
|
||||
}
|
||||
|
||||
if cursor_created_at is not None and cursor_id is not None:
|
||||
query += """
|
||||
WHERE (c.created_at, c.id) > (:cursor_created_at, :cursor_id)
|
||||
"""
|
||||
params["cursor_created_at"] = cursor_created_at
|
||||
params["cursor_id"] = cursor_id
|
||||
|
||||
query += " ORDER BY c.created_at ASC, c.id ASC LIMIT :limit_plus_one"
|
||||
|
||||
result = await db.execute(text(query), params)
|
||||
chats = [dict(row) for row in result.mappings().all()]
|
||||
if not chats:
|
||||
return []
|
||||
|
||||
chat_ids = [chat["id"] for chat in chats]
|
||||
members_result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT chat_id, user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = ANY(CAST(:chat_ids AS uuid[]))
|
||||
ORDER BY chat_id ASC, user_id ASC
|
||||
"""
|
||||
),
|
||||
{"chat_ids": chat_ids},
|
||||
)
|
||||
|
||||
members_by_chat: dict[UUID, list[UUID]] = {chat_id: [] for chat_id in chat_ids}
|
||||
for row in members_result:
|
||||
members_by_chat[row.chat_id].append(row.user_id)
|
||||
|
||||
for chat in chats:
|
||||
chat["member_ids"] = members_by_chat[chat["id"]]
|
||||
|
||||
return chats
|
||||
|
||||
|
||||
# Attachment IDs of a message in the order of the request.
|
||||
MESSAGE_ATTACHMENT_IDS = """
|
||||
COALESCE(
|
||||
(SELECT array_agg(ma.attachment_id ORDER BY ma.position)
|
||||
FROM message_attachments AS ma
|
||||
WHERE ma.message_id = m.id),
|
||||
CAST('{}' AS uuid[])
|
||||
) AS attachment_ids
|
||||
"""
|
||||
|
||||
|
||||
class AttachmentsNotFound(Exception):
|
||||
"""Some attachment_ids do not exist or belong to another chat (-> 404)."""
|
||||
|
||||
|
||||
class AttachmentFailed(Exception):
|
||||
"""A failed attachment cannot be added to a new message (-> 409)."""
|
||||
|
||||
|
||||
async def create_message_idempotent(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text_value: str,
|
||||
attachment_ids: list[UUID],
|
||||
idempotency_key: str,
|
||||
request_hash: str,
|
||||
ttl_seconds: int,
|
||||
) -> tuple[dict[str, Any], bool] | None:
|
||||
"""Insert a message at most once per idempotency key; one transaction.
|
||||
|
||||
1. INSERT the key row. Its primary key (user, chat, method, key) lives in
|
||||
the shared PostgreSQL, so a concurrent request with the same key on
|
||||
ANY replica blocks on this INSERT until the first transaction ends.
|
||||
2. If the key was claimed: check that every attachment belongs to this
|
||||
chat, INSERT the message and its attachment links, link the message
|
||||
to the key and COMMIT everything together. A failure before COMMIT
|
||||
(also AttachmentsNotFound) rolls back all of it, so an error is never
|
||||
stored as the final answer and a retry with the same key runs again.
|
||||
3. If the key already exists (committed by someone else): return the
|
||||
stored message, or None when the body differs (-> 409).
|
||||
|
||||
A key older than ttl_seconds is reclaimed by the ON CONFLICT ... WHERE.
|
||||
Returns (message, replayed) or None on a body mismatch.
|
||||
"""
|
||||
key_params = {
|
||||
"user_id": sender_id,
|
||||
"chat_id": chat_id,
|
||||
"key": idempotency_key,
|
||||
}
|
||||
|
||||
try:
|
||||
claimed = await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO idempotency_keys AS k
|
||||
(user_id, chat_id, method, key, request_hash)
|
||||
VALUES (:user_id, :chat_id, 'POST', :key, :request_hash)
|
||||
ON CONFLICT (user_id, chat_id, method, key) DO UPDATE
|
||||
SET request_hash = EXCLUDED.request_hash,
|
||||
message_id = NULL,
|
||||
created_at = now()
|
||||
WHERE k.created_at < now() - make_interval(secs => :ttl)
|
||||
RETURNING 1
|
||||
"""
|
||||
),
|
||||
{**key_params, "request_hash": request_hash, "ttl": ttl_seconds},
|
||||
)
|
||||
|
||||
if claimed.first() is not None:
|
||||
if attachment_ids:
|
||||
# Unknown and foreign IDs look the same (404): the response
|
||||
# does not reveal that an attachment of another chat exists.
|
||||
found = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT id, status FROM attachments
|
||||
WHERE chat_id = :chat_id
|
||||
AND id = ANY(CAST(:ids AS uuid[]))
|
||||
FOR SHARE
|
||||
"""
|
||||
),
|
||||
{"chat_id": chat_id, "ids": attachment_ids},
|
||||
)
|
||||
attachments = list(found)
|
||||
if {row.id for row in attachments} != set(attachment_ids):
|
||||
raise AttachmentsNotFound()
|
||||
if any(row.status == "failed" for row in attachments):
|
||||
raise AttachmentFailed()
|
||||
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES (:id, :chat_id, :sender_id, :text)
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
"""
|
||||
),
|
||||
{
|
||||
"id": uuid4(),
|
||||
"chat_id": chat_id,
|
||||
"sender_id": sender_id,
|
||||
"text": text_value,
|
||||
},
|
||||
)
|
||||
message = dict(result.mappings().one())
|
||||
|
||||
if attachment_ids:
|
||||
await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO message_attachments
|
||||
(message_id, attachment_id, position)
|
||||
VALUES (:message_id, :attachment_id, :position)
|
||||
"""
|
||||
),
|
||||
[
|
||||
{
|
||||
"message_id": message["id"],
|
||||
"attachment_id": attachment_id,
|
||||
"position": position,
|
||||
}
|
||||
for position, attachment_id in enumerate(attachment_ids)
|
||||
],
|
||||
)
|
||||
|
||||
await db.execute(
|
||||
text(
|
||||
"""
|
||||
UPDATE idempotency_keys
|
||||
SET message_id = :message_id
|
||||
WHERE user_id = :user_id
|
||||
AND chat_id = :chat_id
|
||||
AND method = 'POST'
|
||||
AND key = :key
|
||||
"""
|
||||
),
|
||||
{**key_params, "message_id": message["id"]},
|
||||
)
|
||||
await db.commit()
|
||||
message["attachment_ids"] = list(attachment_ids)
|
||||
return message, False
|
||||
|
||||
stored = await db.execute(
|
||||
text(
|
||||
f"""
|
||||
SELECT k.request_hash,
|
||||
m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
{MESSAGE_ATTACHMENT_IDS}
|
||||
FROM idempotency_keys AS k
|
||||
JOIN messages AS m ON m.id = k.message_id
|
||||
WHERE k.user_id = :user_id
|
||||
AND k.chat_id = :chat_id
|
||||
AND k.method = 'POST'
|
||||
AND k.key = :key
|
||||
"""
|
||||
),
|
||||
key_params,
|
||||
)
|
||||
row = stored.mappings().first()
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
raise
|
||||
|
||||
if row is None:
|
||||
# Not reachable while the key row and the message commit together.
|
||||
raise RuntimeError("idempotency key without a message")
|
||||
|
||||
message = dict(row)
|
||||
if message.pop("request_hash") != request_hash:
|
||||
return None
|
||||
|
||||
return message, True
|
||||
|
||||
|
||||
async def list_messages_keyset(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
limit: int,
|
||||
cursor_created_at: datetime | None,
|
||||
cursor_id: UUID | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
query = f"""
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
{MESSAGE_ATTACHMENT_IDS}
|
||||
FROM messages AS m
|
||||
WHERE m.chat_id = :chat_id
|
||||
"""
|
||||
params: dict[str, Any] = {
|
||||
"chat_id": chat_id,
|
||||
"limit_plus_one": limit + 1,
|
||||
}
|
||||
|
||||
if cursor_created_at is not None and cursor_id is not None:
|
||||
query += """
|
||||
AND (m.created_at, m.id) > (:cursor_created_at, :cursor_id)
|
||||
"""
|
||||
params["cursor_created_at"] = cursor_created_at
|
||||
params["cursor_id"] = cursor_id
|
||||
|
||||
query += " ORDER BY m.created_at ASC, m.id ASC LIMIT :limit_plus_one"
|
||||
result = await db.execute(text(query), params)
|
||||
return [dict(row) for row in result.mappings().all()]
|
||||
|
||||
|
||||
# --- Attachments ------------------------------------------------------------
|
||||
|
||||
ATTACHMENT_COLUMNS = """
|
||||
a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes,
|
||||
a.sha256, a.status, a.error_code, a.object_key, a.variants, a.created_at, a.updated_at
|
||||
"""
|
||||
|
||||
|
||||
async def create_upload_intent(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
object_key: str,
|
||||
attachment_id: UUID,
|
||||
chat_id: UUID,
|
||||
) -> None:
|
||||
"""Committed BEFORE the S3 PUT: from now on the object can be found and
|
||||
cleaned up even if this process dies right after the PUT."""
|
||||
try:
|
||||
await db.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO upload_intents (object_key, attachment_id, chat_id)
|
||||
VALUES (:object_key, :attachment_id, :chat_id)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"object_key": object_key,
|
||||
"attachment_id": attachment_id,
|
||||
"chat_id": chat_id,
|
||||
},
|
||||
)
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
async def finalize_attachment(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
chat_id: UUID,
|
||||
owner_id: UUID,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
size_bytes: int,
|
||||
sha256: str,
|
||||
width: int,
|
||||
height: int,
|
||||
object_key: str,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Delete the intent, insert queued metadata + outbox in ONE transaction.
|
||||
|
||||
Returns None if the intent is already gone: the janitor decided this
|
||||
upload was abandoned and deleted the object, so the row must not be
|
||||
created. The DELETE waits on the janitor's row lock, so the two can
|
||||
never both succeed.
|
||||
"""
|
||||
try:
|
||||
claimed = await db.execute(
|
||||
text(
|
||||
"DELETE FROM upload_intents WHERE object_key = :object_key RETURNING 1"
|
||||
),
|
||||
{"object_key": object_key},
|
||||
)
|
||||
if claimed.first() is None:
|
||||
await db.rollback()
|
||||
return None
|
||||
|
||||
job_id = uuid4()
|
||||
final_key = f"originals/{attachment_id}/v1/original"
|
||||
result = await db.execute(
|
||||
text(
|
||||
f"""
|
||||
INSERT INTO attachments AS a
|
||||
(id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||
sha256, width, height, object_key, staging_key, job_id, status)
|
||||
VALUES (:id, :chat_id, :owner_id, :filename, :content_type,
|
||||
:size_bytes, :sha256, :width, :height, :final_key, :object_key, :job_id, 'queued')
|
||||
RETURNING {ATTACHMENT_COLUMNS}
|
||||
"""
|
||||
),
|
||||
{
|
||||
"id": attachment_id,
|
||||
"chat_id": chat_id,
|
||||
"owner_id": owner_id,
|
||||
"filename": filename,
|
||||
"content_type": content_type,
|
||||
"size_bytes": size_bytes,
|
||||
"sha256": sha256,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"object_key": object_key,
|
||||
"final_key": final_key,
|
||||
"job_id": job_id,
|
||||
},
|
||||
)
|
||||
row = dict(result.mappings().one())
|
||||
await db.execute(
|
||||
text("INSERT INTO outbox (job_id, attachment_id, attempt) VALUES (:job_id, :id, 1)"),
|
||||
{"job_id": job_id, "id": attachment_id},
|
||||
)
|
||||
await db.commit()
|
||||
return row
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
async def delete_upload_intent(db: AsyncSession, object_key: str) -> None:
|
||||
try:
|
||||
await db.execute(
|
||||
text("DELETE FROM upload_intents WHERE object_key = :object_key"),
|
||||
{"object_key": object_key},
|
||||
)
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
async def get_accessible_attachment(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Only members of the attachment's chat see it; others get None (404)."""
|
||||
result = await db.execute(
|
||||
text(
|
||||
f"""
|
||||
SELECT {ATTACHMENT_COLUMNS}
|
||||
FROM attachments AS a
|
||||
JOIN chat_members AS cm
|
||||
ON cm.chat_id = a.chat_id
|
||||
AND cm.user_id = :user_id
|
||||
WHERE a.id = :attachment_id
|
||||
"""
|
||||
),
|
||||
{"attachment_id": attachment_id, "user_id": user_id},
|
||||
)
|
||||
row = result.mappings().first()
|
||||
return dict(row) if row is not None else None
|
||||
|
||||
|
||||
async def lock_upload_intent(
|
||||
db: AsyncSession,
|
||||
object_key: str,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Lock the intent of one upload (waits for a finishing transaction);
|
||||
the transaction stays open. None: no intent, nothing to compensate."""
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT i.object_key,
|
||||
EXISTS (SELECT 1 FROM attachments AS a
|
||||
WHERE a.staging_key = i.object_key OR a.object_key = i.object_key) AS committed
|
||||
FROM upload_intents AS i
|
||||
WHERE i.object_key = :object_key
|
||||
FOR UPDATE OF i
|
||||
"""
|
||||
),
|
||||
{"object_key": object_key},
|
||||
)
|
||||
row = result.mappings().first()
|
||||
return dict(row) if row is not None else None
|
||||
|
||||
|
||||
async def lock_stale_intent(
|
||||
db: AsyncSession,
|
||||
grace_seconds: int,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Lock ONE intent older than the grace period; the transaction stays open.
|
||||
|
||||
SKIP LOCKED: an upload that is finishing right now holds the row lock in
|
||||
finalize_attachment and is skipped; several replicas can run the janitor
|
||||
at once without touching the same intent.
|
||||
"""
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT i.object_key,
|
||||
EXISTS (SELECT 1 FROM attachments AS a
|
||||
WHERE a.staging_key = i.object_key OR a.object_key = i.object_key) AS committed
|
||||
FROM upload_intents AS i
|
||||
WHERE i.created_at < now() - make_interval(secs => :grace)
|
||||
ORDER BY i.created_at
|
||||
LIMIT 1
|
||||
FOR UPDATE OF i SKIP LOCKED
|
||||
"""
|
||||
),
|
||||
{"grace": grace_seconds},
|
||||
)
|
||||
row = result.mappings().first()
|
||||
return dict(row) if row is not None else None
|
||||
|
||||
|
||||
async def attachment_keys(db: AsyncSession) -> set[str]:
|
||||
result = await db.execute(text("SELECT object_key FROM attachments"))
|
||||
return {row.object_key for row in result}
|
||||
|
||||
|
||||
async def intent_keys(db: AsyncSession) -> dict[str, datetime]:
|
||||
result = await db.execute(
|
||||
text("SELECT object_key, created_at FROM upload_intents")
|
||||
)
|
||||
return {row.object_key: row.created_at for row in result}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerifyMismatchError
|
||||
|
||||
|
||||
password_hasher = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return password_hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return password_hasher.verify(password_hash, password)
|
||||
except (VerifyMismatchError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def generate_session_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def hash_session_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def parse_basic_authorization(value: str | None) -> tuple[str, str] | None:
|
||||
if value is None or not value.startswith("Basic "):
|
||||
return None
|
||||
|
||||
try:
|
||||
encoded_credentials = value[len("Basic "):]
|
||||
decoded = base64.b64decode(
|
||||
encoded_credentials,
|
||||
validate=True,
|
||||
).decode("utf-8")
|
||||
|
||||
username, password = decoded.split(":", 1)
|
||||
except (
|
||||
ValueError,
|
||||
UnicodeDecodeError,
|
||||
binascii.Error,
|
||||
):
|
||||
return None
|
||||
|
||||
if not username or not username.isascii():
|
||||
return None
|
||||
|
||||
return username, password
|
||||
|
||||
|
||||
def _encode_cursor_payload(payload: dict[str, str]) -> str:
|
||||
raw = json.dumps(
|
||||
payload,
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
sort_keys=True,
|
||||
).encode("utf-8")
|
||||
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii")
|
||||
|
||||
|
||||
def _decode_cursor_payload(cursor: str) -> dict[str, str] | None:
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor.encode("ascii"))
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
|
||||
return payload
|
||||
except (
|
||||
ValueError,
|
||||
TypeError,
|
||||
UnicodeDecodeError,
|
||||
binascii.Error,
|
||||
):
|
||||
return None
|
||||
|
||||
|
||||
def _utc_timestamp(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
raise ValueError("Cursor datetime must be timezone-aware.")
|
||||
|
||||
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def encode_chat_cursor(
|
||||
created_at: datetime,
|
||||
chat_id: UUID,
|
||||
) -> str:
|
||||
return _encode_cursor_payload(
|
||||
{
|
||||
"kind": "chat",
|
||||
"created_at": _utc_timestamp(created_at),
|
||||
"id": str(chat_id),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def decode_chat_cursor(
|
||||
cursor: str,
|
||||
) -> tuple[datetime, UUID] | None:
|
||||
payload = _decode_cursor_payload(cursor)
|
||||
|
||||
if payload is None or payload.get("kind") != "chat":
|
||||
return None
|
||||
|
||||
try:
|
||||
created_at = datetime.fromisoformat(
|
||||
payload["created_at"].replace("Z", "+00:00")
|
||||
)
|
||||
chat_id = UUID(payload["id"])
|
||||
except (KeyError, ValueError, AttributeError):
|
||||
return None
|
||||
|
||||
return created_at, chat_id
|
||||
|
||||
|
||||
def encode_message_cursor(
|
||||
chat_id: UUID,
|
||||
created_at: datetime,
|
||||
message_id: UUID,
|
||||
) -> str:
|
||||
return _encode_cursor_payload(
|
||||
{
|
||||
"kind": "message",
|
||||
"chat_id": str(chat_id),
|
||||
"created_at": _utc_timestamp(created_at),
|
||||
"id": str(message_id),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def decode_message_cursor(
|
||||
cursor: str,
|
||||
) -> tuple[UUID, datetime, UUID] | None:
|
||||
payload = _decode_cursor_payload(cursor)
|
||||
|
||||
if payload is None or payload.get("kind") != "message":
|
||||
return None
|
||||
|
||||
try:
|
||||
chat_id = UUID(payload["chat_id"])
|
||||
created_at = datetime.fromisoformat(
|
||||
payload["created_at"].replace("Z", "+00:00")
|
||||
)
|
||||
message_id = UUID(payload["id"])
|
||||
except (KeyError, ValueError, AttributeError):
|
||||
return None
|
||||
|
||||
return chat_id, created_at, message_id
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Entry point: uvicorn with a drain phase before the graceful shutdown.
|
||||
|
||||
Plain uvicorn stops accepting connections immediately on SIGTERM. Behind
|
||||
HAProxy that turns every stop into a burst of refused connections until the
|
||||
active health check notices. Instead, on the first signal:
|
||||
|
||||
t = 0 readiness -> 503, keep serving (Connection: close);
|
||||
t = drain (3 s) HAProxy has marked the server DOWN (inter 1 s x fall 2),
|
||||
uvicorn closes the listener and waits for in-flight
|
||||
requests up to SHUTDOWN_TIMEOUT_SECONDS (8 s).
|
||||
|
||||
stop_grace_period in compose.yaml (15 s) is larger than 3 + 8 s.
|
||||
A second signal skips the drain phase.
|
||||
"""
|
||||
import logging
|
||||
import threading
|
||||
|
||||
import uvicorn
|
||||
|
||||
from app.config import settings
|
||||
from app.lifecycle import draining
|
||||
|
||||
|
||||
logger = logging.getLogger("messenger.server")
|
||||
|
||||
|
||||
class DrainingServer(uvicorn.Server):
|
||||
def handle_exit(self, sig, frame) -> None:
|
||||
if draining.is_set():
|
||||
super().handle_exit(sig, frame)
|
||||
return
|
||||
|
||||
draining.set()
|
||||
logger.warning(
|
||||
"signal %s: draining for %.1f s before shutdown",
|
||||
sig,
|
||||
settings.shutdown_drain_seconds,
|
||||
)
|
||||
# Set should_exit directly instead of super().handle_exit(): uvicorn
|
||||
# would re-raise the captured SIGTERM after shutdown and the process
|
||||
# would exit with 143 instead of a clean 0.
|
||||
timer = threading.Timer(
|
||||
settings.shutdown_drain_seconds,
|
||||
self._begin_shutdown,
|
||||
)
|
||||
timer.daemon = True
|
||||
timer.start()
|
||||
|
||||
def _begin_shutdown(self) -> None:
|
||||
logger.warning("drain finished: closing listener")
|
||||
self.should_exit = True
|
||||
|
||||
|
||||
def main() -> None:
|
||||
config = uvicorn.Config(
|
||||
"app.main:app",
|
||||
host=settings.app_host,
|
||||
port=settings.app_port,
|
||||
proxy_headers=False,
|
||||
# Longer than HAProxy "timeout http-keep-alive 10s": the LB closes an
|
||||
# idle connection first, so it never reuses one the API just closed.
|
||||
timeout_keep_alive=30,
|
||||
timeout_graceful_shutdown=settings.shutdown_timeout_seconds,
|
||||
log_level="info",
|
||||
)
|
||||
DrainingServer(config).run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+432
@@ -0,0 +1,432 @@
|
||||
"""Business rules for MTUSI Messenger Lab4 (users, chats, messages)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app import repositories
|
||||
from app.cache import REVOKED_SESSION, session_cache
|
||||
from app.config import settings
|
||||
from app.errors import ApiError
|
||||
from app.security import (
|
||||
decode_chat_cursor,
|
||||
decode_message_cursor,
|
||||
encode_chat_cursor,
|
||||
encode_message_cursor,
|
||||
generate_session_token,
|
||||
hash_password,
|
||||
hash_session_token,
|
||||
parse_basic_authorization,
|
||||
verify_password,
|
||||
)
|
||||
|
||||
|
||||
def _utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _to_user(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def _to_chat(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"title": row["title"],
|
||||
"member_ids": row["member_ids"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def _to_message(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"chat_id": row["chat_id"],
|
||||
"sender_id": row["sender_id"],
|
||||
"text": row["text"],
|
||||
"created_at": row["created_at"],
|
||||
"attachment_ids": list(row.get("attachment_ids") or []),
|
||||
}
|
||||
|
||||
|
||||
def _bearer_unauthorized() -> ApiError:
|
||||
return ApiError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Authentication is required.",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Bearer realm="messenger"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _basic_unauthorized() -> ApiError:
|
||||
return ApiError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Invalid credentials.",
|
||||
headers={
|
||||
"WWW-Authenticate": (
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# Lab3 contract: ASCII [A-Za-z0-9._:-]{1,128}.
|
||||
IDEMPOTENCY_KEY_PATTERN = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
||||
|
||||
|
||||
def _invalid_request(message: str) -> ApiError:
|
||||
return ApiError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def _not_found() -> ApiError:
|
||||
return ApiError(404, "not_found", "Object not found.")
|
||||
|
||||
|
||||
async def register_user(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
username: str,
|
||||
display_name: str,
|
||||
password: str,
|
||||
) -> dict[str, Any]:
|
||||
# Argon2 is CPU-bound (~0.5-1 s); off the event loop so /health/ready keeps answering.
|
||||
password_hash = await asyncio.to_thread(hash_password, password)
|
||||
user = await repositories.create_user(
|
||||
db,
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
password_hash=password_hash,
|
||||
)
|
||||
|
||||
if user is None:
|
||||
raise ApiError(
|
||||
409,
|
||||
"conflict",
|
||||
"Username is already taken.",
|
||||
)
|
||||
|
||||
return _to_user(user)
|
||||
|
||||
|
||||
async def create_user_session(
|
||||
db: AsyncSession,
|
||||
authorization: str | None,
|
||||
) -> dict[str, Any]:
|
||||
credentials = parse_basic_authorization(authorization)
|
||||
|
||||
if credentials is None:
|
||||
raise _basic_unauthorized()
|
||||
|
||||
username, password = credentials
|
||||
user = await repositories.get_user_by_username(db, username)
|
||||
|
||||
if user is None or not await asyncio.to_thread(
|
||||
verify_password,
|
||||
user["password_hash"],
|
||||
password,
|
||||
):
|
||||
raise _basic_unauthorized()
|
||||
|
||||
token = generate_session_token()
|
||||
expires_at = _utc_now() + timedelta(
|
||||
seconds=settings.session_ttl_seconds
|
||||
)
|
||||
|
||||
await repositories.create_session(
|
||||
db,
|
||||
user_id=user["id"],
|
||||
token_hash=hash_session_token(token),
|
||||
expires_at=expires_at,
|
||||
)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": expires_at,
|
||||
"user": _to_user(user),
|
||||
}
|
||||
|
||||
|
||||
async def current_user_from_bearer_token(
|
||||
db: AsyncSession,
|
||||
token: str,
|
||||
) -> dict[str, Any]:
|
||||
token_hash = hash_session_token(token)
|
||||
cached = await session_cache.get(token_hash)
|
||||
|
||||
if cached is REVOKED_SESSION:
|
||||
raise _bearer_unauthorized()
|
||||
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
# Cache miss or cache unavailable: PostgreSQL decides.
|
||||
session_user = await repositories.get_active_session_user(db, token_hash)
|
||||
|
||||
if session_user is None:
|
||||
raise _bearer_unauthorized()
|
||||
|
||||
user = _to_user(session_user)
|
||||
await session_cache.put(token_hash, user, session_user["expires_at"])
|
||||
return user
|
||||
|
||||
|
||||
async def logout_current_session(
|
||||
db: AsyncSession,
|
||||
token: str,
|
||||
) -> None:
|
||||
token_hash = hash_session_token(token)
|
||||
revoked = await repositories.revoke_active_session(db, token_hash)
|
||||
|
||||
if not revoked:
|
||||
raise _bearer_unauthorized()
|
||||
|
||||
# Invalidate after COMMIT in the source of truth.
|
||||
await session_cache.revoke(token_hash)
|
||||
|
||||
|
||||
async def create_chat(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
title: str,
|
||||
member_ids: list[UUID],
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
unique_member_ids = set(member_ids)
|
||||
|
||||
if len(unique_member_ids) != len(member_ids):
|
||||
raise _invalid_request(
|
||||
"member_ids must not contain duplicates."
|
||||
)
|
||||
|
||||
if current_user["id"] not in unique_member_ids:
|
||||
raise _invalid_request(
|
||||
"The current user must be included in member_ids."
|
||||
)
|
||||
|
||||
existing_ids = await repositories.user_ids_that_exist(
|
||||
db,
|
||||
unique_member_ids,
|
||||
)
|
||||
|
||||
if existing_ids != unique_member_ids:
|
||||
raise _invalid_request(
|
||||
"One or more member_ids do not exist."
|
||||
)
|
||||
|
||||
chat = await repositories.create_chat_with_members(
|
||||
db,
|
||||
title=title,
|
||||
member_ids=member_ids,
|
||||
)
|
||||
|
||||
return _to_chat(chat)
|
||||
|
||||
|
||||
async def get_chat(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
chat = await repositories.get_accessible_chat(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
user_id=current_user["id"],
|
||||
)
|
||||
|
||||
if chat is None:
|
||||
raise _not_found()
|
||||
|
||||
return _to_chat(chat)
|
||||
|
||||
|
||||
async def list_chats(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
limit: int,
|
||||
cursor: str | None,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
cursor_created_at: datetime | None = None
|
||||
cursor_id: UUID | None = None
|
||||
|
||||
if cursor is not None:
|
||||
decoded = decode_chat_cursor(cursor)
|
||||
|
||||
if decoded is None:
|
||||
raise _invalid_request("Invalid cursor.")
|
||||
|
||||
cursor_created_at, cursor_id = decoded
|
||||
|
||||
rows = await repositories.list_chats_for_user(
|
||||
db,
|
||||
user_id=current_user["id"],
|
||||
limit=limit,
|
||||
cursor_created_at=cursor_created_at,
|
||||
cursor_id=cursor_id,
|
||||
)
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = encode_chat_cursor(
|
||||
last["created_at"],
|
||||
last["id"],
|
||||
)
|
||||
|
||||
return {
|
||||
"items": [_to_chat(row) for row in page],
|
||||
"next_cursor": next_cursor,
|
||||
}
|
||||
|
||||
|
||||
def _request_fingerprint(text_value: str, attachment_ids: list[UUID]) -> str:
|
||||
"""Hash of the validated body: key order and whitespace do not matter,
|
||||
a missing attachment_ids equals []. Without attachments the canonical
|
||||
form is the lab3 one, so keys stored by lab3 still replay correctly."""
|
||||
body: dict[str, Any] = {"text": text_value}
|
||||
if attachment_ids:
|
||||
body["attachment_ids"] = [str(item) for item in attachment_ids]
|
||||
canonical = json.dumps(
|
||||
body,
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
sort_keys=True,
|
||||
)
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
async def create_message(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
text_value: str,
|
||||
attachment_ids: list[UUID],
|
||||
idempotency_key: str | None,
|
||||
current_user: dict[str, Any],
|
||||
) -> tuple[dict[str, Any], bool]:
|
||||
"""Send a message once per (user, POST, chat, Idempotency-Key).
|
||||
|
||||
Returns (message, replayed). A replay re-checks the session (done by
|
||||
require_user) and chat membership before returning the stored result.
|
||||
"""
|
||||
if idempotency_key is None or not IDEMPOTENCY_KEY_PATTERN.fullmatch(
|
||||
idempotency_key
|
||||
):
|
||||
raise _invalid_request(
|
||||
"Idempotency-Key header is required: [A-Za-z0-9._:-]{1,128}."
|
||||
)
|
||||
|
||||
chat = await repositories.get_accessible_chat(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
user_id=current_user["id"],
|
||||
)
|
||||
|
||||
if chat is None:
|
||||
raise _not_found()
|
||||
|
||||
try:
|
||||
result = await repositories.create_message_idempotent(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
sender_id=current_user["id"],
|
||||
text_value=text_value,
|
||||
attachment_ids=attachment_ids,
|
||||
idempotency_key=idempotency_key,
|
||||
request_hash=_request_fingerprint(text_value, attachment_ids),
|
||||
ttl_seconds=settings.idempotency_ttl_seconds,
|
||||
)
|
||||
except repositories.AttachmentsNotFound:
|
||||
raise _not_found() from None
|
||||
except repositories.AttachmentFailed:
|
||||
raise ApiError(409, "conflict", "Failed attachment cannot be attached.") from None
|
||||
|
||||
if result is None:
|
||||
raise ApiError(
|
||||
409,
|
||||
"conflict",
|
||||
"Idempotency-Key was already used with a different body.",
|
||||
)
|
||||
|
||||
message, replayed = result
|
||||
return _to_message(message), replayed
|
||||
|
||||
|
||||
async def list_messages(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
limit: int,
|
||||
cursor: str | None,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
chat = await repositories.get_accessible_chat(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
user_id=current_user["id"],
|
||||
)
|
||||
|
||||
if chat is None:
|
||||
raise _not_found()
|
||||
|
||||
cursor_created_at: datetime | None = None
|
||||
cursor_id: UUID | None = None
|
||||
|
||||
if cursor is not None:
|
||||
decoded = decode_message_cursor(cursor)
|
||||
|
||||
if decoded is None:
|
||||
raise _invalid_request("Invalid cursor.")
|
||||
|
||||
cursor_chat_id, cursor_created_at, cursor_id = decoded
|
||||
|
||||
if cursor_chat_id != chat_id:
|
||||
raise _invalid_request(
|
||||
"Cursor belongs to another chat."
|
||||
)
|
||||
|
||||
rows = await repositories.list_messages_keyset(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
limit=limit,
|
||||
cursor_created_at=cursor_created_at,
|
||||
cursor_id=cursor_id,
|
||||
)
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = encode_message_cursor(
|
||||
chat_id,
|
||||
last["created_at"],
|
||||
last["id"],
|
||||
)
|
||||
|
||||
return {
|
||||
"items": [_to_message(row) for row in page],
|
||||
"next_cursor": next_cursor,
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
"""Private S3 bucket for attachment bytes (SeaweedFS S3 gateway).
|
||||
|
||||
One long-lived aiobotocore client per API process, path-style addressing,
|
||||
short connect/read timeouts, at most 2 attempts and an overall deadline
|
||||
S3_OPERATION_TIMEOUT_SECONDS per call, so an unavailable S3 turns into a
|
||||
fast 503 on the attachment endpoints only. Any client-side or
|
||||
network error is raised as StorageUnavailable; a missing key is
|
||||
ObjectMissing. Object keys are generated by the server (see services.py);
|
||||
the user's filename never becomes part of a key.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import AsyncExitStack
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, BinaryIO
|
||||
|
||||
from aiobotocore.config import AioConfig
|
||||
from aiobotocore.session import get_session
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
logger = logging.getLogger("messenger.storage")
|
||||
|
||||
DOWNLOAD_CHUNK = 64 * 1024
|
||||
|
||||
|
||||
class StorageUnavailable(Exception):
|
||||
"""S3 is unreachable, timed out or refused the request."""
|
||||
|
||||
|
||||
class ObjectMissing(Exception):
|
||||
"""The key does not exist in the bucket."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class StoredObject:
|
||||
key: str
|
||||
size: int
|
||||
last_modified: Any
|
||||
|
||||
|
||||
class ObjectStorage:
|
||||
def __init__(self) -> None:
|
||||
self._stack: AsyncExitStack | None = None
|
||||
self._client = None
|
||||
self.bucket = settings.s3_bucket
|
||||
|
||||
async def start(self) -> None:
|
||||
self._stack = AsyncExitStack()
|
||||
session = get_session()
|
||||
self._client = await self._stack.enter_async_context(
|
||||
session.create_client(
|
||||
"s3",
|
||||
endpoint_url=settings.s3_endpoint,
|
||||
region_name=settings.s3_region,
|
||||
aws_access_key_id=settings.s3_access_key_id,
|
||||
aws_secret_access_key=settings.s3_secret_access_key,
|
||||
config=AioConfig(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=settings.s3_connect_timeout_seconds,
|
||||
read_timeout=settings.s3_read_timeout_seconds,
|
||||
retries={"max_attempts": 2, "mode": "standard"},
|
||||
max_pool_connections=settings.max_concurrent_uploads * 2 + 4,
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._stack is not None:
|
||||
await self._stack.aclose()
|
||||
self._stack = None
|
||||
self._client = None
|
||||
|
||||
@staticmethod
|
||||
def _deadline(size: int = 0):
|
||||
return asyncio.timeout(
|
||||
settings.s3_operation_timeout_seconds
|
||||
+ size / settings.s3_put_min_bytes_per_second
|
||||
)
|
||||
|
||||
def _require_client(self):
|
||||
if self._client is None:
|
||||
raise StorageUnavailable("S3 client is not started")
|
||||
return self._client
|
||||
|
||||
async def put(
|
||||
self,
|
||||
key: str,
|
||||
body: BinaryIO,
|
||||
size: int,
|
||||
content_type: str,
|
||||
) -> None:
|
||||
"""Upload a seekable file. SigV4 signs the payload SHA-256, so S3
|
||||
itself rejects bytes that were damaged on the way."""
|
||||
client = self._require_client()
|
||||
body.seek(0)
|
||||
try:
|
||||
async with self._deadline(size):
|
||||
await client.put_object(
|
||||
Bucket=self.bucket,
|
||||
Key=key,
|
||||
Body=body,
|
||||
ContentLength=size,
|
||||
ContentType=content_type,
|
||||
)
|
||||
except (BotoCoreError, ClientError, OSError, asyncio.TimeoutError) as exc:
|
||||
raise StorageUnavailable(type(exc).__name__) from exc
|
||||
|
||||
async def open_download(self, key: str) -> tuple[AsyncIterator[bytes], int]:
|
||||
"""GET the object; S3 errors surface here, before any byte is sent."""
|
||||
client = self._require_client()
|
||||
try:
|
||||
async with self._deadline():
|
||||
response = await client.get_object(Bucket=self.bucket, Key=key)
|
||||
except ClientError as exc:
|
||||
if exc.response.get("Error", {}).get("Code") in {"NoSuchKey", "404"}:
|
||||
raise ObjectMissing(key) from exc
|
||||
raise StorageUnavailable(type(exc).__name__) from exc
|
||||
except (BotoCoreError, OSError, asyncio.TimeoutError) as exc:
|
||||
raise StorageUnavailable(type(exc).__name__) from exc
|
||||
|
||||
body = response["Body"]
|
||||
|
||||
async def chunks() -> AsyncIterator[bytes]:
|
||||
try:
|
||||
async for chunk in body.iter_chunks(DOWNLOAD_CHUNK):
|
||||
yield chunk
|
||||
finally:
|
||||
body.close()
|
||||
|
||||
return chunks(), int(response["ContentLength"])
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
"""Idempotent: deleting a missing key succeeds in S3."""
|
||||
client = self._require_client()
|
||||
try:
|
||||
async with self._deadline():
|
||||
await client.delete_object(Bucket=self.bucket, Key=key)
|
||||
except (BotoCoreError, ClientError, OSError, asyncio.TimeoutError) as exc:
|
||||
raise StorageUnavailable(type(exc).__name__) from exc
|
||||
|
||||
async def exists(self, key: str) -> bool:
|
||||
client = self._require_client()
|
||||
try:
|
||||
async with self._deadline():
|
||||
await client.head_object(Bucket=self.bucket, Key=key)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
if exc.response.get("Error", {}).get("Code") in {"NoSuchKey", "404", "NotFound"}:
|
||||
return False
|
||||
raise StorageUnavailable(type(exc).__name__) from exc
|
||||
except (BotoCoreError, OSError, asyncio.TimeoutError) as exc:
|
||||
raise StorageUnavailable(type(exc).__name__) from exc
|
||||
|
||||
async def list_objects(self, prefix: str) -> AsyncIterator[StoredObject]:
|
||||
client = self._require_client()
|
||||
paginator = client.get_paginator("list_objects_v2")
|
||||
try:
|
||||
async for page in paginator.paginate(Bucket=self.bucket, Prefix=prefix):
|
||||
for item in page.get("Contents", []):
|
||||
yield StoredObject(item["Key"], item["Size"], item["LastModified"])
|
||||
except (BotoCoreError, ClientError, OSError, asyncio.TimeoutError) as exc:
|
||||
raise StorageUnavailable(type(exc).__name__) from exc
|
||||
|
||||
|
||||
storage = ObjectStorage()
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
"""RabbitMQ consumer: one bounded job at a time, explicit ack after COMMIT."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.config import settings
|
||||
from app.db import SessionLocal, engine
|
||||
from app.pipeline import (IMAGE_TIMEOUT, LEASE_SECONDS, TOTAL_TIMEOUT,
|
||||
arm_from_env, broker_channel, crash_if_armed,
|
||||
event, parse_envelope, retry_or_fail)
|
||||
from app.storage import ObjectMissing, storage
|
||||
|
||||
logger = logging.getLogger("messenger.worker")
|
||||
|
||||
|
||||
class PermanentFailure(Exception):
|
||||
pass
|
||||
|
||||
|
||||
async def claim(job: dict) -> dict | None:
|
||||
async with SessionLocal() as db:
|
||||
result = await db.execute(text("""
|
||||
SELECT * FROM attachments WHERE id=:id FOR UPDATE
|
||||
"""), {"id": UUID(job["attachment_id"])})
|
||||
row = result.mappings().first()
|
||||
if row is None or row["job_id"] != UUID(job["job_id"]) or (
|
||||
row["pipeline_version"] != job["pipeline_version"] or
|
||||
row["attempt"] != job["attempt"] or row["status"] != "queued"
|
||||
):
|
||||
await db.rollback()
|
||||
return None
|
||||
# An early/manual duplicate cannot bypass the durable retry date.
|
||||
result = await db.execute(text("""
|
||||
UPDATE attachments SET status='processing',attempts_run=attempts_run+1,
|
||||
lease_token=:token,lease_until=now()+make_interval(secs => :lease),
|
||||
updated_at=now()
|
||||
WHERE id=:id AND next_attempt_at<=now() RETURNING *
|
||||
"""), {"id": row["id"], "token": uuid4(), "lease": LEASE_SECONDS})
|
||||
claimed = result.mappings().first()
|
||||
if claimed is None:
|
||||
await db.rollback()
|
||||
return None
|
||||
claimed = dict(claimed)
|
||||
await event(db, claimed, "processing")
|
||||
await db.commit()
|
||||
return claimed
|
||||
|
||||
|
||||
async def generate(source: Path, directory: Path) -> list[dict]:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
sys.executable, "-m", "app.image_worker", str(source), str(directory),
|
||||
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
|
||||
)
|
||||
try:
|
||||
try:
|
||||
async with asyncio.timeout(IMAGE_TIMEOUT):
|
||||
code = await process.wait()
|
||||
except TimeoutError:
|
||||
raise PermanentFailure("image_timeout") from None
|
||||
if code == 21:
|
||||
raise PermanentFailure("image_resource_limit")
|
||||
if code != 0:
|
||||
raise PermanentFailure("invalid_image")
|
||||
return json.loads((directory / "manifest.json").read_text(encoding="utf-8"))
|
||||
finally:
|
||||
# Includes cancellation of the entire job. Native image code cannot
|
||||
# continue using CPU/RAM after its parent timed out.
|
||||
if process.returncode is None:
|
||||
process.kill()
|
||||
await process.wait()
|
||||
|
||||
|
||||
async def build_objects(row: dict) -> list[dict]:
|
||||
with tempfile.TemporaryDirectory(prefix="attachment-") as temporary:
|
||||
directory = Path(temporary)
|
||||
source = directory / "source"
|
||||
if not row["staging_key"] or row["staging_deleted"]:
|
||||
raise PermanentFailure("source_missing")
|
||||
try:
|
||||
chunks, declared_length = await storage.open_download(row["staging_key"])
|
||||
except ObjectMissing:
|
||||
raise PermanentFailure("source_missing") from None
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
try:
|
||||
with source.open("wb") as output:
|
||||
async for chunk in chunks:
|
||||
size += len(chunk)
|
||||
if size > settings.max_upload_bytes:
|
||||
raise PermanentFailure("source_too_large")
|
||||
digest.update(chunk)
|
||||
output.write(chunk)
|
||||
finally:
|
||||
await chunks.aclose()
|
||||
if size != declared_length or size != row["size_bytes"] or digest.hexdigest() != row["sha256"]:
|
||||
raise PermanentFailure("source_checksum_mismatch")
|
||||
variants = await generate(source, directory)
|
||||
# API never publishes directly to this final prefix. Repeating one
|
||||
# v1 job writes the same bytes to the same four keys, never appends.
|
||||
with source.open("rb") as body:
|
||||
await storage.put(row["object_key"], body, size, row["content_type"])
|
||||
prefix = row["object_key"].rsplit("/", 1)[0]
|
||||
for variant in variants:
|
||||
filename = variant.pop("filename")
|
||||
key = f"{prefix}/{filename}"
|
||||
with (directory / filename).open("rb") as body:
|
||||
await storage.put(key, body, variant["size_bytes"], variant["content_type"])
|
||||
variant["object_key"] = key
|
||||
await crash_if_armed("crash_after_objects_before_commit")
|
||||
return variants
|
||||
|
||||
|
||||
async def finish(row: dict, *, variants=None, code: str | None = None,
|
||||
permanent: bool = False) -> bool:
|
||||
async with SessionLocal() as db:
|
||||
result = await db.execute(text("""
|
||||
SELECT * FROM attachments WHERE id=:id AND status='processing'
|
||||
AND lease_token=:token AND lease_until>now() FOR UPDATE
|
||||
"""), {"id": row["id"], "token": row["lease_token"]})
|
||||
current = result.mappings().first()
|
||||
if current is None:
|
||||
# Lease recovery or explicit operator action already owns a
|
||||
# newer attempt. Never overwrite its state with an old worker.
|
||||
await db.rollback()
|
||||
return False
|
||||
if code is not None:
|
||||
await retry_or_fail(db, current, code, permanent=permanent)
|
||||
else:
|
||||
await db.execute(text("""
|
||||
UPDATE attachments SET status='ready',variants=CAST(:variants AS jsonb),
|
||||
error_code=NULL,lease_token=NULL,lease_until=NULL,updated_at=now()
|
||||
WHERE id=:id
|
||||
"""), {"id": row["id"], "variants": json.dumps(variants)})
|
||||
await event(db, current, "ready")
|
||||
await db.commit()
|
||||
return True
|
||||
|
||||
|
||||
async def handle(message) -> None:
|
||||
try:
|
||||
job = parse_envelope(message.body)
|
||||
except (ValueError, TypeError, KeyError, AttributeError):
|
||||
logger.warning("invalid envelope sent to durable DLQ")
|
||||
await message.reject(requeue=False)
|
||||
return
|
||||
row = await claim(job)
|
||||
if row is None:
|
||||
# A ready/failed/stale attempt is a durable no-op. A duplicate of
|
||||
# active processing is covered by the DB lease recovery, so it too
|
||||
# can be acknowledged without running a second concurrent decoder.
|
||||
await message.ack()
|
||||
return
|
||||
try:
|
||||
async with asyncio.timeout(TOTAL_TIMEOUT):
|
||||
variants = await build_objects(row)
|
||||
except PermanentFailure as exc:
|
||||
await finish(row, code=str(exc), permanent=True)
|
||||
except Exception as exc:
|
||||
logger.warning("temporary processing failure attachment=%s type=%s",
|
||||
row["id"], type(exc).__name__)
|
||||
await finish(row, code="processing_failed")
|
||||
else:
|
||||
if await finish(row, variants=variants):
|
||||
await crash_if_armed("crash_after_commit_before_ack")
|
||||
logger.info("ready attachment=%s", row["id"])
|
||||
# If finish failed, the exception propagates and the connection closes:
|
||||
# RabbitMQ redelivers while PG keeps the durable lease/retry intention.
|
||||
await message.ack()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
for name in ("aio_pika", "aiormq"):
|
||||
logging.getLogger(name).setLevel(logging.CRITICAL)
|
||||
await storage.start()
|
||||
connection = None
|
||||
try:
|
||||
await arm_from_env("WORKER_FAULT")
|
||||
while True:
|
||||
try:
|
||||
connection, _, queue = await broker_channel()
|
||||
async with queue.iterator() as deliveries:
|
||||
async for message in deliveries:
|
||||
await handle(message)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.warning("worker reconnect: %s", type(exc).__name__)
|
||||
if connection:
|
||||
await connection.close()
|
||||
connection = None
|
||||
await asyncio.sleep(1)
|
||||
finally:
|
||||
if connection:
|
||||
await connection.close()
|
||||
await storage.close()
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user