ЛР 2: PostgreSQL, Bearer-сессии и кэш сессий в Valkey (на 4)
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
- Перенесён минимум lab1; переход 1 → 2: password при регистрации, Basic только на POST /auth/sessions, Bearer вместо X-User-Id, logout. - PostgreSQL — источник истины: users, chats, chat_members, messages, sessions; миграции с PK/FK/UNIQUE/CHECK и индексами, атомарное создание чата, scrypt для паролей, SHA-256 токенов в БД. - Valkey — кэш проверенных сессий с TTL, tombstone при logout, обход кэша и окно недоверия при отказе. - Ограниченные пулы и таймауты PostgreSQL/Valkey, 503 при отказе БД. - compose.yaml с Docker secrets и именованным томом, restart hook, собственные тесты, EXPLAIN на 110 тыс. сообщений, замер пользы кэша, заполненный REPORT.md и evidence/. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
"""Пароли (scrypt из стандартной библиотеки) и сессионные токены."""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import secrets
|
||||
|
||||
# Параметры scrypt: N=2^15, r=8, p=1 (~32 МБ памяти и ~0.1 с на проверку).
|
||||
SCRYPT_LOG_N = 15
|
||||
SCRYPT_R = 8
|
||||
SCRYPT_P = 1
|
||||
_MAXMEM = 128 * 1024 * 1024
|
||||
|
||||
|
||||
def _scrypt(password, salt, log_n, r, p):
|
||||
return hashlib.scrypt(password.encode("utf-8"), salt=salt, n=2 ** log_n, r=r, p=p,
|
||||
maxmem=_MAXMEM, dklen=32)
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
"""Возвращает строку scrypt$logN$r$p$salt$hash; plaintext нигде не хранится."""
|
||||
salt = os.urandom(16)
|
||||
digest = _scrypt(password, salt, SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P)
|
||||
return "scrypt$%d$%d$%d$%s$%s" % (
|
||||
SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P,
|
||||
base64.b64encode(salt).decode(), base64.b64encode(digest).decode())
|
||||
|
||||
|
||||
def verify_password(password, stored):
|
||||
try:
|
||||
scheme, log_n, r, p, salt, digest = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
expected = base64.b64decode(digest)
|
||||
actual = _scrypt(password, base64.b64decode(salt), int(log_n), int(r), int(p))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
return hmac.compare_digest(actual, expected) # сравнение за постоянное время
|
||||
|
||||
|
||||
# Хеш несуществующего пользователя: неверный логин тратит столько же времени,
|
||||
# сколько неверный пароль, и не выдаёт, существует ли username.
|
||||
DUMMY_HASH = hash_password(secrets.token_urlsafe(16))
|
||||
|
||||
|
||||
def new_token():
|
||||
"""Непрозрачный случайный токен: 32 байта = 256 бит энтропии."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_hash(token):
|
||||
"""В БД лежит только SHA-256 токена: утечка таблицы не даёт готовых сессий."""
|
||||
return hashlib.sha256(token.encode("utf-8")).digest()
|
||||
+503
@@ -0,0 +1,503 @@
|
||||
#!/usr/bin/env python3
|
||||
"""MTUSI Messenger, lab2: REST API с PostgreSQL и сессиями.
|
||||
|
||||
Отличия от lab1:
|
||||
* данные лежат в PostgreSQL и переживают перезапуск API и БД;
|
||||
* регистрация требует password (хранится только scrypt-хеш);
|
||||
* POST /api/v1/auth/sessions (Basic) выдаёт Bearer-токен;
|
||||
* все защищённые endpoint принимают только Authorization: Bearer;
|
||||
* X-User-Id игнорируется.
|
||||
|
||||
Общий каркас (маршрутизация, формат ошибок, X-Request-Id, валидация, keyset-курсор)
|
||||
перенесён из lab1 (app/server.py); хранилище в памяти заменено на store.py.
|
||||
"""
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import psycopg
|
||||
from psycopg.conninfo import make_conninfo
|
||||
from psycopg_pool import PoolTimeout
|
||||
|
||||
import security
|
||||
from session_cache import REVOKED, SessionCache
|
||||
from store import Conflict, Store, UnknownMember, format_ts
|
||||
|
||||
HOST = os.environ.get("APP_HOST", "0.0.0.0")
|
||||
PORT = int(os.environ.get("APP_PORT", "8080"))
|
||||
APP_ENV = os.environ.get("APP_ENV", "lab")
|
||||
SESSION_TTL_SECONDS = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
MIGRATIONS_DIR = os.environ.get("MIGRATIONS_DIR", str(Path(__file__).resolve().parents[1] / "migrations"))
|
||||
MAX_BODY_BYTES = 1024 * 1024
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
DEFAULT_LIMIT = 50
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
log = logging.getLogger("messenger")
|
||||
|
||||
|
||||
def database_conninfo():
|
||||
"""Строка подключения к PostgreSQL.
|
||||
|
||||
Порядок: DATABASE_URL_FILE (Docker secret, рекомендуемый путь) → DATABASE_URL →
|
||||
набор POSTGRES_*. Значение секрета нигде не логируется.
|
||||
"""
|
||||
path = os.environ.get("DATABASE_URL_FILE")
|
||||
if path:
|
||||
url = Path(path).read_text(encoding="utf-8").strip()
|
||||
else:
|
||||
url = os.environ.get("DATABASE_URL", "")
|
||||
if url:
|
||||
# connect_timeout ограничивает ожидание недоступной БД при открытии соединения.
|
||||
return make_conninfo(url, connect_timeout=5)
|
||||
return make_conninfo(
|
||||
host=os.environ.get("POSTGRES_HOST", "localhost"),
|
||||
port=os.environ.get("POSTGRES_PORT", "5432"),
|
||||
dbname=os.environ.get("POSTGRES_DB", "messenger"),
|
||||
user=os.environ.get("POSTGRES_USER", "messenger"),
|
||||
password=os.environ.get("POSTGRES_PASSWORD", ""),
|
||||
connect_timeout=5,
|
||||
)
|
||||
|
||||
|
||||
STORE = Store(database_conninfo(),
|
||||
pool_size=int(os.environ.get("DB_POOL_SIZE", "10")),
|
||||
statement_timeout_ms=int(os.environ.get("DB_STATEMENT_TIMEOUT_MS", "5000")))
|
||||
|
||||
|
||||
def cache_url():
|
||||
"""URL Valkey из CACHE_URL_FILE (Docker secret). SESSION_CACHE=off отключает кэш."""
|
||||
if os.environ.get("SESSION_CACHE", "valkey").lower() == "off":
|
||||
return ""
|
||||
path = os.environ.get("CACHE_URL_FILE")
|
||||
if path:
|
||||
return Path(path).read_text(encoding="utf-8").strip()
|
||||
return os.environ.get("CACHE_URL", "")
|
||||
|
||||
|
||||
SESSION_CACHE = SessionCache(
|
||||
cache_url(),
|
||||
ttl_seconds=int(os.environ.get("SESSION_CACHE_TTL_SECONDS", "30")),
|
||||
timeout_ms=int(os.environ.get("CACHE_TIMEOUT_MS", "250")),
|
||||
retry_seconds=float(os.environ.get("CACHE_RETRY_SECONDS", "5")))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Ошибки API
|
||||
# --------------------------------------------------------------------------
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status, code, message, headers=None):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def bad_request(message="Неверный запрос"):
|
||||
return ApiError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def unauthorized(challenge=BEARER_CHALLENGE):
|
||||
# Одинаковый ответ для любых причин: не раскрываем, что именно не так.
|
||||
return ApiError(401, "unauthorized", "Требуется действительная аутентификация",
|
||||
{"WWW-Authenticate": challenge})
|
||||
|
||||
|
||||
def not_found():
|
||||
return ApiError(404, "not_found", "Объект не найден")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Валидация
|
||||
# --------------------------------------------------------------------------
|
||||
def parse_uuid(value):
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
def require_object(body, allowed, required):
|
||||
if not isinstance(body, dict):
|
||||
raise bad_request("Тело запроса должно быть JSON-объектом")
|
||||
if set(body) - set(allowed):
|
||||
raise bad_request("Лишние поля в запросе")
|
||||
if any(k not in body for k in required):
|
||||
raise bad_request("Не хватает обязательных полей")
|
||||
|
||||
|
||||
def require_text(value, field, max_len, min_len=1):
|
||||
if not isinstance(value, str):
|
||||
raise bad_request("Поле %s должно быть строкой" % field)
|
||||
if not value.strip():
|
||||
raise bad_request("Поле %s не должно быть пустым" % field)
|
||||
if "\x00" in value:
|
||||
raise bad_request("Поле %s содержит недопустимый символ" % field)
|
||||
if not min_len <= len(value) <= max_len: # len() считает Unicode code points
|
||||
raise bad_request("Поле %s имеет недопустимую длину" % field)
|
||||
return value
|
||||
|
||||
|
||||
def encode_cursor(kind, scope, key):
|
||||
raw = json.dumps({"k": kind, "s": scope, "t": key[0], "i": key[1]}, separators=(",", ":"))
|
||||
return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor, kind, scope):
|
||||
try:
|
||||
padded = cursor + "=" * (-len(cursor) % 4)
|
||||
data = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")))
|
||||
if data["k"] != kind or data["s"] != scope:
|
||||
raise ValueError
|
||||
t, i = data["t"], parse_uuid(data["i"])
|
||||
if not isinstance(t, int) or isinstance(t, bool) or i is None or abs(t) > 10 ** 17:
|
||||
raise ValueError
|
||||
return (t, i)
|
||||
except (ValueError, KeyError, TypeError, UnicodeError, binascii.Error):
|
||||
raise bad_request("Неверный cursor")
|
||||
|
||||
|
||||
def page_params(query):
|
||||
def single(name):
|
||||
values = query.get(name)
|
||||
if values is None:
|
||||
return None
|
||||
if len(values) != 1:
|
||||
raise bad_request("Параметр %s указан несколько раз" % name)
|
||||
return values[0]
|
||||
|
||||
limit_raw = single("limit")
|
||||
if limit_raw is None:
|
||||
limit = DEFAULT_LIMIT
|
||||
else:
|
||||
if not re.fullmatch(r"[0-9]{1,3}", limit_raw) or not 1 <= int(limit_raw) <= 100:
|
||||
raise bad_request("limit должен быть целым от 1 до 100")
|
||||
limit = int(limit_raw)
|
||||
cursor = single("cursor")
|
||||
if cursor == "":
|
||||
raise bad_request("Неверный cursor")
|
||||
return limit, cursor
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Обработчики
|
||||
# --------------------------------------------------------------------------
|
||||
def h_live(req):
|
||||
return 200, {"status": "ok"}
|
||||
|
||||
|
||||
def h_ready(req):
|
||||
# Критичная зависимость одна — PostgreSQL. Без неё обслуживать запросы нельзя.
|
||||
# Valkey не критичен: при его отказе сессии проверяются напрямую в PostgreSQL.
|
||||
try:
|
||||
STORE.ping()
|
||||
except Exception:
|
||||
raise ApiError(503, "unavailable", "Сервис временно недоступен")
|
||||
return 200, {"status": "ok"}
|
||||
|
||||
|
||||
def h_create_user(req):
|
||||
body = req.json_body()
|
||||
fields = ("username", "display_name", "password")
|
||||
require_object(body, fields, fields)
|
||||
username = body["username"]
|
||||
if not isinstance(username, str) or not USERNAME_RE.fullmatch(username):
|
||||
raise bad_request("username должен соответствовать [a-z0-9_]{3,32}")
|
||||
display_name = require_text(body["display_name"], "display_name", 100)
|
||||
password = require_text(body["password"], "password", 128, min_len=12)
|
||||
try:
|
||||
return 201, STORE.create_user(username, display_name, security.hash_password(password))
|
||||
except Conflict:
|
||||
raise ApiError(409, "conflict", "Имя пользователя уже занято")
|
||||
|
||||
|
||||
def h_create_session(req):
|
||||
"""Вход: только Authorization: Basic, без JSON body."""
|
||||
header = req.headers.get("Authorization", "")
|
||||
scheme, _, encoded = header.partition(" ")
|
||||
failure = unauthorized(BASIC_CHALLENGE)
|
||||
if scheme.lower() != "basic":
|
||||
raise failure
|
||||
try:
|
||||
decoded = base64.b64decode(encoded.strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, ValueError, UnicodeError):
|
||||
raise failure
|
||||
username, sep, password = decoded.partition(":") # двоеточие в пароле допустимо
|
||||
if not sep:
|
||||
raise failure
|
||||
user, stored_hash = (None, None)
|
||||
if USERNAME_RE.fullmatch(username):
|
||||
user, stored_hash = STORE.get_credentials(username)
|
||||
# Проверяем scrypt всегда (для неизвестного логина — с фиктивным хешем):
|
||||
# время ответа не выдаёт, существует ли пользователь.
|
||||
ok = security.verify_password(password, stored_hash or security.DUMMY_HASH)
|
||||
if user is None or not ok:
|
||||
raise failure
|
||||
token = security.new_token()
|
||||
th = security.token_hash(token)
|
||||
started = time.monotonic()
|
||||
expires_at = STORE.create_session(user["id"], th, SESSION_TTL_SECONDS) # источник истины
|
||||
SESSION_CACHE.put(th, user, expires_at.timestamp(), started) # прогрев кэша
|
||||
return 201, {"token": token, "token_type": "Bearer", "expires_at": format_ts(expires_at), "user": user}
|
||||
|
||||
|
||||
def h_delete_session(req):
|
||||
req.current_user()
|
||||
STORE.revoke_session(req.token_hash) # 1) COMMIT отзыва в PostgreSQL
|
||||
SESSION_CACHE.revoke(req.token_hash) # 2) tombstone в Valkey поверх возможной копии
|
||||
return 204, None
|
||||
|
||||
|
||||
def h_me(req):
|
||||
return 200, req.current_user()
|
||||
|
||||
|
||||
def h_create_chat(req):
|
||||
user = req.current_user()
|
||||
body = req.json_body()
|
||||
require_object(body, ("title", "member_ids"), ("title", "member_ids"))
|
||||
title = require_text(body["title"], "title", 100)
|
||||
members = body["member_ids"]
|
||||
if not isinstance(members, list) or not 1 <= len(members) <= 100:
|
||||
raise bad_request("member_ids должен быть списком из 1–100 UUID")
|
||||
normalized = []
|
||||
for m in members:
|
||||
mid = parse_uuid(m) if isinstance(m, str) else None
|
||||
if mid is None:
|
||||
raise bad_request("member_ids должен содержать UUID-строки")
|
||||
normalized.append(mid)
|
||||
if len(set(normalized)) != len(normalized):
|
||||
raise bad_request("Дубликаты в member_ids")
|
||||
if user["id"] not in normalized:
|
||||
raise bad_request("Создатель должен входить в member_ids")
|
||||
try:
|
||||
return 201, STORE.create_chat(title, normalized)
|
||||
except UnknownMember:
|
||||
raise bad_request("Неизвестный участник чата")
|
||||
|
||||
|
||||
def h_list_chats(req):
|
||||
user = req.current_user()
|
||||
limit, cursor = page_params(req.query)
|
||||
after = decode_cursor(cursor, "chats", user["id"]) if cursor else None
|
||||
items, last = STORE.list_chats(user["id"], after, limit)
|
||||
return 200, {"items": items, "next_cursor": encode_cursor("chats", user["id"], last) if last else None}
|
||||
|
||||
|
||||
def _chat_or_404(user, chat_id):
|
||||
chat = STORE.get_chat_for(user["id"], chat_id)
|
||||
if chat is None:
|
||||
raise not_found()
|
||||
return chat
|
||||
|
||||
|
||||
def h_get_chat(req, chat_id):
|
||||
user = req.current_user()
|
||||
return 200, _chat_or_404(user, req.path_uuid(chat_id))
|
||||
|
||||
|
||||
def h_create_message(req, chat_id):
|
||||
user = req.current_user()
|
||||
cid = req.path_uuid(chat_id)
|
||||
_chat_or_404(user, cid) # сначала доступ: посторонний получает 404
|
||||
body = req.json_body()
|
||||
require_object(body, ("text",), ("text",))
|
||||
text = require_text(body["text"], "text", 4000)
|
||||
message = STORE.add_message(user["id"], cid, text)
|
||||
if message is None:
|
||||
raise not_found()
|
||||
return 201, message
|
||||
|
||||
|
||||
def h_list_messages(req, chat_id):
|
||||
user = req.current_user()
|
||||
cid = req.path_uuid(chat_id)
|
||||
_chat_or_404(user, cid)
|
||||
limit, cursor = page_params(req.query)
|
||||
after = decode_cursor(cursor, "messages", cid) if cursor else None
|
||||
items, last = STORE.list_messages(cid, after, limit)
|
||||
return 200, {"items": items, "next_cursor": encode_cursor("messages", cid, last) if last else None}
|
||||
|
||||
|
||||
ROUTES = [
|
||||
("GET", re.compile(r"^/health/live$"), h_live),
|
||||
("GET", re.compile(r"^/health/ready$"), h_ready),
|
||||
("POST", re.compile(r"^/api/v1/users$"), h_create_user),
|
||||
("GET", re.compile(r"^/api/v1/users/me$"), h_me),
|
||||
("POST", re.compile(r"^/api/v1/auth/sessions$"), h_create_session),
|
||||
("DELETE", re.compile(r"^/api/v1/auth/sessions/current$"), h_delete_session),
|
||||
("POST", re.compile(r"^/api/v1/chats$"), h_create_chat),
|
||||
("GET", re.compile(r"^/api/v1/chats$"), h_list_chats),
|
||||
("GET", re.compile(r"^/api/v1/chats/([^/]+)$"), h_get_chat),
|
||||
("POST", re.compile(r"^/api/v1/chats/([^/]+)/messages$"), h_create_message),
|
||||
("GET", re.compile(r"^/api/v1/chats/([^/]+)/messages$"), h_list_messages),
|
||||
]
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
server_version = "mtusi-messenger/2.0"
|
||||
sys_version = ""
|
||||
|
||||
def json_body(self):
|
||||
ctype = (self.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||||
if ctype != "application/json":
|
||||
raise ApiError(415, "unsupported_media_type", "Ожидается Content-Type: application/json")
|
||||
try:
|
||||
return json.loads(self._body.decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
raise bad_request("Некорректный JSON")
|
||||
|
||||
def current_user(self):
|
||||
"""Только Bearer-токен действующей сессии. Basic и X-User-Id доступа не дают."""
|
||||
scheme, _, token = self.headers.get("Authorization", "").partition(" ")
|
||||
token = token.strip()
|
||||
if scheme.lower() != "bearer" or not token:
|
||||
raise unauthorized()
|
||||
self.token_hash = security.token_hash(token)
|
||||
cached = SESSION_CACHE.get(self.token_hash) # 1) Valkey: hit / tombstone / промах
|
||||
if cached is REVOKED:
|
||||
raise unauthorized()
|
||||
if cached is not None:
|
||||
return cached
|
||||
started = time.monotonic()
|
||||
found = STORE.get_session_user(self.token_hash) # 2) промах → PostgreSQL
|
||||
if found is None:
|
||||
raise unauthorized()
|
||||
user, expires_at = found
|
||||
SESSION_CACHE.put(self.token_hash, user, expires_at.timestamp(), started)
|
||||
return user
|
||||
|
||||
def path_uuid(self, value):
|
||||
parsed = parse_uuid(value)
|
||||
if parsed is None:
|
||||
raise bad_request("Неверный UUID в пути")
|
||||
return parsed
|
||||
|
||||
def _read_body(self):
|
||||
length = self.headers.get("Content-Length")
|
||||
if length is None:
|
||||
return b""
|
||||
try:
|
||||
n = int(length)
|
||||
except ValueError:
|
||||
raise bad_request("Неверный Content-Length")
|
||||
if n < 0:
|
||||
raise bad_request("Неверный Content-Length")
|
||||
if n > MAX_BODY_BYTES:
|
||||
self.close_connection = True
|
||||
raise ApiError(413, "payload_too_large", "Тело запроса слишком большое")
|
||||
return self.rfile.read(n)
|
||||
|
||||
def _dispatch(self, method):
|
||||
self.request_id = uuid.uuid4().hex
|
||||
started = time.monotonic()
|
||||
parts = urlsplit(self.path)
|
||||
path = parts.path
|
||||
headers = {}
|
||||
try:
|
||||
self._body = self._read_body()
|
||||
self.query = parse_qs(parts.query, keep_blank_values=True)
|
||||
for m, pattern, func in ROUTES:
|
||||
match = pattern.match(path)
|
||||
if match and m == method:
|
||||
status, payload = func(self, *match.groups())
|
||||
break
|
||||
else:
|
||||
raise not_found()
|
||||
except ApiError as err:
|
||||
status, payload, headers = err.status, self._error(err.code, err.message), err.headers
|
||||
except (psycopg.OperationalError, PoolTimeout):
|
||||
# БД недоступна: честный 503, а не «успех» или 500.
|
||||
log.warning("database unavailable request_id=%s", self.request_id)
|
||||
status, payload = 503, self._error("unavailable", "Сервис временно недоступен")
|
||||
except Exception:
|
||||
log.exception("unhandled error request_id=%s", self.request_id)
|
||||
status, payload = 500, self._error("internal_error", "Внутренняя ошибка сервера")
|
||||
self._send(status, payload, headers)
|
||||
# В лог не попадают тела запросов, пароли, токены и тексты сообщений.
|
||||
log.info("%s %s -> %d %.1fms request_id=%s", method, path, status,
|
||||
(time.monotonic() - started) * 1000, self.request_id)
|
||||
|
||||
def _error(self, code, message):
|
||||
return {"error": {"code": code, "message": message, "request_id": self.request_id}}
|
||||
|
||||
def _send(self, status, payload, headers):
|
||||
self.send_response(status)
|
||||
self.send_header("X-Request-Id", self.request_id)
|
||||
for name, value in headers.items():
|
||||
self.send_header(name, value)
|
||||
if payload is None: # 204: без тела
|
||||
self.end_headers()
|
||||
return
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
self._dispatch("GET")
|
||||
|
||||
def do_POST(self):
|
||||
self._dispatch("POST")
|
||||
|
||||
def do_PUT(self):
|
||||
self._dispatch("PUT")
|
||||
|
||||
def do_PATCH(self):
|
||||
self._dispatch("PATCH")
|
||||
|
||||
def do_DELETE(self):
|
||||
self._dispatch("DELETE")
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
pass
|
||||
|
||||
|
||||
class Server(ThreadingHTTPServer):
|
||||
request_queue_size = 1024
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
def main():
|
||||
STORE.open()
|
||||
STORE.migrate(MIGRATIONS_DIR)
|
||||
if "--migrate-only" in sys.argv[1:]:
|
||||
# Отдельный запуск миграций: docker compose run --rm api python /app/src/server.py --migrate-only
|
||||
log.info("migrations are up to date, exiting (--migrate-only)")
|
||||
STORE.close()
|
||||
return
|
||||
server = Server((HOST, PORT), Handler)
|
||||
|
||||
def stop(signum, frame):
|
||||
log.info("signal %d received, shutting down", signum)
|
||||
threading.Thread(target=server.shutdown, daemon=True).start()
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
log.info("listening on %s:%d env=%s session_ttl=%ds session_cache=%s", HOST, PORT, APP_ENV,
|
||||
SESSION_TTL_SECONDS, "valkey" if SESSION_CACHE.enabled else "off")
|
||||
server.serve_forever()
|
||||
server.server_close()
|
||||
STORE.close()
|
||||
log.info("stopped")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Кэш сессий в Valkey (уровень 4).
|
||||
|
||||
Роль: ускорить проверку Bearer-токена, которая выполняется на КАЖДОМ защищённом запросе.
|
||||
Источник истины — таблица sessions в PostgreSQL; Valkey хранит только производные копии.
|
||||
|
||||
Ключ: sess:<sha256(token) hex> (сам токен в Valkey не попадает)
|
||||
Значение: {"user": {...}, "exp": <unix-время истечения сессии>} либо "revoked"
|
||||
|
||||
Политика expiry:
|
||||
* положительная запись живёт min(SESSION_CACHE_TTL_SECONDS, остаток сессии) — PX в мс,
|
||||
поэтому кэш не переживает саму сессию; при чтении "exp" дополнительно сверяется с часами;
|
||||
* запись "revoked" (tombstone) живёт SESSION_CACHE_TTL_SECONDS + 1 с — дольше любой
|
||||
положительной записи, созданной до отзыва.
|
||||
|
||||
Инвалидация (logout): сначала UPDATE sessions SET revoked_at в PostgreSQL (COMMIT), затем
|
||||
SET sess:<h> "revoked" поверх положительной записи. Заполнение кэша после промаха делается
|
||||
SET NX, поэтому конкурентный запрос, прочитавший БД до отзыва, не может перезаписать tombstone.
|
||||
|
||||
Отказ Valkey: любая ошибка/таймаут (по умолчанию 250 мс) → запрос обслуживается из PostgreSQL,
|
||||
кэш обходится CACHE_RETRY_SECONDS секунд (простой circuit breaker). Если не удалось записать
|
||||
tombstone, процесс SESSION_CACHE_TTL_SECONDS+1 секунд не доверяет положительным записям кэша:
|
||||
устаревшая запись могла остаться в Valkey, но за это время она гарантированно истечёт.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
|
||||
import redis
|
||||
|
||||
log = logging.getLogger("messenger.cache")
|
||||
|
||||
PREFIX = "sess:"
|
||||
REVOKED = object() # результат get(): сессия отозвана (tombstone)
|
||||
MISS = None # результат get(): нет данных/кэш недоступен → идти в PostgreSQL
|
||||
_TOMBSTONE = b"revoked"
|
||||
|
||||
|
||||
class SessionCache:
|
||||
def __init__(self, url, ttl_seconds=30, timeout_ms=250, retry_seconds=5.0, pool_size=10):
|
||||
self.enabled = bool(url)
|
||||
self.ttl = ttl_seconds
|
||||
self.retry_seconds = retry_seconds
|
||||
self._lock = threading.Lock()
|
||||
self._skip_until = 0.0 # circuit breaker: до этого момента кэш не опрашиваем
|
||||
self._distrust_until = 0.0 # до этого момента положительные записи игнорируем
|
||||
self.client = None
|
||||
if self.enabled:
|
||||
timeout = timeout_ms / 1000.0
|
||||
# Ограниченный пул: не более pool_size соединений, ожидание свободного — timeout.
|
||||
pool = redis.BlockingConnectionPool.from_url(
|
||||
url, max_connections=pool_size, timeout=timeout,
|
||||
socket_timeout=timeout, socket_connect_timeout=timeout)
|
||||
self.client = redis.Redis(connection_pool=pool)
|
||||
|
||||
# --- служебное ---
|
||||
def _available(self):
|
||||
return self.enabled and time.monotonic() >= self._skip_until
|
||||
|
||||
def _failed(self, op, invalidation=False):
|
||||
now = time.monotonic()
|
||||
with self._lock:
|
||||
self._skip_until = now + self.retry_seconds
|
||||
if invalidation:
|
||||
self._distrust_until = max(self._distrust_until, now + self.ttl + 1)
|
||||
log.warning("cache unavailable op=%s; bypassing cache for %.0fs%s", op, self.retry_seconds,
|
||||
"; positive entries distrusted for %ds" % (self.ttl + 1) if invalidation else "")
|
||||
|
||||
@staticmethod
|
||||
def _key(token_hash):
|
||||
return PREFIX + token_hash.hex()
|
||||
|
||||
# --- API ---
|
||||
def get(self, token_hash):
|
||||
"""Пользователь из кэша, REVOKED или MISS."""
|
||||
if not self._available():
|
||||
return MISS
|
||||
try:
|
||||
raw = self.client.get(self._key(token_hash))
|
||||
except redis.RedisError:
|
||||
self._failed("get")
|
||||
return MISS
|
||||
if raw is None:
|
||||
return MISS
|
||||
if raw == _TOMBSTONE:
|
||||
return REVOKED
|
||||
if time.monotonic() < self._distrust_until:
|
||||
return MISS
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
if data["exp"] <= time.time():
|
||||
return MISS
|
||||
return data["user"]
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return MISS
|
||||
|
||||
def put(self, token_hash, user, expires_epoch, read_started):
|
||||
"""Заполнить кэш после чтения действующей сессии из PostgreSQL."""
|
||||
if not self._available():
|
||||
return
|
||||
# Если между чтением БД и записью в кэш прошло подозрительно много времени,
|
||||
# данные могли устареть (например, logout + истечение tombstone) — не кэшируем.
|
||||
if time.monotonic() - read_started > 1.0:
|
||||
return
|
||||
ttl_ms = int(min(self.ttl, expires_epoch - time.time()) * 1000)
|
||||
if ttl_ms <= 0:
|
||||
return
|
||||
value = json.dumps({"user": user, "exp": expires_epoch}, separators=(",", ":"))
|
||||
try:
|
||||
self.client.set(self._key(token_hash), value, px=ttl_ms, nx=True)
|
||||
except redis.RedisError:
|
||||
self._failed("set")
|
||||
|
||||
def revoke(self, token_hash):
|
||||
"""Tombstone после COMMIT отзыва в PostgreSQL. Пробуем даже при открытом breaker."""
|
||||
if not self.enabled:
|
||||
return
|
||||
try:
|
||||
self.client.set(self._key(token_hash), _TOMBSTONE, ex=self.ttl + 1)
|
||||
except redis.RedisError:
|
||||
self._failed("revoke", invalidation=True)
|
||||
+271
@@ -0,0 +1,271 @@
|
||||
"""Работа с PostgreSQL: пользователи, чаты, сообщения, сессии.
|
||||
|
||||
Источник истины — база данных. В памяти процесса состояния нет, поэтому
|
||||
перезапуск API (и самой БД с сохранённым volume) не теряет данные.
|
||||
"""
|
||||
import datetime as dt
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
log = logging.getLogger("messenger.store")
|
||||
|
||||
EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.timezone.utc)
|
||||
MIGRATIONS_LOCK_ID = 727001 # произвольный номер advisory-блокировки для миграций
|
||||
|
||||
|
||||
class Conflict(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnknownMember(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def format_ts(value):
|
||||
"""datetime -> RFC 3339 UTC с микросекундами и суффиксом Z."""
|
||||
return value.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def to_micros(value):
|
||||
delta = value - EPOCH
|
||||
return (delta.days * 86400 + delta.seconds) * 1_000_000 + delta.microseconds
|
||||
|
||||
|
||||
def from_micros(micros):
|
||||
return EPOCH + dt.timedelta(microseconds=micros)
|
||||
|
||||
|
||||
def _user(row):
|
||||
# Пароль/hash и сессионные данные никогда не входят в User.
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _chat(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(m) for m in row["member_ids"]],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _message(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
CHAT_COLUMNS = """c.id, c.title, c.created_at,
|
||||
(SELECT array_agg(m.user_id ORDER BY m.position) FROM chat_members m WHERE m.chat_id = c.id) AS member_ids"""
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, conninfo, pool_size=10, statement_timeout_ms=5000):
|
||||
# Ограниченный пул: не более pool_size соединений; ожидание свободного — до 5 с,
|
||||
# затем PoolTimeout → 503. statement_timeout обрывает зависший SQL.
|
||||
# check: перед выдачей соединение проверяется. После перезапуска PostgreSQL
|
||||
# «мёртвые» соединения отбрасываются, и запрос не получает ложный 503.
|
||||
self.pool = ConnectionPool(
|
||||
conninfo, min_size=1, max_size=pool_size, timeout=5,
|
||||
kwargs={"row_factory": dict_row,
|
||||
"options": "-c statement_timeout=%d" % statement_timeout_ms},
|
||||
open=False,
|
||||
check=ConnectionPool.check_connection)
|
||||
|
||||
# --- запуск ---
|
||||
def open(self, wait_seconds=60):
|
||||
"""Ждём готовности БД (она может стартовать дольше API) и открываем пул."""
|
||||
self.pool.open()
|
||||
deadline = time.monotonic() + wait_seconds
|
||||
while True:
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
return
|
||||
except Exception as exc:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
log.info("database is not ready yet (%s), retrying", type(exc).__name__)
|
||||
time.sleep(1)
|
||||
|
||||
def close(self):
|
||||
self.pool.close()
|
||||
|
||||
def migrate(self, directory):
|
||||
"""Применяет *.sql по порядку имён; каждая миграция — одна транзакция, один раз."""
|
||||
files = sorted(Path(directory).glob("*.sql"))
|
||||
with self.pool.connection() as conn:
|
||||
# Advisory-блокировка (сессионная): несколько процессов не применят миграции одновременно.
|
||||
conn.autocommit = True
|
||||
conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATIONS_LOCK_ID,))
|
||||
try:
|
||||
conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())""")
|
||||
done = {r["version"] for r in conn.execute("SELECT version FROM schema_migrations")}
|
||||
for path in files:
|
||||
if path.name in done:
|
||||
continue
|
||||
# Каждая миграция и её отметка — одна транзакция: либо целиком, либо никак.
|
||||
with conn.transaction():
|
||||
conn.execute(path.read_text(encoding="utf-8"))
|
||||
conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (path.name,))
|
||||
log.info("migration applied: %s", path.name)
|
||||
log.info("schema version: %s", files[-1].name if files else "none")
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATIONS_LOCK_ID,))
|
||||
conn.autocommit = False
|
||||
|
||||
def ping(self):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
|
||||
# --- пользователи ---
|
||||
def create_user(self, username, display_name, password_hash):
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (%s, %s, %s, %s, clock_timestamp())
|
||||
RETURNING id, username, display_name, created_at""",
|
||||
(uuid.uuid4(), username, display_name, password_hash)).fetchone()
|
||||
except psycopg.errors.UniqueViolation:
|
||||
# Уникальность гарантирует сама БД — гонка двух регистраций безопасна.
|
||||
raise Conflict()
|
||||
return _user(row)
|
||||
|
||||
def get_credentials(self, username):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s",
|
||||
(username,)).fetchone()
|
||||
if row is None:
|
||||
return None, None
|
||||
return _user(row), row["password_hash"]
|
||||
|
||||
# --- сессии ---
|
||||
def create_session(self, user_id, token_hash, ttl_seconds):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""INSERT INTO sessions (token_hash, user_id, created_at, expires_at)
|
||||
VALUES (%s, %s, now(), now() + make_interval(secs => %s))
|
||||
RETURNING expires_at""",
|
||||
(token_hash, user_id, ttl_seconds)).fetchone()
|
||||
return row["expires_at"]
|
||||
|
||||
def get_session_user(self, token_hash):
|
||||
"""(пользователь, expires_at) действующей сессии или None (неизвестна/истекла/отозвана)."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = %s AND s.revoked_at IS NULL AND s.expires_at > now()""",
|
||||
(token_hash,)).fetchone()
|
||||
return (_user(row), row["expires_at"]) if row else None
|
||||
|
||||
def revoke_session(self, token_hash):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"UPDATE sessions SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
|
||||
(token_hash,))
|
||||
|
||||
# --- чаты ---
|
||||
def create_chat(self, title, member_ids):
|
||||
"""Чат и его участники создаются в одной транзакции (атомарно)."""
|
||||
chat_id = uuid.uuid4()
|
||||
# Блок `with pool.connection()` = одна транзакция: COMMIT при выходе без исключения,
|
||||
# ROLLBACK при любом исключении. Чат без участников (или наоборот) не появится.
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
found = conn.execute(
|
||||
"SELECT count(*) AS n FROM users WHERE id = ANY(%s::uuid[])", (member_ids,)).fetchone()["n"]
|
||||
if found != len(member_ids):
|
||||
raise UnknownMember()
|
||||
conn.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, clock_timestamp())",
|
||||
(chat_id, title))
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id, position) VALUES (%s, %s, %s)",
|
||||
[(chat_id, m, i) for i, m in enumerate(member_ids)])
|
||||
row = conn.execute("SELECT " + CHAT_COLUMNS + " FROM chats c WHERE c.id = %s", (chat_id,)).fetchone()
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
# Внешний ключ — последняя линия защиты: транзакция откатывается целиком.
|
||||
raise UnknownMember()
|
||||
return _chat(row)
|
||||
|
||||
def get_chat_for(self, user_id, chat_id):
|
||||
"""Чат, если пользователь — участник; иначе None (чужой и несуществующий неразличимы)."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT " + CHAT_COLUMNS + """ FROM chats c
|
||||
WHERE c.id = %s AND EXISTS (
|
||||
SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = %s)""",
|
||||
(chat_id, user_id)).fetchone()
|
||||
return _chat(row) if row else None
|
||||
|
||||
def list_chats(self, user_id, after, limit):
|
||||
params = [user_id]
|
||||
where = ""
|
||||
if after:
|
||||
where = "AND (c.created_at, c.id) > (%s, %s::uuid)"
|
||||
params += [from_micros(after[0]), after[1]]
|
||||
params.append(limit + 1) # +1 запись: узнаём, есть ли следующая страница
|
||||
with self.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT " + CHAT_COLUMNS + """ FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s
|
||||
WHERE true """ + where + " ORDER BY c.created_at, c.id LIMIT %s", params).fetchall()
|
||||
return self._page(rows, limit, _chat)
|
||||
|
||||
# --- сообщения ---
|
||||
def add_message(self, user_id, chat_id, text):
|
||||
with self.pool.connection() as conn:
|
||||
# FOR UPDATE по строке чата: вставки в один чат идут по очереди, поэтому
|
||||
# created_at растёт в порядке фиксации и keyset-курсор не пропускает записи.
|
||||
allowed = conn.execute(
|
||||
"""SELECT 1 FROM chats c WHERE c.id = %s AND EXISTS (
|
||||
SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = %s)
|
||||
FOR UPDATE OF c""", (chat_id, user_id)).fetchone()
|
||||
if allowed is None:
|
||||
return None
|
||||
row = conn.execute(
|
||||
"""INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES (%s, %s, %s, %s, clock_timestamp())
|
||||
RETURNING id, chat_id, sender_id, text, created_at""",
|
||||
(uuid.uuid4(), chat_id, user_id, text)).fetchone()
|
||||
return _message(row)
|
||||
|
||||
def list_messages(self, chat_id, after, limit):
|
||||
params = [chat_id]
|
||||
where = ""
|
||||
if after:
|
||||
where = "AND (created_at, id) > (%s, %s::uuid)"
|
||||
params += [from_micros(after[0]), after[1]]
|
||||
params.append(limit + 1)
|
||||
with self.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s "
|
||||
+ where + " ORDER BY created_at, id LIMIT %s", params).fetchall()
|
||||
return self._page(rows, limit, _message)
|
||||
|
||||
@staticmethod
|
||||
def _page(rows, limit, convert):
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
last = (to_micros(rows[-1]["created_at"]), str(rows[-1]["id"])) if rows and has_more else None
|
||||
return [convert(r) for r in rows], last
|
||||
Reference in New Issue
Block a user