Реализовать лабораторную 4 на оценку 5

Добавить приватное S3-хранилище, вложения, presigned upload, reconciler и доказательства.
This commit is contained in:
Чиняева
2026-11-07 01:37:21 +03:00
parent ec540a1a72
commit f39ae06ef3
69 changed files with 5254 additions and 31 deletions
+1
View File
@@ -0,0 +1 @@
# Messenger API for MTUSI high-load course, laboratory 2.
+135
View File
@@ -0,0 +1,135 @@
"""Attachment upload validation and serialisation.
Design rules for laboratory 4:
* raw bytes are streamed to an ephemeral file, never accumulated in RAM;
* the declared MIME type must match the format sniffed from the bytes;
* the pixel budget is checked before the image is decoded;
* a small semaphore bounds how many full decodes run at once per API replica;
* the object key is generated by the server and never contains the filename.
"""
from __future__ import annotations
import hashlib
import os
import tempfile
import threading
import uuid
from datetime import datetime, timezone
from PIL import Image, UnidentifiedImageError
from .config import settings
from .errors import ApiError, payload_too_large, unsupported_media_type
# Pillow's own bomb guard is a second line of defence; the explicit product
# check below is the contract limit and runs before verify()/load().
Image.MAX_IMAGE_PIXELS = settings.max_image_pixels
_decoders = threading.BoundedSemaphore(settings.max_decode_concurrency)
ALLOWED = {"PNG": "image/png", "JPEG": "image/jpeg"}
def format_time(value: datetime) -> str:
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def object_key(chat_id: uuid.UUID, attachment_id: uuid.UUID) -> str:
# Random UUIDs make the key unguessable; the client filename is display
# metadata only. A stable prefix helps the reconciler and operators.
return f"chats/{chat_id}/{attachment_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": format_time(row["created_at"]),
"updated_at": format_time(row["updated_at"]),
}
def read_to_temp(stream) -> tuple[str, int, str]:
"""Stream the request body to a bounded temporary file.
The caller owns the returned path and must delete it in a finally block.
"""
digest = hashlib.sha256()
total = 0
handle = tempfile.NamedTemporaryFile(
mode="wb", prefix="upload-", suffix=".bin", dir=settings.upload_temp_dir, delete=False
)
path = handle.name
try:
while True:
try:
chunk = stream.read(64 * 1024)
except Exception as error:
# Flask raises RequestEntityTooLarge when MAX_CONTENT_LENGTH is
# exceeded on a chunked request.
if getattr(error, "code", None) == 413:
raise payload_too_large() from error
raise
if not chunk:
break
total += len(chunk)
if total > settings.max_upload_bytes:
raise payload_too_large("Файл больше 10 MiB")
digest.update(chunk)
handle.write(chunk)
finally:
handle.close()
if total == 0:
os.unlink(path)
raise unsupported_media_type("Пустой файл")
return path, total, digest.hexdigest()
def validate_image(path: str, declared_content_type: str) -> None:
"""Sniff the real format, enforce the pixel budget, then fully decode."""
try:
with Image.open(path) as image:
actual = ALLOWED.get(image.format or "")
if actual is None:
raise unsupported_media_type("Поддерживаются только PNG и JPEG")
if actual != declared_content_type:
raise unsupported_media_type("Content-Type не совпадает с содержимым")
width, height = image.size
if width < 1 or height < 1:
raise unsupported_media_type("Некорректные размеры изображения")
if width * height > settings.max_image_pixels:
raise payload_too_large("Слишком много пикселей")
# verify() parses the container and checks CRCs without keeping the
# decoded bitmap; load() below is the bounded full decode.
image.verify()
except ApiError:
raise
except (UnidentifiedImageError, OSError, ValueError, SyntaxError) as error:
raise unsupported_media_type("Повреждённое изображение") from error
with _decoders:
try:
with Image.open(path) as image:
image.load()
except (UnidentifiedImageError, OSError, ValueError, SyntaxError) as error:
raise unsupported_media_type("Повреждённое изображение") from error
def cleanup(path: str | None) -> None:
if not path:
return
try:
os.unlink(path)
except FileNotFoundError:
return
except OSError:
return
+134
View File
@@ -0,0 +1,134 @@
"""Runtime configuration.
The application never embeds credentials. Local Compose passes environment
variables from an ignored .env file; *_FILE variants are accepted as well so a
container platform can mount secrets without copying them into the image.
Laboratory 4 adds S3 settings. The API uses a restricted application identity;
only the one-shot bootstrap service receives the administrative identity.
"""
from __future__ import annotations
import os
import socket
from dataclasses import dataclass
from pathlib import Path
def _value(name: str, fallback_name: str | None = None, default: str | None = None) -> str:
raw = os.environ.get(name)
if raw:
return raw
if fallback_name:
filename = os.environ.get(fallback_name)
if filename:
path = Path(filename)
text = path.read_text(encoding="utf-8").strip()
if text:
return text
if default is not None:
return default
raise RuntimeError(f"missing required configuration: {name}")
def _positive_int(name: str, default: int) -> int:
raw = os.environ.get(name, str(default))
try:
value = int(raw)
except ValueError as exc:
raise RuntimeError(f"{name} must be an integer") from exc
if value < 1:
raise RuntimeError(f"{name} must be positive")
return value
def _positive_float(name: str, default: float) -> float:
raw = os.environ.get(name, str(default))
try:
value = float(raw)
except ValueError as exc:
raise RuntimeError(f"{name} must be a number") from exc
if value <= 0:
raise RuntimeError(f"{name} must be positive")
return value
def _instance_id() -> str:
"""Stable public alias of one API process/container.
Containers use their hostname (the short container id) by default. An
explicit INSTANCE_ID is useful for non-container deployments or for a
randomly generated lab7 alias. The value never contains host IP data.
"""
value = (os.environ.get("INSTANCE_ID") or socket.gethostname()).strip()
if not value or len(value) > 128 or any(not (c.isalnum() or c in "-._:") for c in value):
raise RuntimeError("INSTANCE_ID must be 1..128 safe characters")
return value
@dataclass(frozen=True)
class Settings:
database_url: str
cache_url: str
instance_id: str
session_ttl_seconds: int
idempotency_ttl_seconds: int
db_pool_min: int
db_pool_max: int
db_pool_acquire_timeout: float
db_connect_timeout: int
db_statement_timeout_ms: int
redis_connect_timeout: float
redis_socket_timeout: float
max_body_bytes: int
max_upload_bytes: int
max_image_pixels: int
max_decode_concurrency: int
upload_temp_dir: str
s3_endpoint: str
s3_public_endpoint: str
s3_region: str
s3_bucket: str
s3_access_key_id: str
s3_secret_access_key: str
s3_connect_timeout: float
s3_read_timeout: float
presign_ttl_seconds: int
presign_grace_seconds: int
orphan_grace_seconds: int
def load_settings() -> Settings:
return Settings(
database_url=_value("DATABASE_URL", "DATABASE_URL_FILE"),
cache_url=_value("CACHE_URL", "CACHE_URL_FILE"),
instance_id=_instance_id(),
session_ttl_seconds=_positive_int("SESSION_TTL_SECONDS", 3600),
idempotency_ttl_seconds=_positive_int("IDEMPOTENCY_TTL_SECONDS", 86400),
db_pool_min=_positive_int("DB_POOL_MIN", 1),
db_pool_max=_positive_int("DB_POOL_MAX", 10),
db_pool_acquire_timeout=float(os.environ.get("DB_POOL_ACQUIRE_TIMEOUT_SECONDS", "3")),
db_connect_timeout=_positive_int("DB_CONNECT_TIMEOUT_SECONDS", 3),
db_statement_timeout_ms=_positive_int("DB_STATEMENT_TIMEOUT_MS", 5000),
redis_connect_timeout=float(os.environ.get("REDIS_CONNECT_TIMEOUT_SECONDS", "2")),
redis_socket_timeout=float(os.environ.get("REDIS_SOCKET_TIMEOUT_SECONDS", "2")),
max_body_bytes=_positive_int("MAX_BODY_BYTES", 1024 * 1024),
max_upload_bytes=_positive_int("MAX_UPLOAD_BYTES", 10 * 1024 * 1024),
max_image_pixels=_positive_int("MAX_IMAGE_PIXELS", 40_000_000),
max_decode_concurrency=_positive_int("MAX_DECODE_CONCURRENCY", 1),
upload_temp_dir=os.environ.get("UPLOAD_TEMP_DIR", "/tmp"),
s3_endpoint=_value("S3_ENDPOINT", "S3_ENDPOINT_FILE", "http://seaweedfs:8333"),
s3_public_endpoint=_value("S3_PUBLIC_ENDPOINT", "S3_PUBLIC_ENDPOINT_FILE", "http://localhost:9000"),
s3_region=_value("S3_REGION", default="us-east-1"),
s3_bucket=_value("S3_BUCKET", default="messenger-attachments"),
s3_access_key_id=_value("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE"),
s3_secret_access_key=_value("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE"),
s3_connect_timeout=_positive_float("S3_CONNECT_TIMEOUT_SECONDS", 3.0),
s3_read_timeout=_positive_float("S3_READ_TIMEOUT_SECONDS", 30.0),
presign_ttl_seconds=_positive_int("PRESIGN_TTL_SECONDS", 300),
presign_grace_seconds=_positive_int("PRESIGN_GRACE_SECONDS", 3600),
orphan_grace_seconds=_positive_int("ORPHAN_GRACE_SECONDS", 86400),
)
settings = load_settings()
+174
View File
@@ -0,0 +1,174 @@
"""PostgreSQL access: bounded pool, timeouts, and versioned migrations.
Laboratory 3 separates schema management from request serving. The one-shot
``migrate`` Compose service calls :func:`apply_migrations`; API replicas only
open their pool and wait until the newest migration is visible. That prevents
N replicas from racing each other on DDL during a deploy.
"""
from __future__ import annotations
import logging
import threading
import time
from pathlib import Path
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from .config import settings
log = logging.getLogger("messenger.db")
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations"
LOCK_ID = 0x4D545553 # stable application-wide advisory lock
_pool: ConnectionPool | None = None
_pool_lock = threading.Lock()
_ready = threading.Event()
_started = False
_start_lock = threading.Lock()
def _create_pool() -> ConnectionPool:
options = (
f"-c statement_timeout={settings.db_statement_timeout_ms} "
"-c idle_in_transaction_session_timeout=10000 "
"-c lock_timeout=3000"
)
return ConnectionPool(
conninfo=settings.database_url,
min_size=settings.db_pool_min,
max_size=settings.db_pool_max,
timeout=settings.db_pool_acquire_timeout,
open=False,
kwargs={
"row_factory": dict_row,
"connect_timeout": settings.db_connect_timeout,
"application_name": "mtusi-messenger-lab3",
"options": options,
},
)
def pool() -> ConnectionPool:
global _pool
with _pool_lock:
if _pool is None:
_pool = _create_pool()
return _pool
def required_version() -> str:
"""Newest migration shipped in this image; readiness waits for it."""
versions = sorted(path.stem for path in MIGRATIONS_DIR.glob("*.sql"))
if not versions:
raise RuntimeError("no migrations found")
return versions[-1]
def open_pool(timeout: float = 60.0) -> None:
"""Open the pool with bounded retries; used by migrate and API startup."""
deadline = time.monotonic() + timeout
backoff = 0.5
while True:
try:
pool().open(wait=True, timeout=min(5.0, max(0.5, deadline - time.monotonic())))
return
except Exception as exc:
if time.monotonic() >= deadline:
raise
log.warning("database is not reachable yet: %s", type(exc).__name__)
time.sleep(backoff)
backoff = min(backoff * 2, 5.0)
def apply_migrations() -> list[str]:
"""Apply every migration exactly once.
A session-level advisory lock serialises the one-shot migrate service and
any explicit operator run. Each migration and its schema_migrations row
share one transaction, so a failed DDL statement leaves no version row.
"""
applied_now: list[str] = []
with pool().connection() as conn:
conn.execute("SELECT pg_advisory_lock(%s)", (LOCK_ID,))
try:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT clock_timestamp()
)
"""
)
applied = {
row["version"]
for row in conn.execute("SELECT version FROM schema_migrations").fetchall()
}
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
version = path.stem
if version in applied:
continue
log.info("applying migration %s", version)
conn.execute(path.read_text(encoding="utf-8"))
conn.execute(
"INSERT INTO schema_migrations(version) VALUES (%s)", (version,)
)
applied_now.append(version)
finally:
conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))
return applied_now
def schema_is_current() -> bool:
"""Cheap readiness probe: the newest migration is committed and visible."""
if _pool is None:
return False
try:
with pool().connection(timeout=1.0) as conn:
row = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(required_version(),),
).fetchone()
return row is not None
except Exception:
return False
def start_background_initialisation() -> None:
"""Open the pool and wait for the one-shot migrator, without blocking the
liveness endpoint. The API never performs DDL itself."""
global _started
with _start_lock:
if _started:
return
_started = True
def run() -> None:
backoff = 0.5
opened = False
while True:
try:
if not opened:
open_pool(timeout=5.0)
opened = True
if schema_is_current():
_ready.set()
log.info("database pool is ready; schema %s is current", required_version())
return
log.warning("waiting for migrate service: schema %s is not ready", required_version())
except Exception as exc:
log.warning("database initialisation is not ready: %s", type(exc).__name__)
time.sleep(backoff)
backoff = min(backoff * 2, 5.0)
threading.Thread(target=run, name="db-init", daemon=True).start()
def is_ready() -> bool:
return _ready.is_set()
def check_ready() -> bool:
"""Readiness checks the live connection and the migrated schema each time."""
return is_ready() and schema_is_current()
+44
View File
@@ -0,0 +1,44 @@
"""Typed public errors. Internal details never cross the HTTP boundary."""
from __future__ import annotations
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str, headers: dict[str, str] | None = None):
super().__init__(message)
self.status = status
self.code = code
self.message = message
self.headers = headers or {}
def bad_request(message: str = "Некорректный запрос") -> ApiError:
return ApiError(400, "invalid_request", message)
def unauthorized(*, basic: bool = False) -> ApiError:
challenge = (
'Basic realm="messenger", charset="UTF-8"'
if basic
else 'Bearer realm="messenger"'
)
return ApiError(401, "unauthorized", "Требуется аутентификация", {"WWW-Authenticate": challenge})
def not_found(message: str = "Объект не найден") -> ApiError:
return ApiError(404, "not_found", message)
def conflict(message: str = "Конфликт") -> ApiError:
return ApiError(409, "conflict", message)
def payload_too_large(message: str = "Файл слишком велик") -> ApiError:
return ApiError(413, "payload_too_large", message)
def unsupported_media_type(message: str = "Неподдерживаемый тип файла") -> ApiError:
return ApiError(415, "unsupported_media_type", message)
def unavailable(message: str = "Сервис временно недоступен") -> ApiError:
return ApiError(503, "unavailable", message)
+179
View File
@@ -0,0 +1,179 @@
"""Shared, transactional idempotency for message creation.
The unique scope is (user, method, path, key). The idempotency row, the
message row and its attachment links are written in one PostgreSQL
transaction, so a crash or rollback cannot leave a committed key without its
message. Concurrent retries through different API replicas converge on the
same primary-key row: the loser of the INSERT ... ON CONFLICT waits for the
winner to commit and then reads the original message.
Only the canonical body is hashed, so JSON key order and an omitted
``attachment_ids`` equal to ``[]`` are the same request.
"""
from __future__ import annotations
import hashlib
import json
import secrets
import uuid
from datetime import datetime
from . import db
from .config import settings
from .errors import conflict, not_found
def fingerprint(text: str, attachment_ids: list[str]) -> str:
payload = {
"text": text,
"attachment_ids": sorted(attachment_ids),
}
canonical = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def _cleanup_expired(conn) -> None:
"""Best-effort maintenance; never on the critical path of every request."""
if secrets.randbelow(100) != 0:
return
conn.execute(
"""
DELETE FROM idempotency_keys
WHERE ctid IN (
SELECT ctid FROM idempotency_keys
WHERE expires_at <= clock_timestamp()
LIMIT 1000
)
"""
)
def _validate_attachments(conn, chat_id: uuid.UUID, attachment_ids: list[str]) -> None:
if not attachment_ids:
return
parsed = [uuid.UUID(item) for item in attachment_ids]
rows = conn.execute(
"""
SELECT id, chat_id, status
FROM attachments
WHERE id = ANY(%s)
FOR SHARE
""",
(parsed,),
).fetchall()
if len(rows) != len(parsed):
raise not_found("Вложение не найдено")
by_id = {str(row["id"]): row for row in rows}
for attachment_id in attachment_ids:
row = by_id.get(attachment_id)
if row is None or row["chat_id"] != chat_id:
raise not_found("Вложение не найдено в этом чате")
if row["status"] != "ready":
raise conflict("Вложение ещё не готово")
def _message_with_attachments(conn, message_id) -> dict:
row = conn.execute(
"""
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
ARRAY(
SELECT ma.attachment_id
FROM message_attachments ma
WHERE ma.message_id = m.id
ORDER BY ma.position
) AS attachment_ids
FROM messages m
WHERE m.id = %s
""",
(message_id,),
).fetchone()
if row is None:
raise conflict("Результат ещё не готов, повторите запрос")
return row
def create_message(
*,
chat_id: uuid.UUID,
actor_id: uuid.UUID,
path: str,
key: str,
text: str,
attachment_ids: list[str],
) -> dict:
"""Return the original or newly created message row, atomically."""
request_hash = fingerprint(text, attachment_ids)
message_id = uuid.uuid4()
with db.pool().connection() as conn:
with conn.transaction():
_validate_attachments(conn, chat_id, attachment_ids)
# An expired key may be reused: remove it inside the same scope.
conn.execute(
"""
DELETE FROM idempotency_keys
WHERE user_id = %s AND method = 'POST' AND path = %s AND key = %s
AND expires_at <= clock_timestamp()
""",
(actor_id, path, key),
)
_cleanup_expired(conn)
inserted = conn.execute(
"""
INSERT INTO idempotency_keys
(user_id, method, path, key, request_hash, message_id, expires_at)
VALUES
(%s, 'POST', %s, %s, %s, %s,
clock_timestamp() + (%s * interval '1 second'))
ON CONFLICT (user_id, method, path, key) DO NOTHING
RETURNING message_id
""",
(
actor_id,
path,
key,
request_hash,
message_id,
settings.idempotency_ttl_seconds,
),
).fetchone()
if inserted is not None:
conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES (%s, %s, %s, %s)
""",
(inserted["message_id"], chat_id, actor_id, text),
)
if attachment_ids:
with conn.cursor() as cursor:
cursor.executemany(
"""
INSERT INTO message_attachments
(message_id, attachment_id, position)
VALUES (%s, %s, %s)
""",
[
(inserted["message_id"], uuid.UUID(item), position)
for position, item in enumerate(attachment_ids)
],
)
return _message_with_attachments(conn, inserted["message_id"])
existing = conn.execute(
"""
SELECT request_hash, message_id, expires_at
FROM idempotency_keys
WHERE user_id = %s AND method = 'POST' AND path = %s AND key = %s
""",
(actor_id, path, key),
).fetchone()
if existing is None:
# The row disappeared between the conflict and this read (only
# possible with a concurrent expiry cleanup). 409 asks the
# client to retry rather than creating an ambiguous duplicate.
raise conflict("Повторите запрос: ключ идемпотентности истёк")
if existing["request_hash"] != request_hash:
raise conflict("Idempotency-Key уже использован с другим сообщением")
return _message_with_attachments(conn, existing["message_id"])
+746
View File
@@ -0,0 +1,746 @@
"""HTTP API for laboratory 3 (PostgreSQL + Redis sessions behind a LB)."""
from __future__ import annotations
import json
import logging
import os
import time
import uuid
from datetime import datetime, timedelta, timezone
from urllib.parse import quote
import psycopg
import psycopg_pool
import redis
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerifyMismatchError
from flask import Flask, Response, g, request
from . import attachments as attachment_store
from . import db, idempotency, s3, sessions
from .config import settings
from .errors import (
ApiError,
bad_request,
conflict,
not_found,
payload_too_large,
unauthorized,
unavailable,
unsupported_media_type,
)
from .validation import (
byte_size,
cursor_time,
decode_cursor,
display_name,
encode_cursor,
exact_keys,
filename,
idempotency_key,
image_content_type,
json_object,
limit_arg,
message_text,
non_blank,
password,
sha256_hex,
username,
uuid_list,
uuid_value,
)
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
log = logging.getLogger("messenger.api")
app = Flask(__name__)
# Uploads stream through the handler; the Flask ceiling is deliberately just
# above the contract limit so a single oversized request is rejected early.
app.config["MAX_CONTENT_LENGTH"] = settings.max_upload_bytes + 64 * 1024
hasher = PasswordHasher()
# ---------------------------------------------------------------------------
# Response helpers and middleware
# ---------------------------------------------------------------------------
def _json(payload: object, status: int = 200, headers: dict[str, str] | None = None) -> Response:
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
response = Response(body, status=status, mimetype="application/json")
for key, value in (headers or {}).items():
response.headers[key] = value
return response
def _error_response(error: ApiError, request_id: str) -> Response:
return _json(
{
"error": {
"code": error.code,
"message": error.message,
"request_id": request_id,
}
},
error.status,
error.headers,
)
@app.before_request
def _request_context() -> None:
g.request_id = uuid.uuid4().hex
g.started_at = time.monotonic()
db.start_background_initialisation()
@app.after_request
def _response_headers(response: Response) -> Response:
response.headers["X-Request-Id"] = g.get("request_id", uuid.uuid4().hex)
response.headers["X-Instance-Id"] = settings.instance_id
response.headers["Cache-Control"] = "no-store"
return response
@app.errorhandler(ApiError)
def _handle_api_error(error: ApiError) -> Response:
return _error_response(error, g.get("request_id", uuid.uuid4().hex))
@app.errorhandler(413)
def _handle_too_large(_error: object) -> Response:
return _error_response(
ApiError(413, "payload_too_large", "Тело запроса слишком велико"),
g.get("request_id", uuid.uuid4().hex),
)
@app.errorhandler(404)
def _handle_not_found(_error: object) -> Response:
return _error_response(not_found(), g.get("request_id", uuid.uuid4().hex))
@app.errorhandler(405)
def _handle_method(_error: object) -> Response:
return _error_response(bad_request("Метод не поддерживается"), g.get("request_id", uuid.uuid4().hex))
@app.errorhandler(Exception)
def _handle_unexpected(error: Exception) -> Response:
request_id = g.get("request_id", uuid.uuid4().hex)
if isinstance(error, (psycopg.OperationalError, psycopg_pool.PoolTimeout, psycopg_pool.PoolClosed)):
log.warning("database unavailable on %s %s: %s", request.method, request.path, type(error).__name__)
return _error_response(unavailable("База данных недоступна"), request_id)
if isinstance(error, redis.RedisError):
log.warning("session store unavailable on %s %s: %s", request.method, request.path, type(error).__name__)
return _error_response(unavailable("Хранилище сессий недоступно"), request_id)
if isinstance(error, s3.S3Unavailable):
log.warning("object store unavailable on %s %s", request.method, request.path)
return _error_response(unavailable("Объектное хранилище недоступно"), request_id)
log.exception("unhandled error on %s %s", request.method, request.path)
return _error_response(
ApiError(500, "internal_error", "Внутренняя ошибка сервера"), request_id
)
# ---------------------------------------------------------------------------
# Serialisation
# ---------------------------------------------------------------------------
def format_time(value: datetime) -> str:
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def user_json(row: dict) -> dict:
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": format_time(row["created_at"]),
}
def chat_json(row: dict) -> dict:
member_ids = sorted(str(item) for item in (row.get("member_ids") or []))
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": member_ids,
"created_at": format_time(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": format_time(row["created_at"]),
"attachment_ids": [str(item) for item in (row.get("attachment_ids") or [])],
}
# ---------------------------------------------------------------------------
# Authentication
# ---------------------------------------------------------------------------
def _bearer_token() -> str:
header = request.headers.get("Authorization", "")
parts = header.split(None, 1)
if len(parts) != 2 or parts[0].lower() != "bearer" or not parts[1].strip():
raise unauthorized()
return parts[1].strip()
def current_user() -> dict:
cached = g.get("current_user")
if cached is not None:
return cached
token = _bearer_token()
user_id, token_digest = sessions.resolve(token)
if not user_id:
raise unauthorized()
try:
parsed = uuid.UUID(user_id)
except ValueError as exc:
raise unauthorized() from exc
with db.pool().connection() as conn:
row = conn.execute(
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
(parsed,),
).fetchone()
if row is None:
sessions.revoke(token_digest)
raise unauthorized()
g.current_user = row
g.session_token_digest = token_digest
return row
def _basic_credentials() -> tuple[str, str]:
header = request.headers.get("Authorization", "")
parts = header.split(None, 1)
if len(parts) != 2 or parts[0].lower() != "basic":
raise unauthorized(basic=True)
import base64
try:
decoded = base64.b64decode(parts[1].strip(), validate=True).decode("utf-8")
except (ValueError, UnicodeError) as exc:
raise unauthorized(basic=True) from exc
name, separator, secret = decoded.partition(":")
if not separator or not name or not secret:
raise unauthorized(basic=True)
if len(name) > 32 or any(ord(char) > 127 for char in name):
raise unauthorized(basic=True)
return name, secret
def _authenticate_basic() -> dict:
name, secret = _basic_credentials()
with db.pool().connection() as conn:
row = conn.execute(
"SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = %s",
(name,),
).fetchone()
if row is None:
raise unauthorized(basic=True)
try:
hasher.verify(row["password_hash"], secret)
except (VerifyMismatchError, InvalidHashError):
raise unauthorized(basic=True)
return row
# ---------------------------------------------------------------------------
# Health
# ---------------------------------------------------------------------------
@app.get("/health/live")
def health_live() -> Response:
return _json({"status": "ok"})
@app.get("/health/ready")
def health_ready() -> Response:
if not db.check_ready():
raise unavailable("База данных ещё не готова")
sessions.ping()
if not s3.check_ready():
raise unavailable("Объектное хранилище ещё не готово")
return _json({"status": "ok"})
# ---------------------------------------------------------------------------
# Users and sessions
# ---------------------------------------------------------------------------
@app.post("/api/v1/users")
def register_user() -> Response:
body = json_object(request, settings.max_body_bytes)
exact_keys(body, ("username", "display_name", "password"))
name = username(body["username"])
shown_name = display_name(body["display_name"])
secret = password(body["password"])
user_id = uuid.uuid4()
try:
with db.pool().connection() as conn:
row = conn.execute(
"""
INSERT INTO users (id, username, display_name, password_hash)
VALUES (%s, %s, %s, %s)
RETURNING id, username, display_name, created_at
""",
(user_id, name, shown_name, hasher.hash(secret)),
).fetchone()
except psycopg.errors.UniqueViolation as exc:
raise conflict("Username уже занят") from exc
return _json(user_json(row), 201)
@app.post("/api/v1/auth/sessions")
def create_session() -> Response:
row = _authenticate_basic()
token, expires_at = sessions.create(str(row["id"]))
return _json(
{
"token": token,
"token_type": "Bearer",
"expires_at": format_time(expires_at),
"user": user_json(row),
},
201,
)
@app.delete("/api/v1/auth/sessions/current")
def revoke_session() -> Response:
current_user() # authentication must happen before revocation
sessions.revoke(g.session_token_digest)
return Response(status=204)
@app.get("/api/v1/users/me")
def current_user_endpoint() -> Response:
return _json(user_json(current_user()))
# ---------------------------------------------------------------------------
# Chats
# ---------------------------------------------------------------------------
def _require_chat_member(chat_id: uuid.UUID, user_id: uuid.UUID) -> None:
with db.pool().connection() as conn:
row = conn.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, user_id),
).fetchone()
if row is None:
raise not_found()
@app.post("/api/v1/chats")
def create_chat() -> Response:
actor = current_user()
body = json_object(request, settings.max_body_bytes)
exact_keys(body, ("title", "member_ids"))
title = non_blank(body["title"], "title", 1, 100)
member_ids = uuid_list(body["member_ids"], "member_ids")
actor_id = str(actor["id"])
if actor_id not in member_ids:
raise bad_request("Создатель должен входить в member_ids")
member_uuids = [uuid.UUID(item) for item in member_ids]
chat_id = uuid.uuid4()
with db.pool().connection() as conn:
existing = conn.execute(
"SELECT id FROM users WHERE id = ANY(%s)", (member_uuids,)
).fetchall()
if len(existing) != len(member_uuids):
raise bad_request("Указан неизвестный участник")
row = conn.execute(
"INSERT INTO chats (id, title) VALUES (%s, %s) RETURNING id, title, created_at",
(chat_id, title),
).fetchone()
with conn.cursor() as cursor:
cursor.executemany(
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
[(chat_id, member) for member in member_uuids],
)
payload = dict(row)
payload["member_ids"] = member_uuids
return _json(chat_json(payload), 201)
@app.get("/api/v1/chats")
def list_chats() -> Response:
actor = current_user()
limit = limit_arg(request.args.get("limit"))
cursor = decode_cursor(request.args.get("cursor"))
parameters: list[object] = [actor["id"]]
predicate = ""
if cursor is not None:
if cursor.get("kind") != "chats" or cursor.get("user_id") != str(actor["id"]):
raise bad_request("Некорректный cursor")
try:
cursor_created = cursor_time(cursor.get("created_at"))
cursor_id = uuid_value(cursor.get("id"), "cursor")
except ApiError:
raise bad_request("Некорректный cursor")
predicate = "AND (c.created_at, c.id) > (%s, %s)"
parameters.extend([cursor_created, cursor_id])
parameters.append(limit + 1)
query = f"""
SELECT c.id, c.title, c.created_at,
ARRAY(
SELECT cm.user_id FROM chat_members cm
WHERE cm.chat_id = c.id ORDER BY cm.user_id
) AS member_ids
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s
WHERE TRUE {predicate}
ORDER BY c.created_at, c.id
LIMIT %s
"""
with db.pool().connection() as conn:
rows = conn.execute(query, tuple(parameters)).fetchall()
page = rows[:limit]
next_cursor = None
if len(rows) > limit and page:
last = page[-1]
next_cursor = encode_cursor(
{
"v": 1,
"kind": "chats",
"user_id": str(actor["id"]),
"created_at": format_time(last["created_at"]),
"id": str(last["id"]),
}
)
return _json({"items": [chat_json(row) for row in page], "next_cursor": next_cursor})
@app.get("/api/v1/chats/<chat_id>")
def get_chat(chat_id: str) -> Response:
actor = current_user()
parsed_chat_id = uuid_value(chat_id, "chat_id")
with db.pool().connection() as conn:
row = conn.execute(
"""
SELECT c.id, c.title, c.created_at,
ARRAY(
SELECT cm.user_id FROM chat_members cm
WHERE cm.chat_id = c.id ORDER BY cm.user_id
) AS member_ids
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s
WHERE c.id = %s
""",
(actor["id"], parsed_chat_id),
).fetchone()
if row is None:
raise not_found()
return _json(chat_json(row))
# ---------------------------------------------------------------------------
# Messages
# ---------------------------------------------------------------------------
@app.post("/api/v1/chats/<chat_id>/messages")
def create_message(chat_id: str) -> Response:
actor = current_user()
parsed_chat_id = uuid_value(chat_id, "chat_id")
_require_chat_member(parsed_chat_id, actor["id"])
body = json_object(request, settings.max_body_bytes)
exact_keys(body, ("text",), ("attachment_ids",))
attachments = uuid_list(body.get("attachment_ids", []), "attachment_ids", 0, 10)
text = message_text(body["text"], allow_empty=bool(attachments))
key = idempotency_key(request.headers.get("Idempotency-Key"))
row = idempotency.create_message(
chat_id=parsed_chat_id,
actor_id=actor["id"],
path=request.path,
key=key,
text=text,
attachment_ids=attachments,
)
return _json(message_json(row), 201)
@app.get("/api/v1/chats/<chat_id>/messages")
def list_messages(chat_id: str) -> Response:
actor = current_user()
parsed_chat_id = uuid_value(chat_id, "chat_id")
_require_chat_member(parsed_chat_id, actor["id"])
limit = limit_arg(request.args.get("limit"))
cursor = decode_cursor(request.args.get("cursor"))
parameters: list[object] = [parsed_chat_id]
predicate = ""
if cursor is not None:
if cursor.get("kind") != "messages" or cursor.get("chat_id") != str(parsed_chat_id):
raise bad_request("Некорректный cursor")
try:
cursor_created = cursor_time(cursor.get("created_at"))
cursor_id = uuid_value(cursor.get("id"), "cursor")
except ApiError:
raise bad_request("Некорректный cursor")
predicate = "AND (created_at, id) > (%s, %s)"
parameters.extend([cursor_created, cursor_id])
parameters.append(limit + 1)
query = f"""
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
ARRAY(
SELECT ma.attachment_id
FROM message_attachments ma
WHERE ma.message_id = m.id
ORDER BY ma.position
) AS attachment_ids
FROM messages m
WHERE m.chat_id = %s {predicate}
ORDER BY m.created_at, m.id
LIMIT %s
"""
with db.pool().connection() as conn:
rows = conn.execute(query, tuple(parameters)).fetchall()
page = rows[:limit]
next_cursor = None
if len(rows) > limit and page:
last = page[-1]
next_cursor = encode_cursor(
{
"v": 1,
"kind": "messages",
"chat_id": str(parsed_chat_id),
"created_at": format_time(last["created_at"]),
"id": str(last["id"]),
}
)
return _json({"items": [message_json(row) for row in page], "next_cursor": next_cursor})
# ---------------------------------------------------------------------------
# Attachments (lab4)
# ---------------------------------------------------------------------------
def _attachment_for_member(attachment_id: uuid.UUID, actor_id: uuid.UUID) -> dict:
with db.pool().connection() as conn:
row = conn.execute(
"""
SELECT a.*
FROM attachments a
JOIN chat_members cm
ON cm.chat_id = a.chat_id AND cm.user_id = %s
WHERE a.id = %s
""",
(actor_id, attachment_id),
).fetchone()
if row is None:
raise not_found()
return row
def _attachment_owned(attachment_id: uuid.UUID, actor_id: uuid.UUID) -> dict | None:
with db.pool().connection() as conn:
return conn.execute(
"""
SELECT a.*
FROM attachments a
JOIN chat_members cm
ON cm.chat_id = a.chat_id AND cm.user_id = %s
WHERE a.id = %s AND a.owner_id = %s
""",
(actor_id, attachment_id, actor_id),
).fetchone()
@app.post("/api/v1/chats/<chat_id>/attachments")
def upload_attachment(chat_id: str) -> Response:
"""Synchronous proxy upload: 201 only after S3 PUT and PostgreSQL COMMIT."""
actor = current_user()
parsed_chat_id = uuid_value(chat_id, "chat_id")
_require_chat_member(parsed_chat_id, actor["id"])
name = filename(request.args.get("filename"))
declared = image_content_type(request.mimetype)
if request.content_length is not None and request.content_length > settings.max_upload_bytes:
raise payload_too_large("Файл больше 10 MiB")
path = None
try:
path, size, digest = attachment_store.read_to_temp(request.stream)
attachment_store.validate_image(path, declared)
attachment_id = uuid.uuid4()
key = attachment_store.object_key(parsed_chat_id, attachment_id)
with open(path, "rb") as body:
s3.put_file(key, body, declared, size, digest)
try:
with db.pool().connection() as conn:
row = conn.execute(
"""
INSERT INTO attachments
(id, chat_id, owner_id, filename, content_type,
size_bytes, sha256, object_key, status)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'ready')
RETURNING *
""",
(
attachment_id,
parsed_chat_id,
actor["id"],
name,
declared,
size,
digest,
key,
),
).fetchone()
except Exception as error:
# Compensate: an S3 object without metadata must not survive.
s3.delete(key)
if isinstance(error, psycopg.Error):
raise unavailable("Не удалось сохранить метаданные вложения") from error
raise
return _json(attachment_store.attachment_json(row), 201)
finally:
attachment_store.cleanup(path)
@app.post("/api/v1/chats/<chat_id>/attachments/presign")
def presign_attachment(chat_id: str) -> Response:
"""Extension: short-lived direct upload URL; the proxy endpoint stays mandatory."""
actor = current_user()
parsed_chat_id = uuid_value(chat_id, "chat_id")
_require_chat_member(parsed_chat_id, actor["id"])
body = json_object(request, settings.max_body_bytes)
exact_keys(body, ("filename", "content_type", "size_bytes", "sha256"))
name = filename(body["filename"])
declared = image_content_type(body["content_type"])
size = byte_size(body["size_bytes"], settings.max_upload_bytes)
digest = sha256_hex(body["sha256"])
attachment_id = uuid.uuid4()
key = attachment_store.object_key(parsed_chat_id, attachment_id)
upload_url = s3.presign_put(key, declared, digest, settings.presign_ttl_seconds)
expires_at = datetime.now(timezone.utc) + timedelta(seconds=settings.presign_ttl_seconds)
try:
with db.pool().connection() as conn:
conn.execute(
"""
INSERT INTO attachments
(id, chat_id, owner_id, filename, content_type,
size_bytes, sha256, object_key, status, presign_expires_at)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'pending', %s)
""",
(
attachment_id,
parsed_chat_id,
actor["id"],
name,
declared,
size,
digest,
key,
expires_at,
),
)
except psycopg.Error as error:
raise unavailable("Не удалось сохранить метаданные вложения") from error
return _json(
{
"attachment_id": str(attachment_id),
"upload_url": upload_url,
"method": "PUT",
"headers": {"Content-Type": declared, "x-amz-meta-sha256": digest},
"expires_at": format_time(expires_at),
},
201,
)
@app.post("/api/v1/attachments/<attachment_id>/complete")
def complete_attachment(attachment_id: str) -> Response:
"""Extension: verify a direct upload and make the attachment ready."""
actor = current_user()
parsed_id = uuid_value(attachment_id, "attachment_id")
row = _attachment_owned(parsed_id, actor["id"])
if row is None:
raise not_found()
body = json_object(request, settings.max_body_bytes)
exact_keys(body, ("sha256", "size_bytes"))
digest = sha256_hex(body["sha256"])
size = byte_size(body["size_bytes"], settings.max_upload_bytes)
if row["status"] == "ready":
if row["sha256"] == digest and int(row["size_bytes"]) == size:
return _json(attachment_store.attachment_json(row))
raise conflict("Вложение уже завершено с другими параметрами")
if row["status"] != "pending":
raise conflict("Вложение не может быть завершено")
expires_at = row.get("presign_expires_at")
if expires_at is not None and expires_at <= datetime.now(timezone.utc):
raise conflict("Срок действия загрузки истёк")
head = s3.head(row["object_key"])
if head is None:
raise conflict("Объект ещё не загружен")
if int(head.get("ContentLength", -1)) != size:
raise bad_request("Размер загруженного объекта не совпадает")
actual_size, actual_digest = s3.stream_sha256(row["object_key"])
if actual_size != size or actual_digest != digest:
# Wrong bytes are never promoted; delete them so a retry starts clean.
s3.delete(row["object_key"])
raise bad_request("Контрольная сумма загруженного объекта не совпадает")
with db.pool().connection() as conn:
updated = conn.execute(
"""
UPDATE attachments
SET status = 'ready', error_code = NULL, updated_at = clock_timestamp()
WHERE id = %s AND status = 'pending'
RETURNING *
""",
(parsed_id,),
).fetchone()
if updated is None:
raise conflict("Вложение уже обработано")
return _json(attachment_store.attachment_json(updated))
@app.get("/api/v1/attachments/<attachment_id>")
def get_attachment(attachment_id: str) -> Response:
actor = current_user()
parsed_id = uuid_value(attachment_id, "attachment_id")
row = _attachment_for_member(parsed_id, actor["id"])
return _json(attachment_store.attachment_json(row))
@app.get("/api/v1/attachments/<attachment_id>/content")
def download_attachment(attachment_id: str) -> Response:
actor = current_user()
parsed_id = uuid_value(attachment_id, "attachment_id")
variant = request.args.get("variant", "original")
if variant != "original":
raise bad_request("variant должен быть original")
row = _attachment_for_member(parsed_id, actor["id"])
if row["status"] != "ready":
raise conflict("Вложение ещё не готово")
try:
body = s3.open_stream(row["object_key"])
except s3.S3Missing as error:
raise unavailable("Оригинал вложения недоступен") from error
def chunks():
try:
for chunk in body.iter_chunks(chunk_size=64 * 1024):
yield chunk
finally:
body.close()
response = Response(chunks(), mimetype=row["content_type"])
response.headers["Content-Length"] = str(row["size_bytes"])
response.headers["Content-Disposition"] = (
"inline; filename*=UTF-8''" + quote(row["filename"], safe="")
)
return response
+37
View File
@@ -0,0 +1,37 @@
"""One-shot schema migrator.
Run as ``python -m app.migrate`` from the dedicated Compose service. It waits
for PostgreSQL, takes the application advisory lock and applies only missing
migration files. Exiting non-zero blocks API replicas via
``depends_on: service_completed_successfully``.
"""
from __future__ import annotations
import logging
import sys
from . import db
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
log = logging.getLogger("messenger.migrate")
def main() -> int:
log.info("waiting for PostgreSQL and applying migrations")
db.open_pool(timeout=60.0)
applied = db.apply_migrations()
if applied:
log.info("applied migrations: %s", ", ".join(applied))
else:
log.info("schema already current at %s", db.required_version())
with db.pool().connection() as conn:
rows = conn.execute(
"SELECT version, applied_at FROM schema_migrations ORDER BY version"
).fetchall()
for row in rows:
log.info("schema version %s applied at %s", row["version"], row["applied_at"].isoformat())
return 0
if __name__ == "__main__":
sys.exit(main())
+136
View File
@@ -0,0 +1,136 @@
"""Safe, repeatable S3/PostgreSQL reconciler (lab4 operational backstop).
What it does
------------
* finds S3 objects with no attachment row ("orphans") and deletes only those
older than a grace period;
* finds pending presigned uploads older than a grace period and removes both
the row and any object, so an interrupted direct upload cannot leak forever;
* reports ready rows whose object is missing and records ``missing_since`` for
operators without deleting user-visible metadata.
``--dry-run`` is the default. ``--apply`` performs the deletions. Re-running
after an interruption is safe: every action is idempotent.
"""
from __future__ import annotations
import argparse
import json
import logging
import sys
from datetime import datetime, timezone
from . import db, s3
from .config import settings
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
log = logging.getLogger("messenger.reconcile")
def _age_seconds(now: datetime, value: datetime | None) -> float | None:
if value is None:
return None
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return (now - value.astimezone(timezone.utc)).total_seconds()
def run(*, apply: bool, orphan_grace: int, pending_grace: int, prefix: str) -> dict:
now = datetime.now(timezone.utc)
db.open_pool(timeout=60.0)
objects = s3.list_objects(prefix)
object_keys = {item["key"] for item in objects}
with db.pool().connection() as conn:
rows = conn.execute(
"SELECT id, object_key, status, created_at, missing_since FROM attachments"
).fetchall()
db_keys = {row["object_key"] for row in rows}
orphans = [item for item in objects if item["key"] not in db_keys]
stale_orphans = []
fresh_orphans = []
for item in orphans:
age = _age_seconds(now, item["last_modified"])
if age is None or age >= orphan_grace:
stale_orphans.append(item)
else:
fresh_orphans.append(item)
stale_pending = [
row
for row in rows
if row["status"] == "pending"
and (_age_seconds(now, row["created_at"]) or 0) >= pending_grace
]
missing = [
row
for row in rows
if row["status"] == "ready" and row["object_key"] not in object_keys
]
deleted_orphans = 0
deleted_pending = 0
marked_missing = 0
if apply:
for item in stale_orphans:
s3.delete(item["key"])
deleted_orphans += 1
for row in stale_pending:
s3.delete(row["object_key"])
with db.pool().connection() as conn:
conn.execute(
"DELETE FROM attachments WHERE id = %s AND status = 'pending'",
(row["id"],),
)
deleted_pending += 1
for row in missing:
if row["missing_since"] is None:
with db.pool().connection() as conn:
conn.execute(
"UPDATE attachments SET missing_since = clock_timestamp() WHERE id = %s",
(row["id"],),
)
marked_missing += 1
return {
"apply": apply,
"grace_seconds": {"orphan": orphan_grace, "pending": pending_grace},
"objects": len(objects),
"metadata_rows": len(rows),
"orphans_total": len(orphans),
"orphans_fresh_kept": len(fresh_orphans),
"orphans_stale_deleted": deleted_orphans if apply else len(stale_orphans),
"stale_pending_deleted": deleted_pending if apply else len(stale_pending),
"missing_objects_reported": len(missing),
"missing_objects_marked": marked_missing,
"sample_orphan_keys": [item["key"] for item in stale_orphans[:5]],
"sample_missing_keys": [row["object_key"] for row in missing[:5]],
}
def main() -> int:
parser = argparse.ArgumentParser(description="Reconcile private S3 objects with attachment metadata")
parser.add_argument("--apply", action="store_true", help="delete stale orphans/pending rows (default: dry-run)")
parser.add_argument("--dry-run", action="store_true", help="explicit dry-run (default)")
parser.add_argument("--orphan-grace-seconds", type=int, default=settings.orphan_grace_seconds)
parser.add_argument("--pending-grace-seconds", type=int, default=settings.presign_grace_seconds)
parser.add_argument("--prefix", default="")
args = parser.parse_args()
apply = args.apply and not args.dry_run
try:
summary = run(
apply=apply,
orphan_grace=max(0, args.orphan_grace_seconds),
pending_grace=max(0, args.pending_grace_seconds),
prefix=args.prefix,
)
except s3.S3Unavailable as error:
log.error("object store is unavailable: %s", type(error).__name__)
return 2
print(json.dumps(summary, ensure_ascii=False, sort_keys=True))
return 0
if __name__ == "__main__":
sys.exit(main())
+230
View File
@@ -0,0 +1,230 @@
"""Thin, bounded S3 client wrapper for the attachment store.
The API identity has only Read/Write/List on the private bucket. The
administrative identity is used exclusively by ``app.s3_bootstrap``.
All boto3 calls are wrapped so that HTTP handlers never leak stack traces or
credentials. Large bodies are streamed; no method here reads a whole object
into memory.
"""
from __future__ import annotations
import hashlib
import threading
from datetime import datetime, timezone
import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
from .config import settings
class S3Unavailable(Exception):
"""The object store is unreachable or rejected a request."""
class S3Missing(Exception):
"""The requested object does not exist."""
_clients: dict[bool, object] = {}
_clients_lock = threading.Lock()
def _make_client(admin: bool = False):
if admin:
access_key = _required_admin("S3_ADMIN_ACCESS_KEY_ID", "S3_ADMIN_ACCESS_KEY_ID_FILE")
secret_key = _required_admin("S3_ADMIN_SECRET_ACCESS_KEY", "S3_ADMIN_SECRET_ACCESS_KEY_FILE")
else:
access_key = settings.s3_access_key_id
secret_key = settings.s3_secret_access_key
config = Config(
signature_version="s3v4",
s3={"addressing_style": "path"},
connect_timeout=settings.s3_connect_timeout,
read_timeout=settings.s3_read_timeout,
retries={"max_attempts": 2, "mode": "standard"},
max_pool_connections=32,
)
return boto3.client(
"s3",
endpoint_url=settings.s3_endpoint,
region_name=settings.s3_region,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
config=config,
)
def _required_admin(name: str, fallback: str) -> str:
import os
from pathlib import Path
raw = os.environ.get(name)
if raw:
return raw
filename = os.environ.get(fallback)
if filename:
return Path(filename).read_text(encoding="utf-8").strip()
raise RuntimeError(f"missing required configuration: {name}")
def client(admin: bool = False):
with _clients_lock:
cached = _clients.get(admin)
if cached is None:
cached = _make_client(admin)
_clients[admin] = cached
return cached
def _error_code(error: ClientError) -> str:
return str(error.response.get("Error", {}).get("Code", ""))
def _missing(error: ClientError) -> bool:
return _error_code(error) in ("404", "NoSuchKey", "NoSuchBucket", "NotFound")
def ensure_bucket() -> None:
"""Idempotent private-bucket bootstrap using the administrative identity."""
s3 = client(admin=True)
try:
s3.head_bucket(Bucket=settings.s3_bucket)
return
except ClientError as error:
if _error_code(error) not in ("404", "NoSuchBucket", "NotFound"):
raise S3Unavailable("S3 head_bucket failed") from error
try:
s3.create_bucket(Bucket=settings.s3_bucket)
except ClientError as error:
code = _error_code(error)
if code not in ("BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
raise S3Unavailable("S3 create_bucket failed") from error
try:
s3.head_bucket(Bucket=settings.s3_bucket)
except (BotoCoreError, ClientError) as error:
raise S3Unavailable("bucket is not usable after bootstrap") from error
def check_ready() -> bool:
try:
client().head_bucket(Bucket=settings.s3_bucket)
return True
except Exception:
return False
def put_file(key: str, fileobj, content_type: str, size: int, sha256: str) -> None:
try:
client().put_object(
Bucket=settings.s3_bucket,
Key=key,
Body=fileobj,
ContentType=content_type,
ContentLength=size,
Metadata={"sha256": sha256},
)
except (BotoCoreError, ClientError) as error:
raise S3Unavailable("S3 upload failed") from error
def delete(key: str) -> None:
try:
client().delete_object(Bucket=settings.s3_bucket, Key=key)
except (BotoCoreError, ClientError):
# Compensation is best effort; the reconciler is the backstop.
return
def head(key: str) -> dict | None:
try:
return client().head_object(Bucket=settings.s3_bucket, Key=key)
except ClientError as error:
if _missing(error):
return None
raise S3Unavailable("S3 head_object failed") from error
except BotoCoreError as error:
raise S3Unavailable("S3 head_object failed") from error
def open_stream(key: str):
"""Return a streaming body. The caller must close it."""
try:
return client().get_object(Bucket=settings.s3_bucket, Key=key)["Body"]
except ClientError as error:
if _missing(error):
raise S3Missing("object is missing") from error
raise S3Unavailable("S3 get_object failed") from error
except BotoCoreError as error:
raise S3Unavailable("S3 get_object failed") from error
def stream_sha256(key: str) -> tuple[int, str]:
"""Read an object once, bounded by 64 KiB chunks, and return size+digest."""
body = open_stream(key)
digest = hashlib.sha256()
total = 0
try:
for chunk in body.iter_chunks(chunk_size=64 * 1024):
total += len(chunk)
digest.update(chunk)
except (BotoCoreError, ClientError, OSError) as error:
raise S3Unavailable("S3 streaming read failed") from error
finally:
body.close()
return total, digest.hexdigest()
def presign_put(key: str, content_type: str, sha256: str, expires: int) -> str:
"""Create a short-lived presigned PUT URL on the public S3 endpoint.
The API's internal endpoint is not reachable from user clients, so the
presigner uses S3_PUBLIC_ENDPOINT. The bucket stays private: the URL is
the only grant and it expires quickly.
"""
presigner = boto3.client(
"s3",
endpoint_url=settings.s3_public_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=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
try:
return presigner.generate_presigned_url(
"put_object",
Params={
"Bucket": settings.s3_bucket,
"Key": key,
"ContentType": content_type,
"Metadata": {"sha256": sha256},
},
ExpiresIn=expires,
)
except (BotoCoreError, ClientError) as error:
raise S3Unavailable("could not sign upload URL") from error
def list_objects(prefix: str = "") -> list[dict]:
"""List bucket objects with key, size and LastModified (UTC)."""
s3 = client()
result: list[dict] = []
try:
paginator = s3.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket=settings.s3_bucket, Prefix=prefix):
for item in page.get("Contents", []):
modified = item.get("LastModified")
if isinstance(modified, datetime) and modified.tzinfo is None:
modified = modified.replace(tzinfo=timezone.utc)
result.append(
{
"key": item["Key"],
"size": int(item.get("Size", 0)),
"last_modified": modified,
}
)
except (BotoCoreError, ClientError) as error:
raise S3Unavailable("S3 list_objects failed") from error
return result
+39
View File
@@ -0,0 +1,39 @@
"""One-shot, idempotent private-bucket bootstrap.
Runs in the dedicated ``s3-init`` Compose service with the administrative S3
identity. The API replicas start only after this service exits successfully,
and they use a different, restricted identity.
"""
from __future__ import annotations
import logging
import sys
import time
from . import s3
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
log = logging.getLogger("messenger.s3-bootstrap")
def main() -> int:
deadline = time.monotonic() + 90.0
backoff = 0.5
while True:
try:
s3.ensure_bucket()
if not s3.check_ready():
raise RuntimeError("restricted identity cannot see the bucket")
log.info("private bucket is present and visible to the API identity")
return 0
except Exception as error:
if time.monotonic() >= deadline:
log.error("bucket bootstrap failed: %s", type(error).__name__)
return 1
log.warning("bucket bootstrap is not ready yet: %s", type(error).__name__)
time.sleep(backoff)
backoff = min(backoff * 2, 5.0)
if __name__ == "__main__":
sys.exit(main())
+101
View File
@@ -0,0 +1,101 @@
"""Opaque bearer sessions stored in Redis/Valkey with a TTL.
PostgreSQL is the source of truth for users/chats/messages. Redis is the
authoritative store for *active sessions*; its append-only file and named
volume make those sessions survive a restart. The raw bearer token is never
stored: only a SHA-256 digest is used as the Redis key.
"""
from __future__ import annotations
import hashlib
import json
import secrets
from datetime import datetime, timedelta, timezone
import redis
from .config import settings
from .errors import unavailable
_client: redis.Redis | None = None
def client() -> redis.Redis:
global _client
if _client is None:
_client = redis.Redis.from_url(
settings.cache_url,
decode_responses=True,
socket_connect_timeout=settings.redis_connect_timeout,
socket_timeout=settings.redis_socket_timeout,
retry_on_timeout=False,
health_check_interval=30,
)
return _client
def digest(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def _key(token_digest: str) -> str:
return "session:" + token_digest
def create(user_id: str) -> tuple[str, datetime]:
token = secrets.token_urlsafe(32) # 256 bits of entropy, opaque to clients
ttl = settings.session_ttl_seconds
expires_at = datetime.now(timezone.utc) + timedelta(seconds=ttl)
payload = json.dumps(
{"user_id": user_id, "expires_at": expires_at.isoformat().replace("+00:00", "Z")},
separators=(",", ":"),
)
try:
client().setex(_key(digest(token)), ttl, payload)
except redis.RedisError as exc:
raise unavailable("Хранилище сессий недоступно") from exc
return token, expires_at
def resolve(token: str) -> tuple[str, str]:
"""Return (user_id, token_digest) or raise a bounded 503 error."""
token_digest = digest(token)
try:
raw = client().get(_key(token_digest))
except redis.RedisError as exc:
raise unavailable("Хранилище сессий недоступно") from exc
if not raw:
return "", token_digest
try:
data = json.loads(raw)
user_id = str(data["user_id"])
expires_at = datetime.fromisoformat(str(data["expires_at"]).replace("Z", "+00:00"))
except (ValueError, KeyError, TypeError):
return "", token_digest
if expires_at <= datetime.now(timezone.utc):
revoke(token_digest)
return "", token_digest
return user_id, token_digest
def revoke(token_digest: str) -> None:
try:
client().delete(_key(token_digest))
except redis.RedisError as exc:
raise unavailable("Хранилище сессий недоступно") from exc
def ping() -> None:
try:
if not client().ping():
raise unavailable("Хранилище сессий недоступно")
except redis.RedisError as exc:
raise unavailable("Хранилище сессий недоступно") from exc
def seconds_left(token_digest: str) -> int:
try:
value = client().ttl(_key(token_digest))
except redis.RedisError:
return 0
return max(0, int(value))
+194
View File
@@ -0,0 +1,194 @@
"""Strict parsing shared by HTTP handlers.
The contract requires rejection of extra JSON fields, wrong types and
whitespace-only required strings. Validation happens before any SQL.
"""
from __future__ import annotations
import base64
import binascii
import json
import re
import uuid
from datetime import datetime, timezone
from flask import Request
from .errors import ApiError, bad_request
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
INTEGER_RE = re.compile(r"^[0-9]+$")
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
SHA256_RE = re.compile(r"^[a-f0-9]{64}$")
def json_object(request: Request, max_bytes: int) -> dict:
if request.mimetype != "application/json":
raise bad_request("Ожидается application/json")
raw = request.get_data(cache=False)
if not raw:
raise bad_request("Тело запроса обязательно")
if len(raw) > max_bytes:
raise ApiError(413, "payload_too_large", "Тело запроса слишком велико")
try:
value = json.loads(raw)
except (ValueError, UnicodeError) as exc:
raise bad_request("Некорректный JSON") from exc
if not isinstance(value, dict):
raise bad_request("Ожидается JSON-объект")
return value
def exact_keys(value: dict, required: tuple[str, ...], optional: tuple[str, ...] = ()) -> None:
allowed = set(required) | set(optional)
if not set(required).issubset(value) or set(value) - allowed:
raise bad_request("Неверный набор полей")
def text_field(value: object, name: str, minimum: int, maximum: int) -> str:
if not isinstance(value, str):
raise bad_request(f"Поле {name} должно быть строкой")
if not (minimum <= len(value) <= maximum):
raise bad_request(f"Поле {name} имеет недопустимую длину")
return value
def non_blank(value: object, name: str, minimum: int, maximum: int) -> str:
result = text_field(value, name, minimum, maximum)
if not result.strip():
raise bad_request(f"Поле {name} не должно быть пустым")
return result
def username(value: object) -> str:
result = text_field(value, "username", 3, 32)
if USERNAME_RE.fullmatch(result) is None:
raise bad_request("Недопустимый username")
return result
def display_name(value: object) -> str:
return non_blank(value, "display_name", 1, 100)
def password(value: object) -> str:
result = text_field(value, "password", 12, 128)
return result
def message_text(value: object, allow_empty: bool = False) -> str:
if not isinstance(value, str):
raise bad_request("Поле text должно быть строкой")
if len(value) > 4000:
raise bad_request("Поле text имеет недопустимую длину")
if not allow_empty and not value.strip():
raise bad_request("Поле text не должно быть пустым")
return value
def filename(value: object) -> str:
"""Display-only filename; it never becomes an object key.
The contract forbids path separators, NUL and control characters. The
limit is measured in Unicode code points (Python's len on str).
"""
if not isinstance(value, str):
raise bad_request("Параметр filename обязателен")
if not (1 <= len(value) <= 255):
raise bad_request("filename имеет недопустимую длину")
if value in (".", ".."):
raise bad_request("filename недопустим")
for char in value:
code = ord(char)
if char in "/\\" or code == 0 or code < 0x20 or code == 0x7F:
raise bad_request("filename содержит недопустимые символы")
return value
def image_content_type(value: object) -> str:
if not isinstance(value, str) or value not in ("image/png", "image/jpeg"):
raise ApiError(415, "unsupported_media_type", "Ожидается PNG или JPEG")
return value
def sha256_hex(value: object) -> str:
if not isinstance(value, str) or SHA256_RE.fullmatch(value) is None:
raise bad_request("sha256 должен быть lowercase hex SHA-256")
return value
def byte_size(value: object, maximum: int) -> int:
if not isinstance(value, int) or isinstance(value, bool) or not (1 <= value <= maximum):
raise bad_request("size_bytes вне допустимого диапазона")
return value
def idempotency_key(value: object) -> str:
if not isinstance(value, str) or IDEMPOTENCY_KEY_RE.fullmatch(value) is None:
raise bad_request("Некорректный Idempotency-Key")
return value
def uuid_list(value: object, name: str, minimum: int = 1, maximum: int = 100) -> list[str]:
if not isinstance(value, list):
raise bad_request(f"Поле {name} должно быть массивом")
if not (minimum <= len(value) <= maximum):
raise bad_request(f"Поле {name} имеет недопустимую длину")
parsed: list[str] = []
for item in value:
parsed.append(str(uuid_value(item, name)))
if len(set(parsed)) != len(parsed):
raise bad_request(f"Поле {name} содержит дубликаты")
return parsed
def uuid_value(value: object, name: str = "id") -> uuid.UUID:
if not isinstance(value, str):
raise bad_request(f"Поле {name} должно быть UUID")
try:
return uuid.UUID(value)
except (ValueError, AttributeError) as exc:
raise bad_request(f"Поле {name} должно быть UUID") from exc
def limit_arg(raw: str | None, default: int = 50) -> int:
if raw is None:
return default
if INTEGER_RE.fullmatch(raw) is None:
raise bad_request("limit должен быть целым числом")
value = int(raw)
if not (1 <= value <= 100):
raise bad_request("limit должен быть в диапазоне 1..100")
return value
def encode_cursor(payload: dict) -> str:
raw = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def decode_cursor(raw: str | None) -> dict | None:
if raw is None:
return None
if not raw or len(raw) > 4096:
raise bad_request("Некорректный cursor")
padded = raw + "=" * (-len(raw) % 4)
try:
data = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")))
except (ValueError, UnicodeError, AttributeError, binascii.Error) as exc:
raise bad_request("Некорректный cursor") from exc
if not isinstance(data, dict):
raise bad_request("Некорректный cursor")
return data
def cursor_time(value: object) -> datetime:
if not isinstance(value, str):
raise bad_request("Некорректный cursor")
try:
result = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError as exc:
raise bad_request("Некорректный cursor") from exc
if result.tzinfo is None:
raise bad_request("Некорректный cursor")
return result.astimezone(timezone.utc)