Реализовать лабораторную 2 на оценку 4
PostgreSQL как источник истины, непрозрачные сессии в Redis с TTL и AOF, миграции под advisory lock, пул и таймауты, проверки гонки/отката/отказов и отчёт с evidence.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
# Messenger API for MTUSI high-load course, laboratory 2.
|
||||
@@ -0,0 +1,72 @@
|
||||
"""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
|
||||
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
|
||||
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
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
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),
|
||||
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),
|
||||
)
|
||||
|
||||
|
||||
settings = load_settings()
|
||||
@@ -0,0 +1,118 @@
|
||||
"""PostgreSQL access: bounded pool, timeouts, and versioned migrations."""
|
||||
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-lab2",
|
||||
"options": options,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def pool() -> ConnectionPool:
|
||||
global _pool
|
||||
with _pool_lock:
|
||||
if _pool is None:
|
||||
_pool = _create_pool()
|
||||
return _pool
|
||||
|
||||
|
||||
def apply_migrations() -> None:
|
||||
"""Apply every migration exactly once.
|
||||
|
||||
A session-level advisory lock serialises concurrent API workers/restarts.
|
||||
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 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,)
|
||||
)
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))
|
||||
|
||||
|
||||
def start_background_initialisation() -> None:
|
||||
"""Open the pool and migrate without making /health/live depend on PostgreSQL."""
|
||||
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
|
||||
apply_migrations()
|
||||
_migrated.set()
|
||||
log.info("database pool is ready and schema is migrated")
|
||||
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()
|
||||
@@ -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)
|
||||
+491
@@ -0,0 +1,491 @@
|
||||
"""HTTP API for laboratory 2 (PostgreSQL + opaque sessions in Redis)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, 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 . 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,
|
||||
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["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
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@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",))
|
||||
text = message_text(body["text"])
|
||||
with db.pool().connection() as conn:
|
||||
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(), parsed_chat_id, actor["id"], text),
|
||||
).fetchone()
|
||||
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 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})
|
||||
+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,143 @@
|
||||
"""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]+$")
|
||||
|
||||
|
||||
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 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