ЛР4: S3-вложения (SeaweedFS), приватный bucket, компенсация/reconciler, тесты, отчёт

This commit is contained in:
2026-11-06 17:11:20 +03:00
parent ec540a1a72
commit b25600adcc
62 changed files with 4196 additions and 19 deletions
+1
View File
@@ -0,0 +1 @@
"""MTUSI Messenger lab3 application package."""
+556
View File
@@ -0,0 +1,556 @@
"""FastAPI application implementing the lab4 HTTP contract.
Canonical contract: ``contracts/openapi.json`` and ``contracts/README.md``.
PostgreSQL is the source of truth for metadata; bytes live in a private S3
bucket. Valkey is a best-effort session cache. Every response carries a
non-empty ``X-Request-Id`` and ``X-Instance-Id``. Messages are idempotent per
``Idempotency-Key`` and may reference attachments of the same chat.
"""
from __future__ import annotations
import base64
import binascii
import hashlib
import logging
import re
import tempfile
import uuid
from contextlib import asynccontextmanager
from typing import Dict, List, Optional
from fastapi import Depends, FastAPI, Query, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from psycopg import InterfaceError, OperationalError
from psycopg_pool import PoolTimeout
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException as StarletteHTTPException
from . import imaging, invalidation, storage
from . import repositories as repo
from . import security, sessions, state
from .config import settings
from .db import pool
from .errors import ApiError
from .instance import INSTANCE_ID
from .pagination import bound_cursor, encode_cursor
logger = logging.getLogger("messenger")
BEARER_CHALLENGE = 'Bearer realm="messenger"'
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
_BEARER_RE = re.compile(r"^Bearer\s+(\S+)$", re.IGNORECASE)
_IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
_STATUS_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
405: "invalid_request",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
503: "unavailable",
}
@asynccontextmanager
async def lifespan(_: FastAPI):
invalidation.start_worker()
try:
yield
finally:
invalidation.stop_worker()
app = FastAPI(
title="MTUSI Messenger — лабораторная 4",
version="1.4.0",
docs_url=None,
redoc_url=None,
openapi_url=None,
lifespan=lifespan,
)
# --------------------------------------------------------------------------- #
# Error envelope
# --------------------------------------------------------------------------- #
def _request_id(request: Request) -> str:
return getattr(request.state, "request_id", None) or uuid.uuid4().hex
def error_response(
request: Request, status: int, code: str, message: str, challenge: Optional[str] = None
) -> JSONResponse:
rid = _request_id(request)
headers = {"X-Request-Id": rid, "X-Instance-Id": INSTANCE_ID}
if challenge:
headers["WWW-Authenticate"] = challenge
return JSONResponse(
status_code=status,
content={"error": {"code": code, "message": message, "request_id": rid}},
headers=headers,
)
@app.middleware("http")
async def request_context(request: Request, call_next):
rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex
request.state.request_id = rid
try:
response = await call_next(request)
except Exception as exc: # noqa: BLE001 - never leak internals
logging.getLogger("messenger").error("unhandled error: %s", type(exc).__name__)
logging.getLogger("messenger").debug("traceback", exc_info=exc)
response = error_response(request, 500, "internal_error", "Внутренняя ошибка")
response.headers["X-Request-Id"] = rid
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
@app.exception_handler(ApiError)
async def handle_api_error(request: Request, exc: ApiError) -> JSONResponse:
challenge = exc.challenge or (BEARER_CHALLENGE if exc.status == 401 else None)
return error_response(request, exc.status, exc.code, exc.message, challenge)
@app.exception_handler(RequestValidationError)
async def handle_validation(request: Request, exc: RequestValidationError) -> JSONResponse:
return error_response(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(StarletteHTTPException)
async def handle_http_error(request: Request, exc: StarletteHTTPException) -> JSONResponse:
code = _STATUS_CODES.get(exc.status_code, "invalid_request")
challenge = BEARER_CHALLENGE if exc.status_code == 401 else None
return error_response(request, exc.status_code, code, "Ошибка запроса", challenge)
def _handle_db_error(request: Request, exc: Exception) -> JSONResponse:
logger.warning("database unavailable: %s", type(exc).__name__)
return error_response(request, 503, "unavailable", "База данных недоступна")
app.add_exception_handler(OperationalError, _handle_db_error)
app.add_exception_handler(InterfaceError, _handle_db_error)
app.add_exception_handler(PoolTimeout, _handle_db_error)
# --------------------------------------------------------------------------- #
# Request schemas
# --------------------------------------------------------------------------- #
class CreateUser(BaseModel):
model_config = ConfigDict(extra="forbid")
username: str = Field(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("display_name")
@classmethod
def _not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("display_name must not be blank")
return value
class CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(min_length=1, max_length=100)
member_ids: List[uuid.UUID] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def _not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("title must not be blank")
return value
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(max_length=4000)
attachment_ids: List[uuid.UUID] = Field(default_factory=list, max_length=10)
@field_validator("attachment_ids")
@classmethod
def _unique(cls, value: List[uuid.UUID]) -> List[uuid.UUID]:
if len(set(map(str, value))) != len(value):
raise ValueError("duplicate attachment_ids")
return value
@model_validator(mode="after")
def _non_empty(self) -> "CreateMessage":
if not self.text.strip() and not self.attachment_ids:
raise ValueError("message must have text or attachments")
return self
# --------------------------------------------------------------------------- #
# Dependencies and helpers
# --------------------------------------------------------------------------- #
def get_conn():
with pool().connection() as conn:
yield conn
def _canonical_uuid(value: str) -> str:
try:
return str(uuid.UUID(value))
except (ValueError, AttributeError, TypeError):
raise ApiError(400, "invalid_request", "Некорректный идентификатор")
def _parse_basic(request: Request) -> tuple[str, str]:
header = request.headers.get("Authorization", "").strip()
if not header.lower().startswith("basic "):
raise ApiError(401, "unauthorized", "Требуется Basic-аутентификация", challenge=BASIC_CHALLENGE)
encoded = header[6:].strip()
try:
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
except (binascii.Error, ValueError, UnicodeDecodeError):
raise ApiError(401, "unauthorized", "Неверные учётные данные", challenge=BASIC_CHALLENGE)
if ":" not in decoded:
raise ApiError(401, "unauthorized", "Неверные учётные данные", challenge=BASIC_CHALLENGE)
username, password = decoded.split(":", 1)
return username, password
def _bearer_token(request: Request) -> str:
header = request.headers.get("Authorization", "").strip()
match = _BEARER_RE.match(header)
if not match:
raise ApiError(401, "unauthorized", "Требуется Bearer-токен", challenge=BEARER_CHALLENGE)
return match.group(1)
def _idempotency_key(request: Request) -> str:
value = (request.headers.get("Idempotency-Key") or "").strip()
if not value or not _IDEMPOTENCY_RE.match(value):
raise ApiError(400, "invalid_request", "Требуется корректный Idempotency-Key")
return value
def current_user(request: Request, conn=Depends(get_conn)) -> Dict:
token = _bearer_token(request)
user_id = sessions.resolve(conn, token)
if user_id is None:
raise ApiError(401, "unauthorized", "Сессия недействительна", challenge=BEARER_CHALLENGE)
row = repo.get_user_by_id(conn, user_id)
if row is None:
raise ApiError(401, "unauthorized", "Сессия недействительна", challenge=BEARER_CHALLENGE)
return row
def _require_chat(conn, chat_id: str, user_id: str) -> str:
canonical = _canonical_uuid(chat_id)
if repo.get_chat_for(conn, canonical, user_id) is None:
raise ApiError(404, "not_found", "Чат недоступен")
return canonical
def _require_chat_standalone(chat_id: str, user_id: str) -> str:
"""Chat-membership check on its own connection (used by the async upload)."""
with pool().connection() as conn:
return _require_chat(conn, chat_id, user_id)
def _validate_filename(name: str) -> str:
if not name or len(name) > 255:
raise ApiError(400, "invalid_request", "Недопустимое имя файла")
if any(ch in name for ch in ("/", "\\", "\x00")) or any(
ord(ch) < 0x20 or ord(ch) == 0x7F for ch in name
):
raise ApiError(400, "invalid_request", "Недопустимое имя файла")
return name
def _validate_attachments(conn, chat_id: str, attachment_ids: List[str]) -> List[str]:
"""All referenced attachments must exist in THIS chat and be ready."""
if not attachment_ids:
return []
rows = repo.attachments_in_chat(conn, chat_id, attachment_ids)
found = {str(row["id"]): row["status"] for row in rows}
if len(found) != len(set(attachment_ids)):
raise ApiError(404, "not_found", "Вложение недоступно")
for attachment_id in attachment_ids:
if found.get(attachment_id) != "ready":
raise ApiError(409, "conflict", "Вложение не готово")
return attachment_ids
def _finalize_upload(
chat_id: str, owner_id: str, filename: str, fileobj, size_bytes: int, sha256: str
) -> Dict:
"""Validate the image, store the bytes in S3 and commit metadata.
Runs in a worker thread. The bytes are validated from the temporary file
(never trusted from headers) and uploaded with a server-generated key. If
the metadata COMMIT fails after the PUT, the object is deleted so a failed
upload does not leave an untracked object behind (best-effort; the
reconciler covers crash windows, see scripts/reconcile-s3.py).
"""
content_type, _width, _height = imaging.inspect(fileobj)
attachment_id = str(uuid.uuid4())
key = f"chats/{chat_id}/{attachment_id}"
fileobj.seek(0)
storage.put_object(key, fileobj, content_type)
try:
with pool().connection() as conn:
now = repo.utcnow()
row = repo.insert_attachment(
conn,
attachment_id,
chat_id,
owner_id,
filename,
content_type,
size_bytes,
sha256,
key,
"ready",
None,
now,
now,
)
return repo.attachment_json(row)
except Exception:
if storage.delete_object(key):
logger.warning("compensated orphan S3 object %s", key)
raise
# --------------------------------------------------------------------------- #
# Health
# --------------------------------------------------------------------------- #
@app.get("/health/live")
def liveness() -> dict:
return {"status": "ok"}
@app.get("/health/ready")
def readiness() -> dict:
if state.is_shutting_down():
raise ApiError(503, "unavailable", "Реплика останавливается")
try:
with pool().connection(timeout=2) as conn:
conn.execute("select 1")
except (OperationalError, InterfaceError, PoolTimeout):
raise ApiError(503, "unavailable", "База данных недоступна")
if not storage.ready():
raise ApiError(503, "unavailable", "Хранилище недоступно")
return {"status": "ok"}
# --------------------------------------------------------------------------- #
# Users and sessions
# --------------------------------------------------------------------------- #
@app.post("/api/v1/users", status_code=201)
def register_user(payload: CreateUser, conn=Depends(get_conn)) -> dict:
password_hash = security.hash_password(payload.password)
row = repo.create_user(conn, payload.username, payload.display_name, password_hash)
return repo.user_json(row)
@app.post("/api/v1/auth/sessions", status_code=201)
def create_session(request: Request, conn=Depends(get_conn)) -> dict:
username, password = _parse_basic(request)
row = repo.get_user_with_hash_by_username(conn, username)
if row is None or not security.verify_password(row["password_hash"], password):
raise ApiError(401, "unauthorized", "Неверные учётные данные", challenge=BASIC_CHALLENGE)
token, expires_at = sessions.create(conn, str(row["id"]))
return {
"token": token,
"token_type": "Bearer",
"expires_at": repo.rfc3339(expires_at),
"user": repo.user_json(row),
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def revoke_session(
request: Request,
user: Dict = Depends(current_user),
conn=Depends(get_conn),
) -> Response:
sessions.revoke(conn, _bearer_token(request))
return Response(status_code=204)
@app.get("/api/v1/users/me")
def current_user_endpoint(user: Dict = Depends(current_user)) -> dict:
return repo.user_json(user)
# --------------------------------------------------------------------------- #
# Chats
# --------------------------------------------------------------------------- #
@app.post("/api/v1/chats", status_code=201)
def create_chat(payload: CreateChat, user: Dict = Depends(current_user), conn=Depends(get_conn)) -> dict:
members = [str(member) for member in payload.member_ids]
if len(set(members)) != len(members):
raise ApiError(400, "invalid_request", "Дубликаты участников")
if str(user["id"]) not in members:
raise ApiError(400, "invalid_request", "Вызывающий должен входить в участников")
if repo.count_users(conn, members) != len(set(members)):
raise ApiError(400, "invalid_request", "Неизвестный участник")
row = repo.create_chat(conn, payload.title, members)
return repo.chat_json(row)
@app.get("/api/v1/chats")
def list_chats(
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None),
user: Dict = Depends(current_user),
conn=Depends(get_conn),
) -> dict:
key = bound_cursor(cursor, "chats")
rows = repo.list_chats(conn, str(user["id"]), limit + 1, key)
page = rows[:limit]
next_cursor = None
if len(rows) > limit:
next_cursor = encode_cursor("chats", page[-1]["created_at"], str(page[-1]["id"]))
return {"items": [repo.chat_json(row) for row in page], "next_cursor": next_cursor}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: str, user: Dict = Depends(current_user), conn=Depends(get_conn)) -> dict:
canonical = _require_chat(conn, chat_id, str(user["id"]))
row = repo.get_chat_for(conn, canonical, str(user["id"]))
return repo.chat_json(row)
# --------------------------------------------------------------------------- #
# Messages
# --------------------------------------------------------------------------- #
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def create_message(
chat_id: str,
payload: CreateMessage,
request: Request,
user: Dict = Depends(current_user),
conn=Depends(get_conn),
) -> dict:
canonical = _require_chat(conn, chat_id, str(user["id"]))
key = _idempotency_key(request)
attachment_ids = _validate_attachments(
conn, canonical, [str(item) for item in payload.attachment_ids]
)
scope = f"POST /api/v1/chats/{canonical}/messages"
return repo.create_message_idempotent(
conn,
canonical,
str(user["id"]),
payload.text,
attachment_ids,
scope,
key,
settings.idempotency_ttl_seconds,
)
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(
chat_id: str,
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None),
user: Dict = Depends(current_user),
conn=Depends(get_conn),
) -> dict:
canonical = _require_chat(conn, chat_id, str(user["id"]))
key = bound_cursor(cursor, canonical)
rows = repo.list_messages(conn, canonical, limit + 1, key)
page = rows[:limit]
next_cursor = None
if len(rows) > limit:
next_cursor = encode_cursor(canonical, page[-1]["created_at"], str(page[-1]["id"]))
return {"items": [repo.message_json(row) for row in page], "next_cursor": next_cursor}
# --------------------------------------------------------------------------- #
# Attachments (lab4)
# --------------------------------------------------------------------------- #
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
async def upload_attachment(
chat_id: str,
request: Request,
filename: str = Query(..., min_length=1, max_length=255),
user: Dict = Depends(current_user),
) -> dict:
canonical = await run_in_threadpool(_require_chat_standalone, chat_id, str(user["id"]))
safe_name = _validate_filename(filename)
content_length = request.headers.get("Content-Length", "")
if content_length.isdigit() and int(content_length) > settings.max_upload_bytes:
raise ApiError(413, "payload_too_large", "Файл слишком большой")
# Stream the raw bytes to a bounded spill-to-disk file, hashing as we go, so
# a single upload never holds the whole body in RAM.
spool = tempfile.SpooledTemporaryFile(max_size=1024 * 1024)
size = 0
digest = hashlib.sha256()
try:
async for chunk in request.stream():
if not chunk:
continue
size += len(chunk)
if size > settings.max_upload_bytes:
raise ApiError(413, "payload_too_large", "Файл слишком большой")
digest.update(chunk)
spool.write(chunk)
if size == 0:
raise ApiError(415, "unsupported_media_type", "Пустой файл")
spool.seek(0)
return await run_in_threadpool(
_finalize_upload,
canonical,
str(user["id"]),
safe_name,
spool,
size,
digest.hexdigest(),
)
finally:
spool.close()
@app.get("/api/v1/attachments/{attachment_id}")
def get_attachment(
attachment_id: str, user: Dict = Depends(current_user), conn=Depends(get_conn)
) -> dict:
canonical = _canonical_uuid(attachment_id)
row = repo.get_attachment_for(conn, canonical, str(user["id"]))
if row is None:
raise ApiError(404, "not_found", "Вложение недоступно")
return repo.attachment_json(row)
@app.get("/api/v1/attachments/{attachment_id}/content")
def download_attachment(
attachment_id: str,
variant: str = Query(default="original"),
user: Dict = Depends(current_user),
conn=Depends(get_conn),
) -> StreamingResponse:
canonical = _canonical_uuid(attachment_id)
row = repo.get_attachment_for(conn, canonical, str(user["id"]))
if row is None:
raise ApiError(404, "not_found", "Вложение недоступно")
if variant != "original" or row["status"] != "ready":
raise ApiError(404, "not_found", "Вариант не найден")
obj = storage.open_object(row["s3_key"])
body = obj["Body"]
def stream():
try:
for chunk in body.iter_chunks(chunk_size=64 * 1024):
yield chunk
finally:
body.close()
return StreamingResponse(stream(), media_type=row["content_type"])
+83
View File
@@ -0,0 +1,83 @@
"""Runtime configuration from environment variables / secret files.
Only logical interface names from ``.env.example`` are consumed; secret values
are read from files (``*_FILE``) so that no credential is baked into the image
or committed. The mapping is documented in REPORT.md.
"""
from __future__ import annotations
import os
from dataclasses import dataclass
from pathlib import Path
def _read_secret(file_key: str, value_key: str, default: str = "") -> str:
path = os.environ.get(file_key)
if path:
try:
return Path(path).read_text(encoding="utf-8").strip()
except OSError:
return default
return os.environ.get(value_key, default)
@dataclass(frozen=True)
class Settings:
app_host: str
app_port: int
app_env: str
session_ttl_seconds: int
session_store: str
session_cache_ttl_seconds: int
cache_invalidation_interval_seconds: float
idempotency_ttl_seconds: int
database_url: str
cache_url: str
db_pool_min: int
db_pool_max: int
db_pool_timeout: float
db_statement_timeout_ms: int
# S3 / attachment limits
s3_endpoint: str
s3_region: str
s3_bucket: str
s3_access_key_id: str
s3_secret_access_key: str
max_upload_bytes: int
max_image_pixels: int
@property
def cache_enabled(self) -> bool:
return bool(self.cache_url) and self.session_store in {"valkey", "redis"}
def load_settings() -> Settings:
return Settings(
app_host=os.environ.get("APP_HOST", "0.0.0.0"),
app_port=int(os.environ.get("APP_PORT", "8080")),
app_env=os.environ.get("APP_ENV", "lab"),
session_ttl_seconds=int(os.environ.get("SESSION_TTL_SECONDS", "3600")),
session_store=os.environ.get("SESSION_STORE", "postgres").lower(),
session_cache_ttl_seconds=int(os.environ.get("SESSION_CACHE_TTL_SECONDS", "60")),
cache_invalidation_interval_seconds=float(
os.environ.get("CACHE_INVALIDATION_INTERVAL_SECONDS", "0.5")
),
idempotency_ttl_seconds=int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400")),
database_url=_read_secret("DATABASE_URL_FILE", "DATABASE_URL"),
cache_url=_read_secret("CACHE_URL_FILE", "CACHE_URL"),
db_pool_min=int(os.environ.get("DB_POOL_MIN", "1")),
db_pool_max=int(os.environ.get("DB_POOL_MAX", "10")),
db_pool_timeout=float(os.environ.get("DB_POOL_TIMEOUT", "5")),
db_statement_timeout_ms=int(os.environ.get("DB_STATEMENT_TIMEOUT_MS", "5000")),
s3_endpoint=os.environ.get("S3_ENDPOINT", "http://s3:9000"),
s3_region=os.environ.get("S3_REGION", "us-east-1"),
s3_bucket=os.environ.get("S3_BUCKET", "messenger-attachments"),
s3_access_key_id=_read_secret("S3_ACCESS_KEY_ID_FILE", "S3_ACCESS_KEY_ID"),
s3_secret_access_key=_read_secret("S3_SECRET_ACCESS_KEY_FILE", "S3_SECRET_ACCESS_KEY"),
# 10 MiB per contract; allow one extra byte to detect "too large".
max_upload_bytes=int(os.environ.get("MAX_UPLOAD_BYTES", str(10 * 1024 * 1024))),
max_image_pixels=int(os.environ.get("MAX_IMAGE_PIXELS", "40000000")),
)
settings = load_settings()
+42
View File
@@ -0,0 +1,42 @@
"""PostgreSQL access: a bounded connection pool with timeouts.
All queries elsewhere are parameterized; this module only owns the pool.
A statement timeout and a bounded pool are part of the grade-4 requirements.
"""
from __future__ import annotations
import logging
from typing import Optional
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from .config import settings
logger = logging.getLogger("messenger.db")
_pool: Optional[ConnectionPool] = None
def pool() -> ConnectionPool:
global _pool
if _pool is None:
_pool = ConnectionPool(
conninfo=settings.database_url,
min_size=settings.db_pool_min,
max_size=settings.db_pool_max,
timeout=settings.db_pool_timeout,
kwargs={
"row_factory": dict_row,
"options": f"-c statement_timeout={settings.db_statement_timeout_ms}",
},
open=True,
)
return _pool
def close_pool() -> None:
global _pool
if _pool is not None:
_pool.close()
_pool = None
+20
View File
@@ -0,0 +1,20 @@
"""Shared error type mapped to the contract error envelope."""
from __future__ import annotations
from typing import Optional
class ApiError(Exception):
def __init__(
self,
status: int,
code: str,
message: str,
challenge: Optional[str] = None,
) -> None:
super().__init__(message)
self.status = status
self.code = code
self.message = message
# Optional WWW-Authenticate value (used by 401 responses).
self.challenge = challenge
+50
View File
@@ -0,0 +1,50 @@
"""Image validation for attachments.
The real format is decided by the bytes (Pillow), never by the client's
``Content-Type`` or by ``filename``. Pixel count is checked from the header
*before* any full decode, so a decompression bomb is rejected cheaply.
"""
from __future__ import annotations
import logging
from PIL import Image, UnidentifiedImageError
from .config import settings
from .errors import ApiError
logger = logging.getLogger("messenger.imaging")
# Pillow refuses images above this many pixels outright.
Image.MAX_IMAGE_PIXELS = settings.max_image_pixels
_CONTENT_TYPES = {"PNG": "image/png", "JPEG": "image/jpeg"}
def inspect(fileobj) -> tuple[str, int, int]:
"""Return ``(content_type, width, height)`` or raise ``ApiError``.
415 for anything that is not a valid PNG/JPEG, 413 for too many pixels.
"""
fileobj.seek(0)
try:
image = Image.open(fileobj) # header only; no full decode yet
fmt = image.format
width, height = image.size
except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError):
raise ApiError(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG")
content_type = _CONTENT_TYPES.get(fmt)
if content_type is None:
raise ApiError(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG")
if width * height > settings.max_image_pixels:
raise ApiError(413, "payload_too_large", "Слишком большое изображение")
# Validate the container without decoding every pixel into memory.
try:
image.verify()
except Exception: # noqa: BLE001 - any Pillow failure is an invalid image
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
return content_type, width, height
+21
View File
@@ -0,0 +1,21 @@
"""Stable identity of this API process, exposed as ``X-Instance-Id``.
The value is fixed for the whole life of the process, so clients and the
balancer can tell replicas apart. Inside Docker the default container hostname
already is the (short) container id, which makes the value easy to map back to
a real container without exposing a routable address.
"""
from __future__ import annotations
import os
import socket
def _resolve() -> str:
value = os.environ.get("INSTANCE_ID", "").strip()
if value:
return value
return socket.gethostname() or "api"
INSTANCE_ID = _resolve()
+76
View File
@@ -0,0 +1,76 @@
"""Durable cache-invalidation drainer (lab3).
Logout writes a pending invalidation to PostgreSQL in the same transaction as
the authoritative session delete. This tiny background thread (one per API
replica, not an external broker) removes the corresponding Valkey key and then
the queue row. Multiple replicas may process the same row; cache deletes are
idempotent, so this is safe and needs no distributed lock.
The worker is deliberately not on the request path: it only runs when a cache
is configured, and it retries forever while Valkey is unreachable. That is what
lets a logout survive a Valkey outage: the session is already gone from
PostgreSQL, and the stale cache entry is evicted as soon as the cache returns.
"""
from __future__ import annotations
import logging
import threading
from typing import Optional
from . import repositories as repo
from . import sessions
from .config import settings
from .db import pool
logger = logging.getLogger("messenger.invalidation")
_BATCH = 200
_stop = threading.Event()
_thread: Optional[threading.Thread] = None
def _drain_once() -> None:
with pool().connection() as conn:
pending = repo.list_pending_invalidations(conn, _BATCH)
if not pending:
return
invalidated = [token_hash for token_hash in pending if sessions.invalidate_session_key(token_hash)]
if not invalidated:
# Cache still unreachable; keep the rows for the next attempt.
return
with pool().connection() as conn:
repo.delete_cache_invalidations(conn, invalidated)
logger.debug("drained %d cache invalidations", len(invalidated))
def _loop() -> None:
while not _stop.is_set():
try:
_drain_once()
except Exception as exc: # noqa: BLE001 - never kill the drainer
logger.warning("cache invalidation drain failed: %s", type(exc).__name__)
_stop.wait(settings.cache_invalidation_interval_seconds)
def start_worker() -> None:
global _thread
if not settings.cache_enabled:
return
if _thread is not None and _thread.is_alive():
return
_stop.clear()
_thread = threading.Thread(target=_loop, name="cache-invalidation", daemon=True)
_thread.start()
logger.info(
"cache invalidation drainer started (interval=%.2fs)",
settings.cache_invalidation_interval_seconds,
)
def stop_worker() -> None:
global _thread
_stop.set()
if _thread is not None:
_thread.join(timeout=2)
_thread = None
+60
View File
@@ -0,0 +1,60 @@
"""Container entrypoint: run the HTTP server as PID 1 with graceful shutdown.
Migrations are executed by the dedicated one-shot ``migrate`` compose service
(``python -m src.migrate``) before any replica starts, so replicas do not race
on the schema.
On SIGTERM/SIGINT the handler marks the process as shutting down: readiness
degrades to 503 so the balancer drains this replica, then Uvicorn stops
accepting connections and waits up to ``timeout_graceful_shutdown`` for
in-flight requests to finish.
"""
from __future__ import annotations
import logging
import os
import uvicorn
from . import state
from .config import settings
from .instance import INSTANCE_ID
def main() -> None:
logging.basicConfig(
level=os.environ.get("LOG_LEVEL", "INFO").upper(),
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logging.getLogger("messenger").info(
"starting messenger api instance=%s env=%s port=%s sessions=%s cache=%s",
INSTANCE_ID,
settings.app_env,
settings.app_port,
settings.session_store,
"on" if settings.cache_enabled else "off",
)
config = uvicorn.Config(
"src.app:app",
host=settings.app_host,
port=settings.app_port,
log_level=os.environ.get("LOG_LEVEL", "info").lower(),
access_log=True,
timeout_graceful_shutdown=10,
)
server = uvicorn.Server(config)
def handle_exit(sig, frame=None): # noqa: ANN001 - signal handler
state.begin_shutdown()
logging.getLogger("messenger").info("received signal %s; draining", sig)
server.should_exit = True
# Uvicorn installs this exact method as its signal handler; overriding the
# bound attribute keeps cross-platform behaviour while adding our flag.
server.handle_exit = handle_exit
server.run()
if __name__ == "__main__":
main()
+67
View File
@@ -0,0 +1,67 @@
"""Versioned, idempotent migration runner.
Applied versions are recorded in ``schema_migrations``; a transaction-scoped
advisory lock serializes concurrent callers. In lab3 migrations are executed by
a dedicated one-shot ``migrate`` service, not by every API replica, so schema
changes happen exactly once before any replica starts serving traffic.
"""
from __future__ import annotations
import logging
import time
from pathlib import Path
import psycopg
from psycopg_pool import PoolTimeout
from .db import pool
logger = logging.getLogger("messenger.migrate")
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
LOCK_KEY = 776_2026
def _apply_once() -> None:
files = sorted(MIGRATIONS_DIR.glob("*.sql"))
with pool().connection() as conn:
conn.execute("select pg_advisory_xact_lock(%s)", (LOCK_KEY,))
conn.execute(
"""
create table if not exists schema_migrations (
version text primary key,
applied_at timestamptz not null default now()
)
"""
)
applied = {
row["version"]
for row in conn.execute("select version from schema_migrations").fetchall()
}
for path in files:
if path.name in applied:
continue
logger.info("applying migration %s", path.name)
conn.execute(path.read_text(encoding="utf-8"))
conn.execute(
"insert into schema_migrations (version) values (%s)", (path.name,)
)
def apply_migrations(attempts: int = 30, delay: float = 1.0) -> None:
last: Exception | None = None
for attempt in range(1, attempts + 1):
try:
_apply_once()
logger.info("migrations up to date")
return
except (psycopg.OperationalError, PoolTimeout) as exc:
last = exc
logger.warning("database not ready (attempt %s/%s): %s", attempt, attempts, exc)
time.sleep(delay)
raise RuntimeError(f"database unavailable after {attempts} attempts: {last}")
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
apply_migrations()
+53
View File
@@ -0,0 +1,53 @@
"""Opaque keyset cursors for ``(created_at, id)`` ascending pagination."""
from __future__ import annotations
import base64
import binascii
import datetime as dt
import json
import uuid
from typing import Optional, Tuple
from .errors import ApiError
CursorKey = Tuple[dt.datetime, str]
def encode_cursor(resource_id: str, created_at: dt.datetime, item_id: str) -> str:
payload = json.dumps(
{
"r": resource_id,
"t": created_at.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
"i": item_id,
},
separators=(",", ":"),
).encode("utf-8")
return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")
def decode_cursor(cursor: str) -> Tuple[str, CursorKey]:
try:
padded = cursor + "=" * (-len(cursor) % 4)
data = json.loads(base64.urlsafe_b64decode(padded).decode("utf-8"))
if not isinstance(data, dict):
raise ValueError("cursor payload must be an object")
resource = data["r"]
item_id = data["i"]
if not isinstance(resource, str) or not isinstance(item_id, str):
raise ValueError("cursor fields must be strings")
created = dt.datetime.strptime(data["t"], "%Y-%m-%dT%H:%M:%S.%fZ").replace(
tzinfo=dt.timezone.utc
)
return resource, (created, str(uuid.UUID(item_id)))
except (binascii.Error, ValueError, KeyError, TypeError, AttributeError, UnicodeDecodeError):
raise ApiError(400, "invalid_request", "Некорректный cursor")
def bound_cursor(cursor: str, expected_resource: str) -> Optional[CursorKey]:
"""Validate resource binding and return the key, or None for empty cursor."""
if cursor is None:
return None
resource, key = decode_cursor(cursor)
if resource != expected_resource:
raise ApiError(400, "invalid_request", "cursor относится к другому ресурсу")
return key
+75
View File
@@ -0,0 +1,75 @@
"""Reconcile S3 objects and attachment metadata (lab4 grade-4 safety net).
The synchronous upload spends a short window between the S3 PUT and the
PostgreSQL COMMIT. A crash there can leave an *orphan* object (in S3, no row);
the inline compensation in the API covers the ordinary failure path, and this
tool covers crash windows and any object created but never referenced.
docker compose exec -T api python -m src.reconcile # dry-run
docker compose exec -T api python -m src.reconcile --apply # delete orphans
Safety:
* dry-run by default; ``--apply`` is required to delete anything;
* only objects with no metadata row are candidates (referenced objects are
never touched);
* only objects older than ``--grace-seconds`` (default 3600) are deleted, so a
just-started upload is never mistaken for an orphan;
* objects present in metadata but missing in S3 are reported, never guessed.
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
from . import repositories as repo
from . import storage
from .db import pool
def main() -> None:
parser = argparse.ArgumentParser(description="Reconcile S3 objects and attachment metadata")
parser.add_argument("--apply", action="store_true", help="actually delete orphan objects")
parser.add_argument("--grace-seconds", type=int, default=3600)
parser.add_argument("--limit", type=int, default=50, help="how many orphans to print")
args = parser.parse_args()
with pool().connection() as conn:
rows = repo.list_all_attachments(conn)
known = {str(row["s3_key"]): str(row["id"]) for row in rows}
cutoff = dt.datetime.now(dt.timezone.utc) - dt.timedelta(seconds=args.grace_seconds)
objects = list(storage.list_keys(""))
s3_keys = {item["Key"]: item.get("LastModified") for item in objects}
missing = sorted(key for key in known if key not in s3_keys)
orphans = []
for key, modified in s3_keys.items():
if key in known:
continue
if modified is not None and modified > cutoff:
continue # too fresh: may be an in-flight upload
orphans.append(key)
report = {
"db_attachments": len(known),
"s3_objects": len(s3_keys),
"orphans": len(orphans),
"missing": len(missing),
"apply": bool(args.apply),
"grace_seconds": args.grace_seconds,
}
print(json.dumps(report, ensure_ascii=False))
for key in sorted(orphans)[: args.limit]:
print("orphan:", key)
for key in missing[: args.limit]:
print("missing:", key, "attachment_id=" + known[key])
if args.apply and orphans:
deleted = sum(1 for key in orphans if storage.delete_object(key))
print(json.dumps({"deleted_orphans": deleted}))
if __name__ == "__main__":
main()
+509
View File
@@ -0,0 +1,509 @@
"""Parameterized SQL for users, chats, members, messages, sessions and the
shared idempotency ledger.
Every statement uses bound parameters (no string concatenation). Composite
writes happen inside one transaction so the caller gets all-or-nothing.
"""
from __future__ import annotations
import datetime as dt
import hashlib
import json
import uuid
from typing import Dict, List, Optional, Sequence
from psycopg.errors import UniqueViolation
from psycopg.types.json import Jsonb
from .errors import ApiError
from .pagination import CursorKey
def utcnow() -> dt.datetime:
return dt.datetime.now(dt.timezone.utc)
def rfc3339(value: dt.datetime) -> str:
return value.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z"
def _members(value) -> List[str]:
if value is None:
return []
return [str(item) for item in value]
def user_json(row: Dict) -> Dict:
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": rfc3339(row["created_at"]),
}
def chat_json(row: Dict) -> Dict:
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": _members(row["member_ids"]),
"created_at": rfc3339(row["created_at"]),
}
def message_json(row: Dict) -> Dict:
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": rfc3339(row["created_at"]),
"attachment_ids": _members(row.get("attachment_ids")),
}
_MESSAGE_ATTACHMENTS_SUBQUERY = (
"(select array_agg(ma.attachment_id order by ma.position) "
"from message_attachments ma where ma.message_id = m.id)"
)
def attachment_json(row: Dict) -> Dict:
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"owner_id": str(row["owner_id"]),
"filename": row["filename"],
"content_type": row["content_type"],
"size_bytes": int(row["size_bytes"]),
"sha256": row["sha256"],
"status": row["status"],
"variants": [],
"error_code": row["error_code"],
"created_at": rfc3339(row["created_at"]),
"updated_at": rfc3339(row["updated_at"]),
}
# --------------------------------------------------------------------------- #
# Users
# --------------------------------------------------------------------------- #
def create_user(conn, username: str, display_name: str, password_hash: str) -> Dict:
try:
row = conn.execute(
"""
insert into users (id, username, display_name, password_hash, created_at)
values (%s, %s, %s, %s, %s)
returning id, username, display_name, created_at
""",
(str(uuid.uuid4()), username, display_name, password_hash, utcnow()),
).fetchone()
except UniqueViolation:
raise ApiError(409, "conflict", "Имя пользователя уже занято")
return row
def get_user_by_id(conn, user_id: str) -> Optional[Dict]:
return conn.execute(
"select id, username, display_name, created_at from users where id = %s",
(user_id,),
).fetchone()
def get_user_with_hash_by_username(conn, username: str) -> Optional[Dict]:
return conn.execute(
"select id, username, display_name, created_at, password_hash from users where username = %s",
(username,),
).fetchone()
def count_users(conn, user_ids: Sequence[str]) -> int:
row = conn.execute(
"select count(*) as n from users where id = any(%s::uuid[])", (list(user_ids),)
).fetchone()
return int(row["n"])
# --------------------------------------------------------------------------- #
# Chats
# --------------------------------------------------------------------------- #
def create_chat(conn, title: str, member_ids: Sequence[str]) -> Dict:
chat_id = str(uuid.uuid4())
created = utcnow()
conn.execute(
"insert into chats (id, title, created_at) values (%s, %s, %s)",
(chat_id, title, created),
)
with conn.cursor() as cur:
cur.executemany(
"insert into chat_members (chat_id, user_id) values (%s, %s)",
[(chat_id, member) for member in member_ids],
)
return {
"id": chat_id,
"title": title,
"member_ids": list(member_ids),
"created_at": created,
}
_MEMBER_SUBQUERY = (
"(select array_agg(m.user_id) from chat_members m where m.chat_id = c.id)"
)
def get_chat_for(conn, chat_id: str, user_id: str) -> Optional[Dict]:
return conn.execute(
f"""
select c.id, c.title, c.created_at, {_MEMBER_SUBQUERY} as member_ids
from chats c
where c.id = %s
and exists (
select 1 from chat_members cm
where cm.chat_id = c.id and cm.user_id = %s
)
""",
(chat_id, user_id),
).fetchone()
def list_chats(conn, user_id: str, limit: int, cursor: Optional[CursorKey]) -> List[Dict]:
if cursor is None:
return conn.execute(
f"""
select c.id, c.title, c.created_at, {_MEMBER_SUBQUERY} as member_ids
from chats c
join chat_members cm on cm.chat_id = c.id
where cm.user_id = %s
order by c.created_at, c.id
limit %s
""",
(user_id, limit),
).fetchall()
return conn.execute(
f"""
select c.id, c.title, c.created_at, {_MEMBER_SUBQUERY} as member_ids
from chats c
join chat_members cm on cm.chat_id = c.id
where cm.user_id = %s and (c.created_at, c.id) > (%s, %s)
order by c.created_at, c.id
limit %s
""",
(user_id, cursor[0], cursor[1], limit),
).fetchall()
# --------------------------------------------------------------------------- #
# Messages
# --------------------------------------------------------------------------- #
def insert_message(
conn, chat_id: str, sender_id: str, text: str, attachment_ids: Sequence[str] = ()
) -> Dict:
message_id = str(uuid.uuid4())
created = utcnow()
conn.execute(
"insert into messages (id, chat_id, sender_id, text, created_at) values (%s, %s, %s, %s, %s)",
(message_id, chat_id, sender_id, text, created),
)
attachments = list(attachment_ids)
if attachments:
with conn.cursor() as cur:
cur.executemany(
"insert into message_attachments (message_id, attachment_id, position) values (%s, %s, %s)",
[(message_id, attachment_id, position) for position, attachment_id in enumerate(attachments)],
)
return {
"id": message_id,
"chat_id": chat_id,
"sender_id": sender_id,
"text": text,
"created_at": created,
"attachment_ids": attachments,
}
def list_messages(
conn, chat_id: str, limit: int, cursor: Optional[CursorKey]
) -> List[Dict]:
if cursor is None:
return conn.execute(
f"""
select m.id, m.chat_id, m.sender_id, m.text, m.created_at,
{_MESSAGE_ATTACHMENTS_SUBQUERY} as attachment_ids
from messages m
where m.chat_id = %s
order by m.created_at, m.id
limit %s
""",
(chat_id, limit),
).fetchall()
return conn.execute(
f"""
select m.id, m.chat_id, m.sender_id, m.text, m.created_at,
{_MESSAGE_ATTACHMENTS_SUBQUERY} as attachment_ids
from messages m
where m.chat_id = %s and (m.created_at, m.id) > (%s, %s)
order by m.created_at, m.id
limit %s
""",
(chat_id, cursor[0], cursor[1], limit),
).fetchall()
# --------------------------------------------------------------------------- #
# Shared idempotency ledger (lab3)
# --------------------------------------------------------------------------- #
def message_request_hash(text: str, attachment_ids: Sequence[str] = ()) -> str:
"""Canonical hash of the semantic body.
JSON key order and an absent ``attachment_ids`` versus ``[]`` must be
equivalent, and the order of attachment ids is not significant. The
canonical form is deterministic so any replica computes the same value.
"""
canonical = json.dumps(
{"text": text, "attachment_ids": sorted(attachment_ids or [])},
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def get_idempotency(conn, user_id: str, scope: str, key: str) -> Optional[Dict]:
return conn.execute(
"""
select request_hash, status_code, response_body
from idempotency_keys
where user_id = %s and scope = %s and key = %s
""",
(user_id, scope, key),
).fetchone()
def insert_idempotency(
conn,
user_id: str,
scope: str,
key: str,
request_hash: str,
status_code: int,
response_body: Dict,
ttl_seconds: int,
) -> None:
conn.execute(
"""
insert into idempotency_keys
(user_id, scope, key, request_hash, status_code, response_body, created_at, expires_at)
values (%s, %s, %s, %s, %s, %s, now(), now() + make_interval(secs => %s))
""",
(user_id, scope, key, request_hash, status_code, Jsonb(response_body), ttl_seconds),
)
def purge_expired_idempotency(conn) -> int:
rows = conn.execute(
"delete from idempotency_keys where expires_at <= now() returning key"
).fetchall()
return len(rows)
def create_message_idempotent(
conn,
chat_id: str,
sender_id: str,
text: str,
attachment_ids: Sequence[str],
scope: str,
key: str,
ttl_seconds: int,
) -> Dict:
"""Create a message exactly once for (sender, scope, key).
A transaction-scoped advisory lock keyed on the logical idempotency scope
serializes concurrent retries across *all* API replicas through PostgreSQL.
The first caller inserts the message (and its attachment links) and the
ledger row in one transaction; later callers observe the committed row and
replay the stored response. A reused key with different content conflicts.
"""
request_hash = message_request_hash(text, attachment_ids)
conn.execute(
"select pg_advisory_xact_lock(hashtext(%s), hashtext(%s))",
(sender_id + "|" + scope, key),
)
existing = get_idempotency(conn, sender_id, scope, key)
if existing is not None:
if existing["request_hash"] != request_hash:
raise ApiError(409, "conflict", "Idempotency-Key уже использован с другим сообщением")
return existing["response_body"]
message = insert_message(conn, chat_id, sender_id, text, attachment_ids)
body = message_json(message)
insert_idempotency(conn, sender_id, scope, key, request_hash, 201, body, ttl_seconds)
return body
# --------------------------------------------------------------------------- #
# Sessions (PostgreSQL is the source of truth)
# --------------------------------------------------------------------------- #
def insert_session(conn, token_hash: str, user_id: str, expires_at: dt.datetime) -> None:
conn.execute(
"""
insert into sessions (token_hash, user_id, created_at, expires_at)
values (%s, %s, %s, %s)
""",
(token_hash, user_id, utcnow(), expires_at),
)
def get_valid_session(conn, token_hash: str) -> Optional[Dict]:
return conn.execute(
"""
select token_hash, user_id, expires_at
from sessions
where token_hash = %s and expires_at > now()
""",
(token_hash,),
).fetchone()
def delete_session(conn, token_hash: str) -> None:
conn.execute("delete from sessions where token_hash = %s", (token_hash,))
def purge_expired_sessions(conn) -> int:
row = conn.execute(
"delete from sessions where expires_at <= now() returning token_hash"
).fetchall()
return len(row)
# --------------------------------------------------------------------------- #
# Durable cache invalidation queue (lab3)
# --------------------------------------------------------------------------- #
def enqueue_cache_invalidation(conn, token_hash: str) -> None:
"""Record a session cache key that must be removed from Valkey.
Written in the same transaction as the authoritative session delete, so a
committed logout can never lose the obligation to invalidate the cache.
"""
conn.execute(
"""
insert into cache_invalidations (token_hash, created_at)
values (%s, now())
on conflict (token_hash) do nothing
""",
(token_hash,),
)
def list_pending_invalidations(conn, limit: int) -> List[str]:
rows = conn.execute(
"select token_hash from cache_invalidations order by created_at limit %s",
(limit,),
).fetchall()
return [str(row["token_hash"]) for row in rows]
def delete_cache_invalidations(conn, token_hashes: Sequence[str]) -> None:
if not token_hashes:
return
conn.execute(
"delete from cache_invalidations where token_hash = any(%s)",
(list(token_hashes),),
)
# --------------------------------------------------------------------------- #
# Attachments (lab4): metadata in PostgreSQL, bytes in S3
# --------------------------------------------------------------------------- #
def insert_attachment(
conn,
attachment_id: str,
chat_id: str,
owner_id: str,
filename: str,
content_type: str,
size_bytes: int,
sha256: str,
s3_key: str,
status: str,
error_code: Optional[str],
created_at: dt.datetime,
updated_at: dt.datetime,
) -> Dict:
return conn.execute(
"""
insert into attachments
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
status, s3_key, error_code, created_at, updated_at)
values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
returning id, chat_id, owner_id, filename, content_type, size_bytes,
sha256, status, s3_key, error_code, created_at, updated_at
""",
(
attachment_id,
chat_id,
owner_id,
filename,
content_type,
size_bytes,
sha256,
status,
s3_key,
error_code,
created_at,
updated_at,
),
).fetchone()
def get_attachment(conn, attachment_id: str) -> Optional[Dict]:
return conn.execute(
"""
select id, chat_id, owner_id, filename, content_type, size_bytes,
sha256, status, s3_key, error_code, created_at, updated_at
from attachments where id = %s
""",
(attachment_id,),
).fetchone()
def get_attachment_for(conn, attachment_id: str, user_id: str) -> Optional[Dict]:
"""Metadata only when the caller is a member of the attachment's chat."""
return conn.execute(
"""
select a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
a.size_bytes, a.sha256, a.status, a.s3_key, a.error_code,
a.created_at, a.updated_at
from attachments a
where a.id = %s
and exists (
select 1 from chat_members cm
where cm.chat_id = a.chat_id and cm.user_id = %s
)
""",
(attachment_id, user_id),
).fetchone()
def attachments_in_chat(conn, chat_id: str, attachment_ids: Sequence[str]) -> List[Dict]:
if not attachment_ids:
return []
return conn.execute(
"""
select id, status from attachments
where chat_id = %s and id = any(%s::uuid[])
""",
(chat_id, list(attachment_ids)),
).fetchall()
def list_attachments_for_chat(conn, chat_id: str) -> List[Dict]:
return conn.execute(
"select id, s3_key, created_at from attachments where chat_id = %s",
(chat_id,),
).fetchall()
def list_all_attachments(conn) -> List[Dict]:
return conn.execute("select id, s3_key, created_at from attachments").fetchall()
+57
View File
@@ -0,0 +1,57 @@
"""Idempotent S3 bucket bootstrap (one-shot compose service).
Creates the private attachments bucket with the root credentials before any API
replica starts. Re-running is safe; no credentials are printed.
"""
from __future__ import annotations
import os
import time
import boto3
from botocore.client import Config
from botocore.exceptions import BotoCoreError, ClientError
def _read(env_key: str) -> str:
with open(os.environ[env_key], encoding="utf-8") as handle:
return handle.read().strip()
def main() -> None:
endpoint = os.environ["S3_ENDPOINT"]
region = os.environ.get("S3_REGION", "us-east-1")
bucket = os.environ["S3_BUCKET"]
client = boto3.client(
"s3",
endpoint_url=endpoint,
region_name=region,
aws_access_key_id=_read("S3_ROOT_ACCESS_KEY_ID_FILE"),
aws_secret_access_key=_read("S3_ROOT_SECRET_ACCESS_KEY_FILE"),
config=Config(
connect_timeout=2,
read_timeout=5,
retries={"max_attempts": 1},
s3={"addressing_style": "path"},
),
)
last: Exception | None = None
for attempt in range(1, 31):
try:
try:
client.head_bucket(Bucket=bucket)
print(f"bucket {bucket} already present")
except ClientError:
client.create_bucket(Bucket=bucket)
print(f"bucket {bucket} created")
return
except (ClientError, BotoCoreError) as exc:
last = exc
print(f"bucket bootstrap not ready (attempt {attempt}/30)")
time.sleep(2)
raise SystemExit(f"bucket bootstrap failed: {last}")
if __name__ == "__main__":
main()
+37
View File
@@ -0,0 +1,37 @@
"""Prove the bucket is private *outside* the API authorization path.
Lists one object with the limited credentials, then requests the same object
over plain HTTP with NO credentials. A private bucket must answer AccessDenied
(403) or 404, never 200 with the bytes.
docker compose exec -T api python -m src.s3_private_check
"""
from __future__ import annotations
import urllib.error
import urllib.request
from . import storage
from .config import settings
def main() -> None:
keys = [item["Key"] for item in storage.list_keys("")]
if not keys:
raise SystemExit("no objects to check; upload an attachment first")
key = keys[0]
url = f"{settings.s3_endpoint.rstrip('/')}/{settings.s3_bucket}/{key}"
try:
with urllib.request.urlopen(url, timeout=5) as response:
status = response.status
size = len(response.read())
except urllib.error.HTTPError as error:
print(f"anonymous GET -> {error.code} (denied)")
assert error.code in {403, 404}, f"unexpected status {error.code}"
print("PASS: private bucket denies anonymous access")
return
raise SystemExit(f"FAIL: anonymous GET returned {status} with {size} bytes")
if __name__ == "__main__":
main()
+33
View File
@@ -0,0 +1,33 @@
"""Password KDF (Argon2id) and opaque bearer-token helpers."""
from __future__ import annotations
import hashlib
import secrets
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerifyMismatchError, VerificationError
# Argon2id is the default of argon2-cffi's PasswordHasher. Parameters are kept
# modest so the local test suite stays fast while still using a real KDF.
_hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
def hash_password(password: str) -> str:
return _hasher.hash(password)
def verify_password(password_hash: str, password: str) -> bool:
try:
return _hasher.verify(password_hash, password)
except (VerifyMismatchError, VerificationError, InvalidHashError):
return False
def new_token() -> str:
"""Opaque bearer token with >= 256 bits of entropy."""
return secrets.token_urlsafe(32)
def token_hash(token: str) -> str:
"""Sessions are identified by a SHA-256 of the token, never the token itself."""
return hashlib.sha256(token.encode("utf-8")).hexdigest()
+87
View File
@@ -0,0 +1,87 @@
"""Synthetic data seeder for EXPLAIN evidence (never used by the public smoke).
Runs INSIDE the api container so it can reach PostgreSQL over the compose
network:
docker compose exec -T api python -m src.seed --messages 10000
It writes a small number of users/chats and one "hot" chat with many messages,
then prints the hot chat id so the operator can run EXPLAIN against it.
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import uuid
from .db import pool
def _now() -> dt.datetime:
return dt.datetime.now(dt.timezone.utc)
def main() -> None:
parser = argparse.ArgumentParser(description="Seed synthetic chat history")
parser.add_argument("--users", type=int, default=10)
parser.add_argument("--chats", type=int, default=3)
parser.add_argument("--messages", type=int, default=10000)
args = parser.parse_args()
user_ids = [str(uuid.uuid4()) for _ in range(args.users)]
chat_ids = [str(uuid.uuid4()) for _ in range(args.chats)]
base = _now()
with pool().connection() as conn:
with conn.cursor() as cur:
cur.executemany(
"""
insert into users (id, username, display_name, password_hash, created_at)
values (%s, %s, %s, %s, %s)
""",
[
(uid, f"seed_{i}_{uuid.uuid4().hex[:6]}", f"Seed {i}", "seed-not-loginable", base)
for i, uid in enumerate(user_ids)
],
)
cur.executemany(
"insert into chats (id, title, created_at) values (%s, %s, %s)",
[(cid, f"Seed chat {i}", base) for i, cid in enumerate(chat_ids)],
)
cur.executemany(
"insert into chat_members (chat_id, user_id) values (%s, %s)",
[(cid, uid) for cid in chat_ids for uid in user_ids],
)
hot_chat = chat_ids[0]
per_chat = max(1, args.messages // len(chat_ids))
rows = []
total = 0
for chat_index, cid in enumerate(chat_ids):
count = args.messages - total if chat_index == len(chat_ids) - 1 else per_chat
count = max(0, count)
for _ in range(count):
rows.append(
(
str(uuid.uuid4()),
cid,
user_ids[0],
"synthetic history message",
base,
)
)
total += count
cur.executemany(
"""
insert into messages (id, chat_id, sender_id, text, created_at)
values (%s, %s, %s, %s, %s)
""",
rows,
)
print(json.dumps({"hot_chat_id": hot_chat, "messages": args.messages, "chats": chat_ids}))
if __name__ == "__main__":
main()
+203
View File
@@ -0,0 +1,203 @@
"""Sessions: PostgreSQL is the source of truth, Valkey is a shared session cache.
Design (lab3):
* ``sessions`` rows in PostgreSQL decide validity (``expires_at > now()``) and
survive restarts with the named volume.
* Valkey caches ``session:{token_hash} -> {user_id, expires_at}`` for at most
``SESSION_CACHE_TTL_SECONDS``. The TTL is a *bounded staleness* guarantee:
even if an invalidation is lost, a cached positive cannot outlive this
window.
* Logout deletes the PostgreSQL row and, in the same transaction, enqueues the
token hash in ``cache_invalidations``. A background drainer (see
``src/invalidation.py``) removes the Valkey key and then the queue row, so
a logout that happened while Valkey was down is still honoured as soon as
the cache returns — instead of being resurrected from a stale entry.
* If Valkey is unreachable every cache operation degrades to PostgreSQL. The
API keeps serving; the cache is never trusted as the source of truth.
Cache calls on the request path are bounded by a hard timeout and a small
circuit breaker (a stopped Valkey can make Docker DNS block for seconds). The
drainer bypasses the breaker on purpose: invalidation must not be skipped.
"""
from __future__ import annotations
import concurrent.futures
import datetime as dt
import json
import logging
import time
from typing import Optional, Tuple
import redis
from redis.backoff import NoBackoff
from redis.retry import Retry
from . import repositories as repo
from . import security
from .config import settings
logger = logging.getLogger("messenger.sessions")
_client: Optional[redis.Redis] = None
_client_disabled = False
_executor = concurrent.futures.ThreadPoolExecutor(max_workers=2, thread_name_prefix="cache")
_OP_TIMEOUT = 0.5
_BREAKER_SECONDS = 5.0
_breaker_until = 0.0
def _cache() -> Optional[redis.Redis]:
global _client, _client_disabled
if not settings.cache_enabled or _client_disabled:
return None
if _client is None:
try:
_client = redis.Redis.from_url(
settings.cache_url,
socket_timeout=0.2,
socket_connect_timeout=0.2,
health_check_interval=0,
retry_on_timeout=False,
retry=Retry(NoBackoff(), 0),
)
except (ValueError, redis.RedisError):
logger.warning("valkey client init failed; cache disabled")
_client_disabled = True
return None
return _client
def _guard(fn, *args):
"""Run a request-path cache operation with a deadline and a small breaker."""
global _breaker_until
if time.monotonic() < _breaker_until:
return None
try:
return _executor.submit(fn, *args).result(timeout=_OP_TIMEOUT)
except (concurrent.futures.TimeoutError, redis.RedisError, OSError):
_breaker_until = time.monotonic() + _BREAKER_SECONDS
logger.warning("valkey unavailable; cache bypassed for %.0fs", _BREAKER_SECONDS)
return None
def _session_key(token_hash: str) -> str:
return f"session:{token_hash}"
def _cache_get(key: str) -> Optional[str]:
client = _cache()
if client is None:
return None
value = _guard(lambda: client.get(key))
if value is None:
return None
return value.decode("utf-8") if isinstance(value, bytes) else str(value)
def _cache_set(key: str, value: str, ttl_seconds: float) -> None:
client = _cache()
if client is None:
return
_guard(lambda: client.set(key, value, ex=max(1, int(ttl_seconds))))
def _cache_delete(key: str) -> None:
client = _cache()
if client is None:
return
_guard(lambda: client.delete(key))
def _encode_session(user_id: str, expires_at: dt.datetime) -> str:
return json.dumps(
{"user_id": user_id, "expires_at": repo.rfc3339(expires_at)},
separators=(",", ":"),
)
def _decode_session(raw: str) -> Optional[Tuple[str, dt.datetime]]:
try:
data = json.loads(raw)
user_id = str(data["user_id"])
value = str(data["expires_at"])
if value.endswith("Z"):
value = value[:-1] + "+00:00"
expires_at = dt.datetime.fromisoformat(value)
return user_id, expires_at
except (ValueError, KeyError, TypeError):
return None
def _cache_ttl(remaining: float) -> int:
return max(1, int(min(remaining, settings.session_cache_ttl_seconds)))
def create(conn, user_id: str) -> Tuple[str, dt.datetime]:
token = security.new_token()
hashed = security.token_hash(token)
expires_at = repo.utcnow() + dt.timedelta(seconds=settings.session_ttl_seconds)
repo.insert_session(conn, hashed, user_id, expires_at)
# The cache is populated by the first successful resolve() (read-through),
# so it can only ever contain sessions already committed to PostgreSQL.
return token, expires_at
def resolve(conn, token: str) -> Optional[str]:
"""Return the session's user id, or None if the token is not valid.
A cache hit is accepted only while the stored expiry is in the future and
only for the bounded cache TTL. A miss or any cache failure falls back to
the authoritative PostgreSQL row.
"""
hashed = security.token_hash(token)
cached = _cache_get(_session_key(hashed))
if cached is not None:
decoded = _decode_session(cached)
if decoded is not None and decoded[1] > repo.utcnow():
return decoded[0]
row = repo.get_valid_session(conn, hashed)
if row is None:
# Remove any legacy/stale entry; revocation is already authoritative.
_cache_delete(_session_key(hashed))
return None
user_id = str(row["user_id"])
remaining = (row["expires_at"] - repo.utcnow()).total_seconds()
if remaining > 0:
_cache_set(
_session_key(hashed),
_encode_session(user_id, row["expires_at"]),
_cache_ttl(remaining),
)
return user_id
def revoke(conn, token: str) -> None:
hashed = security.token_hash(token)
repo.delete_session(conn, hashed)
if settings.cache_enabled:
# Durable obligation, committed together with the session delete.
repo.enqueue_cache_invalidation(conn, hashed)
# Best effort: the drainer retries if this fails (e.g. Valkey is down).
_cache_delete(_session_key(hashed))
def invalidate_session_key(token_hash: str) -> bool:
"""Delete one cache key for the drainer; True means it is safe to dequeue.
Deliberately bypasses the circuit breaker: a transient cache outage must not
cause pending invalidations to be dropped. Socket timeouts still bound the
call so the worker cannot block forever.
"""
client = _cache()
if client is None:
# Cache deliberately disabled -> nothing to invalidate. A client that
# failed to initialise keeps its rows so a restart can retry.
return not settings.cache_enabled
try:
client.delete(_session_key(token_hash))
return True
except (redis.RedisError, OSError):
return False
+19
View File
@@ -0,0 +1,19 @@
"""Process-wide lifecycle flags.
``shutting_down`` is raised from the SIGTERM/SIGINT handler before Uvicorn
stops accepting connections, so ``/health/ready`` reports ``503`` and the
balancer drains this replica instead of sending it new work.
"""
from __future__ import annotations
import threading
_shutting_down = threading.Event()
def begin_shutdown() -> None:
_shutting_down.set()
def is_shutting_down() -> bool:
return _shutting_down.is_set()
+119
View File
@@ -0,0 +1,119 @@
"""S3-compatible object storage client (SeaweedFS).
Only the API process uses these limited credentials; the bucket is private and
object keys are generated by the server, never derived from ``filename``. All
connectivity failures become a bounded ``503 unavailable``.
Every operation runs under a hard deadline with a small circuit breaker: a
stopped S3 container can make Docker DNS itself block for seconds, and without
this guard a storage outage would stall request handling instead of failing fast.
"""
from __future__ import annotations
import concurrent.futures
import logging
import time
from typing import BinaryIO, Iterable, Optional
import boto3
from botocore.client import Config
from botocore.exceptions import BotoCoreError, ClientError
from .config import settings
from .errors import ApiError
logger = logging.getLogger("messenger.storage")
_client = None
_BOTO_CONFIG = Config(
connect_timeout=2,
read_timeout=10,
retries={"max_attempts": 1, "mode": "standard"},
s3={"addressing_style": "path"},
)
_executor = concurrent.futures.ThreadPoolExecutor(max_workers=4, thread_name_prefix="s3")
_BREAKER_SECONDS = 5.0
_breaker_until = 0.0
def _unavailable() -> ApiError:
return ApiError(503, "unavailable", "Хранилище недоступно")
def client():
global _client
if _client is None:
_client = boto3.client(
"s3",
endpoint_url=settings.s3_endpoint,
region_name=settings.s3_region,
aws_access_key_id=settings.s3_access_key_id or None,
aws_secret_access_key=settings.s3_secret_access_key or None,
config=_BOTO_CONFIG,
)
return _client
def _run(fn, timeout: float):
"""Run an S3 call under a deadline and a shared breaker."""
global _breaker_until
if time.monotonic() < _breaker_until:
raise _unavailable()
try:
return _executor.submit(fn).result(timeout=timeout)
except (concurrent.futures.TimeoutError, BotoCoreError, ClientError, OSError):
_breaker_until = time.monotonic() + _BREAKER_SECONDS
logger.warning("S3 unavailable; operations fail fast for %.0fs", _BREAKER_SECONDS)
raise _unavailable()
def ready() -> bool:
"""Return True if the bucket is reachable (used by /health/ready)."""
try:
_run(lambda: client().head_bucket(Bucket=settings.s3_bucket), timeout=1.5)
return True
except ApiError:
return False
def put_object(key: str, fileobj: BinaryIO, content_type: str) -> None:
_run(
lambda: client().upload_fileobj(
fileobj, settings.s3_bucket, key, ExtraArgs={"ContentType": content_type}
),
timeout=30,
)
def open_object(key: str):
"""Return the boto3 get_object response (caller streams and closes Body)."""
def _get():
try:
return client().get_object(Bucket=settings.s3_bucket, Key=key)
except ClientError as exc:
if exc.response.get("Error", {}).get("Code") in {"NoSuchKey", "404"}:
raise ApiError(404, "not_found", "Объект не найден")
raise
return _run(_get, timeout=10)
def delete_object(key: str) -> bool:
try:
_run(lambda: client().delete_object(Bucket=settings.s3_bucket, Key=key), timeout=10)
return True
except ApiError:
return False
def list_keys(prefix: str = "") -> Iterable[dict]:
paginator = client().get_paginator("list_objects_v2")
try:
for page in paginator.paginate(Bucket=settings.s3_bucket, Prefix=prefix):
for item in page.get("Contents", []):
yield item
except (BotoCoreError, ClientError):
raise _unavailable()