Реализовать лабораторную 3 на оценку 5 (трек 1)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
# Messenger API for MTUSI high-load course, laboratory 2.
|
||||
@@ -0,0 +1,80 @@
|
||||
"""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.
|
||||
"""
|
||||
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
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
database_url: str
|
||||
cache_url: 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
|
||||
instance_id: str
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
# The container hostname is stable for the life of the process and unique
|
||||
# per API replica. Lab7 replaces this with a random public alias.
|
||||
instance_id = os.environ.get("INSTANCE_ID") or socket.gethostname()
|
||||
return Settings(
|
||||
database_url=_value("DATABASE_URL", "DATABASE_URL_FILE"),
|
||||
cache_url=_value("CACHE_URL", "CACHE_URL_FILE"),
|
||||
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),
|
||||
instance_id=instance_id,
|
||||
)
|
||||
|
||||
|
||||
settings = load_settings()
|
||||
@@ -0,0 +1,158 @@
|
||||
"""PostgreSQL access: bounded pool, timeouts, and versioned migrations.
|
||||
|
||||
The API does not race migrations on every replica. Compose runs the one-shot
|
||||
``migrate`` service first; API processes only verify that the expected schema is
|
||||
present. ``python -m app.migrate`` is also the local/manual entry point.
|
||||
"""
|
||||
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()
|
||||
_migrated = 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 _migration_files() -> list[Path]:
|
||||
return sorted(MIGRATIONS_DIR.glob("*.sql"))
|
||||
|
||||
|
||||
def apply_migrations() -> None:
|
||||
"""Apply every migration exactly once.
|
||||
|
||||
A session-level advisory lock serialises concurrent migration runners.
|
||||
Each migration and its schema_migrations row share one transaction.
|
||||
"""
|
||||
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 _migration_files():
|
||||
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,)
|
||||
)
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))
|
||||
|
||||
|
||||
def schema_is_current() -> bool:
|
||||
"""True when every migration shipped in this image is already applied."""
|
||||
expected = {path.stem for path in _migration_files()}
|
||||
if not expected:
|
||||
return False
|
||||
try:
|
||||
with pool().connection(timeout=1.0) as conn:
|
||||
row = conn.execute(
|
||||
"SELECT to_regclass('public.schema_migrations') IS NOT NULL AS present"
|
||||
).fetchone()
|
||||
if not row or not row["present"]:
|
||||
return False
|
||||
applied = {
|
||||
item["version"]
|
||||
for item in conn.execute("SELECT version FROM schema_migrations").fetchall()
|
||||
}
|
||||
return expected.issubset(applied)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def start_background_initialisation() -> None:
|
||||
"""Open the pool and verify schema without making /health/live depend on DB."""
|
||||
global _started
|
||||
with _start_lock:
|
||||
if _started:
|
||||
return
|
||||
_started = True
|
||||
|
||||
def run() -> None:
|
||||
backoff = 0.5
|
||||
opened = False
|
||||
while True:
|
||||
try:
|
||||
if not opened:
|
||||
pool().open(wait=True, timeout=5)
|
||||
opened = True
|
||||
if not schema_is_current():
|
||||
log.warning("database schema is not current; waiting for migrate service")
|
||||
raise RuntimeError("schema is not current")
|
||||
_migrated.set()
|
||||
log.info("database pool is ready and schema is current")
|
||||
return
|
||||
except Exception as exc: # startup is retried; request path stays bounded
|
||||
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_migrated() -> bool:
|
||||
return _migrated.is_set()
|
||||
|
||||
|
||||
def close_pool() -> None:
|
||||
global _pool
|
||||
with _pool_lock:
|
||||
if _pool is not None:
|
||||
_pool.close()
|
||||
_pool = None
|
||||
@@ -0,0 +1,36 @@
|
||||
"""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 unavailable(message: str = "Сервис временно недоступен") -> ApiError:
|
||||
return ApiError(503, "unavailable", message)
|
||||
+578
@@ -0,0 +1,578 @@
|
||||
"""HTTP API for laboratory 3 (balanced replicas + shared idempotency)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
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 psycopg.types.json import Jsonb
|
||||
|
||||
from . import db, sessions
|
||||
from .config import settings
|
||||
from .errors import ApiError, bad_request, conflict, not_found, unauthorized, unavailable
|
||||
from .validation import (
|
||||
cursor_time,
|
||||
decode_cursor,
|
||||
display_name,
|
||||
encode_cursor,
|
||||
exact_keys,
|
||||
idempotency_key,
|
||||
json_object,
|
||||
limit_arg,
|
||||
message_text,
|
||||
non_blank,
|
||||
password,
|
||||
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__)
|
||||
app.config["MAX_CONTENT_LENGTH"] = settings.max_body_bytes
|
||||
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)
|
||||
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"]),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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.is_migrated():
|
||||
raise unavailable("База данных ещё не готова")
|
||||
try:
|
||||
with db.pool().connection(timeout=1.0) as conn:
|
||||
conn.execute("SELECT 1")
|
||||
except Exception as exc:
|
||||
raise unavailable("База данных недоступна") from exc
|
||||
sessions.ping()
|
||||
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
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _message_request_hash(text: str) -> str:
|
||||
"""Canonical body fingerprint; key order and absent optional arrays are equal."""
|
||||
canonical = json.dumps(
|
||||
{"text": text, "attachment_ids": []},
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _idempotent_message(actor: dict, chat_id: uuid.UUID, text: str, key: str) -> Response:
|
||||
"""Create one message and remember its exact response atomically.
|
||||
|
||||
The unique constraint on (user_id, method, path, key) is the cross-replica
|
||||
lock. A concurrent request with the same key waits for the first
|
||||
transaction; after commit it reads the stored 201 response. If the first
|
||||
transaction rolls back, the waiter inserts instead. A transient 5xx never
|
||||
leaves a completed key without its message because both writes commit
|
||||
together.
|
||||
"""
|
||||
digest = _message_request_hash(text)
|
||||
path = request.path
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(
|
||||
seconds=settings.idempotency_ttl_seconds
|
||||
)
|
||||
|
||||
for _attempt in range(2):
|
||||
with db.pool().connection() as conn:
|
||||
inserted = conn.execute(
|
||||
"""
|
||||
INSERT INTO idempotency_keys
|
||||
(user_id, method, path, key, request_hash, expires_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
ON CONFLICT (user_id, method, path, key) DO NOTHING
|
||||
RETURNING id
|
||||
""",
|
||||
(actor["id"], "POST", path, key, digest, expires_at),
|
||||
).fetchone()
|
||||
if inserted is not None:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
""",
|
||||
(uuid.uuid4(), chat_id, actor["id"], text),
|
||||
).fetchone()
|
||||
payload = message_json(row)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE idempotency_keys
|
||||
SET status_code = 201, response_body = %s, message_id = %s
|
||||
WHERE id = %s
|
||||
""",
|
||||
(Jsonb(payload), row["id"], inserted["id"]),
|
||||
)
|
||||
return _json(payload, 201)
|
||||
|
||||
existing = conn.execute(
|
||||
"""
|
||||
SELECT request_hash, status_code, response_body, expires_at
|
||||
FROM idempotency_keys
|
||||
WHERE user_id = %s AND method = %s AND path = %s AND key = %s
|
||||
FOR UPDATE
|
||||
""",
|
||||
(actor["id"], "POST", path, key),
|
||||
).fetchone()
|
||||
|
||||
if existing is None:
|
||||
# The conflicting row was removed by an expiry cleanup between
|
||||
# our insert and select; retry the insert once.
|
||||
continue
|
||||
if existing["expires_at"] <= datetime.now(timezone.utc):
|
||||
conn.execute(
|
||||
"""
|
||||
DELETE FROM idempotency_keys
|
||||
WHERE user_id = %s AND method = %s AND path = %s AND key = %s
|
||||
""",
|
||||
(actor["id"], "POST", path, key),
|
||||
)
|
||||
continue
|
||||
if existing["request_hash"] != digest:
|
||||
raise conflict("Idempotency-Key уже использован с другим телом")
|
||||
if existing["status_code"] is None or existing["response_body"] is None:
|
||||
raise conflict("Запрос с этим Idempotency-Key ещё выполняется")
|
||||
return _json(existing["response_body"], existing["status_code"])
|
||||
|
||||
raise unavailable("Не удалось согласовать повтор запроса")
|
||||
|
||||
|
||||
@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"])
|
||||
key = idempotency_key(request.headers.get("Idempotency-Key"))
|
||||
body = json_object(request, settings.max_body_bytes)
|
||||
exact_keys(body, ("text",))
|
||||
text = message_text(body["text"])
|
||||
return _idempotent_message(actor, parsed_chat_id, text, key)
|
||||
|
||||
|
||||
@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 id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = %s {predicate}
|
||||
ORDER BY created_at, 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})
|
||||
@@ -0,0 +1,33 @@
|
||||
"""One-shot migration entry point used by Compose.
|
||||
|
||||
Run after PostgreSQL is healthy and before API replicas start:
|
||||
|
||||
python -m app.migrate
|
||||
"""
|
||||
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")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
db.pool().open(wait=True, timeout=60)
|
||||
db.apply_migrations()
|
||||
if not db.schema_is_current():
|
||||
raise RuntimeError("schema verification failed after migration")
|
||||
except Exception as exc:
|
||||
logging.getLogger("messenger.migrate").error("migration failed: %s", type(exc).__name__)
|
||||
return 1
|
||||
finally:
|
||||
db.close_pool()
|
||||
logging.getLogger("messenger.migrate").info("migrations applied and verified")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+101
@@ -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))
|
||||
@@ -0,0 +1,152 @@
|
||||
"""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_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
|
||||
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) -> str:
|
||||
return non_blank(value, "text", 1, 4000)
|
||||
|
||||
|
||||
def idempotency_key(value: str | None) -> str:
|
||||
if value is None:
|
||||
raise bad_request("Заголовок Idempotency-Key обязателен")
|
||||
if IDEMPOTENCY_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)
|
||||
Reference in New Issue
Block a user