Собрать стенд lab3: балансировка, идемпотентность и трек 1

This commit is contained in:
Wladislava1
2026-11-06 16:04:28 +03:00
parent 0ab3a341aa
commit d9e13a06d9
42 changed files with 3602 additions and 33 deletions
+24
View File
@@ -0,0 +1,24 @@
class ApiError(Exception):
def __init__(self, status, code, message, headers=None):
self.status = status
self.code = code
self.message = message
self.headers = headers or {}
class DependencyDown(Exception):
"""Postgres или Redis не ответили. Наружу это 503 без имени хранилища."""
class IdempotencyConflict(Exception):
"""Тот же Idempotency-Key уже зафиксирован с другим телом."""
def error_body(code, message, request_id):
return {
"error": {
"code": code,
"message": message,
"request_id": request_id,
}
}
+360
View File
@@ -0,0 +1,360 @@
import json
import logging
import os
import re
import uuid
from contextlib import asynccontextmanager
import anyio
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from pydantic import ValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from errors import ApiError, DependencyDown, IdempotencyConflict, error_body
from schemas import CreateChat, CreateMessage, CreateUser
from store import Store, instance_id
LOGGER = logging.getLogger("messenger")
store = Store()
INSTANCE_ID = instance_id()
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
MAX_JSON_BYTES = 65536
@asynccontextmanager
async def lifespan(_app):
await anyio.to_thread.run_sync(store.startup)
yield
store.shutting_down = True
await anyio.to_thread.run_sync(store.shutdown)
app = FastAPI(
title="mtusi-messenger",
version="lab3",
lifespan=lifespan,
redirect_slashes=False,
docs_url="/docs",
redoc_url=None,
openapi_url="/openapi.json",
)
def request_id_of(request: Request):
rid = getattr(request.state, "request_id", None)
if rid:
return rid
return str(uuid.uuid4())
def stamp(request: Request, response):
response.headers["X-Request-Id"] = request_id_of(request)
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
def json_ok(request: Request, payload, status_code=200):
return stamp(request, JSONResponse(payload, status_code=status_code))
def json_error(request: Request, status, code, message, extra_headers=None):
headers = {"X-Request-Id": request_id_of(request), "X-Instance-Id": INSTANCE_ID}
if extra_headers:
headers.update(extra_headers)
return JSONResponse(error_body(code, message, request_id_of(request)), status_code=status, headers=headers)
@app.middleware("http")
async def wrap_request(request: Request, call_next):
incoming = request.headers.get("X-Request-Id", "")
if incoming and len(incoming) <= 200 and incoming.isprintable() and incoming.strip():
request.state.request_id = incoming.strip()
else:
request.state.request_id = str(uuid.uuid4())
if store.shutting_down and request.url.path != "/health/live":
return json_error(request, 503, "unavailable", "Сервис временно недоступен")
response = await call_next(request)
return stamp(request, response)
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
@app.exception_handler(RequestValidationError)
async def request_validation_handler(request: Request, _exc: RequestValidationError):
return json_error(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(ValidationError)
async def pydantic_handler(request: Request, _exc: ValidationError):
return json_error(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
if exc.status_code == 404:
return json_error(request, 404, "not_found", "Объект не найден")
return json_error(request, exc.status_code if exc.status_code < 500 else 500, "invalid_request", "Некорректный запрос")
@app.exception_handler(Exception)
async def unexpected_handler(request: Request, exc: Exception):
if isinstance(exc, ApiError):
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
LOGGER.exception("unhandled")
return json_error(request, 500, "internal_error", "Внутренняя ошибка")
def unavailable():
raise ApiError(503, "unavailable", "Сервис временно недоступен")
def bearer_unauthorized():
raise ApiError(401, "unauthorized", "Требуется авторизация", {"WWW-Authenticate": BEARER_CHALLENGE})
def basic_unauthorized():
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": BASIC_CHALLENGE})
def invalid():
raise ApiError(400, "invalid_request", "Некорректный запрос")
async def call_store(func, *args):
try:
return await anyio.to_thread.run_sync(func, *args)
except DependencyDown:
unavailable()
except IdempotencyConflict:
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
def parse_basic(request: Request):
header = request.headers.get("Authorization", "")
if not header.lower().startswith("basic "):
basic_unauthorized()
raw = header.split(" ", 1)[1].strip()
try:
import base64
decoded = base64.b64decode(raw, validate=True).decode("utf-8")
except (ValueError, UnicodeError):
basic_unauthorized()
if ":" not in decoded:
basic_unauthorized()
username, password = decoded.split(":", 1)
return username, password
def parse_bearer(request: Request):
header = request.headers.get("Authorization", "")
# Basic на бизнес-методе не открывает сессию. X-User-Id не смотрим.
if not header.lower().startswith("bearer "):
bearer_unauthorized()
token = header.split(" ", 1)[1].strip()
if len(token) < 32 or len(token) > 512 or any(ch.isspace() for ch in token):
bearer_unauthorized()
return token
async def current_user(request: Request):
token = parse_bearer(request)
user = await call_store(store.user_for_token, token)
if user is None:
bearer_unauthorized()
request.state.user_id = user["id"]
request.state.token = token
return user
def parse_chat_id(chat_id):
try:
return str(uuid.UUID(chat_id))
except ValueError:
invalid()
def parse_limit(raw):
if raw is None:
return 50
if not isinstance(raw, str) or len(raw) > 3 or not raw.isdigit():
invalid()
value = int(raw)
if value < 1 or value > 100:
invalid()
return value
async def read_json(request: Request):
ctype = request.headers.get("content-type", "")
if "application/json" not in ctype.lower():
raise ApiError(415, "unsupported_media_type", "Нужен application/json")
length = request.headers.get("content-length")
if length is not None and (not length.isdigit() or int(length) > MAX_JSON_BYTES):
raise ApiError(413, "payload_too_large", "Слишком большое тело")
raw = await request.body()
if len(raw) > MAX_JSON_BYTES:
raise ApiError(413, "payload_too_large", "Слишком большое тело")
try:
payload = json.loads(raw)
except (ValueError, UnicodeError):
invalid()
if not isinstance(payload, dict):
invalid()
return payload
def parse_idempotency_key(request: Request):
key = request.headers.get("Idempotency-Key")
if key is None or not IDEMPOTENCY_RE.fullmatch(key):
invalid()
return key
@app.get("/health/live")
async def liveness(request: Request):
return json_ok(request, {"status": "ok"})
@app.get("/health/ready")
async def readiness(request: Request):
if store.shutting_down:
raise ApiError(503, "unavailable", "Сервис временно недоступен")
ok = await call_store(store.ready)
if not ok:
unavailable()
return json_ok(request, {"status": "ok"})
@app.post("/api/v1/users", status_code=201)
async def register_user(request: Request, body: CreateUser):
user = await call_store(store.create_user, body.username, body.display_name, body.password)
if user is None:
raise ApiError(409, "conflict", "Имя пользователя занято")
return json_ok(request, user, 201)
@app.post("/api/v1/auth/sessions", status_code=201)
async def create_session(request: Request):
username, password = parse_basic(request)
session = await call_store(store.login, username, password)
if session is None:
basic_unauthorized()
request.state.user_id = session["user"]["id"]
return json_ok(request, session, 201)
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def revoke_session(request: Request):
user = await current_user(request)
request.state.user_id = user["id"]
removed = await call_store(store.revoke, request.state.token)
if not removed:
bearer_unauthorized()
return stamp(request, Response(status_code=204))
@app.get("/api/v1/users/me")
async def me(request: Request):
user = await current_user(request)
return json_ok(request, user)
@app.post("/api/v1/chats", status_code=201)
async def create_chat(request: Request):
user = await current_user(request)
payload = await read_json(request)
try:
body = CreateChat.model_validate(payload)
except ValidationError:
invalid()
try:
chat = await call_store(store.create_chat, body.title, body.member_ids, user["id"])
except ValueError:
invalid()
return json_ok(request, chat, 201)
@app.get("/api/v1/chats")
async def list_chats(request: Request):
user = await current_user(request)
limit = parse_limit(request.query_params.get("limit"))
cursor = request.query_params.get("cursor")
if cursor is not None and (not cursor or len(cursor) > 512):
invalid()
try:
items, next_cursor = await call_store(store.list_chats, user["id"], limit, cursor)
except ValueError:
invalid()
return json_ok(request, {"items": items, "next_cursor": next_cursor})
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(request: Request, chat_id: str):
user = await current_user(request)
chat = await call_store(store.get_chat, parse_chat_id(chat_id), user["id"])
if chat is None:
raise ApiError(404, "not_found", "Объект не найден")
return json_ok(request, chat)
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def create_message(request: Request, chat_id: str):
user = await current_user(request)
canonical = parse_chat_id(chat_id)
payload = await read_json(request)
key = parse_idempotency_key(request)
try:
body = CreateMessage.model_validate(payload)
except ValidationError:
invalid()
message = await call_store(store.add_message, canonical, user["id"], body.text, key)
if message is None:
raise ApiError(404, "not_found", "Объект не найден")
return json_ok(request, message, 201)
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(request: Request, chat_id: str):
user = await current_user(request)
canonical = parse_chat_id(chat_id)
limit = parse_limit(request.query_params.get("limit"))
cursor = request.query_params.get("cursor")
if cursor is not None and (not cursor or len(cursor) > 512):
invalid()
try:
result = await call_store(store.list_messages, canonical, user["id"], limit, cursor)
except ValueError:
invalid()
if result is None:
raise ApiError(404, "not_found", "Объект не найден")
items, next_cursor = result
return json_ok(request, {"items": items, "next_cursor": next_cursor})
def setup_logging():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
if __name__ == "__main__":
import uvicorn
setup_logging()
host = os.environ.get("APP_HOST", "0.0.0.0")
port = int(os.environ.get("APP_PORT", "8080"))
uvicorn.run(
app,
host=host,
port=port,
timeout_graceful_shutdown=5,
timeout_keep_alive=2,
access_log=False,
)
+112
View File
@@ -0,0 +1,112 @@
"""Однократные миграции. Запускается отдельным контейнером, не каждой репликой API."""
import logging
import os
import sys
import time
from pathlib import Path
import psycopg
from psycopg.rows import dict_row
LOGGER = logging.getLogger("migrate")
MIGRATION_LOCK = 421003
CONNECT_TIMEOUT = 3
def read_secret_file(path):
with open(path, encoding="utf-8") as handle:
return handle.read().strip()
def database_url():
path = os.environ.get("DATABASE_URL_FILE")
if path:
return read_secret_file(path)
url = os.environ.get("DATABASE_URL", "").strip()
if not url:
raise RuntimeError("DATABASE_URL_FILE")
return url
def split_sql(script):
parts = []
buf = []
for line in script.splitlines():
if line.strip().startswith("--"):
continue
buf.append(line)
if line.strip().endswith(";"):
statement = "\n".join(buf).strip()
if statement.endswith(";"):
statement = statement[:-1].strip()
if statement:
parts.append(statement)
buf = []
tail = "\n".join(buf).strip().rstrip(";").strip()
if tail:
parts.append(tail)
return parts
def wait_postgres(conninfo):
last = None
for _ in range(60):
try:
with psycopg.connect(conninfo, connect_timeout=CONNECT_TIMEOUT) as conn:
conn.execute("SELECT 1")
return
except psycopg.OperationalError as exc:
last = type(exc).__name__
time.sleep(1)
LOGGER.error("postgres not ready: %s", last)
raise SystemExit(1)
def apply(conninfo):
directory = Path(__file__).resolve().parents[1] / "migrations"
with psycopg.connect(conninfo, connect_timeout=CONNECT_TIMEOUT, row_factory=dict_row) as conn:
conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATION_LOCK,))
conn.commit()
try:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)
"""
)
conn.commit()
for path in sorted(directory.glob("*.sql")):
version = path.stem
found = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(version,),
).fetchone()
conn.rollback()
if found:
LOGGER.info("migration %s already applied", version)
continue
with conn.transaction():
for statement in split_sql(path.read_text(encoding="utf-8")):
conn.execute(statement)
conn.execute(
"INSERT INTO schema_migrations (version) VALUES (%s)",
(version,),
)
LOGGER.info("migration %s applied", version)
finally:
conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATION_LOCK,))
conn.commit()
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
conninfo = database_url()
wait_postgres(conninfo)
apply(conninfo)
return 0
if __name__ == "__main__":
sys.exit(main())
+26
View File
@@ -0,0 +1,26 @@
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHash, VerificationError, VerifyMismatchError
# Параметры ближе к учебному стенду, чем к максимальным: time=2, 19 MiB, Argon2id.
# Хеш всё равно медленный password KDF, не SHA-256 и не открытый текст.
hasher = PasswordHasher(
time_cost=2,
memory_cost=19456,
parallelism=1,
hash_len=32,
salt_len=16,
)
# Чтобы неизвестный username не отвечал заметно быстрее известного.
DUMMY_HASH = hasher.hash("dummy-password-not-a-user")
def hash_password(password):
return hasher.hash(password)
def verify_password(password, encoded):
try:
return hasher.verify(encoded, password)
except (VerifyMismatchError, VerificationError, InvalidHash):
return False
+105
View File
@@ -0,0 +1,105 @@
import re
import uuid
from pydantic import BaseModel, ConfigDict, field_validator, model_validator
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
class StrictModel(BaseModel):
model_config = ConfigDict(extra="forbid")
def _visible(value, limit):
if not isinstance(value, str) or not value.strip() or len(value) > limit:
raise ValueError("text")
return value
class CreateUser(StrictModel):
username: str
display_name: str
password: str
@field_validator("username")
@classmethod
def username_ok(cls, value):
if not isinstance(value, str) or not USERNAME_RE.fullmatch(value):
raise ValueError("username")
return value
@field_validator("display_name")
@classmethod
def display_name_ok(cls, value):
return _visible(value, 100)
@field_validator("password")
@classmethod
def password_ok(cls, value):
if not isinstance(value, str) or not value.strip():
raise ValueError("password")
# Длина в code points, не в байтах: bcrypt тут не подходит из-за усечения UTF-8.
if len(value) < 12 or len(value) > 128:
raise ValueError("password")
return value
class CreateChat(StrictModel):
title: str
member_ids: list
@field_validator("title")
@classmethod
def title_ok(cls, value):
return _visible(value, 100)
@field_validator("member_ids")
@classmethod
def member_ids_ok(cls, value):
if not isinstance(value, list) or not (1 <= len(value) <= 100):
raise ValueError("member_ids")
# Канонический UUID (нижний регистр). Иначе один и тот же id
# в разном регистре выглядит как два участника и упирается в PK.
normalized = []
seen = set()
for item in value:
if not isinstance(item, str):
raise ValueError("member_ids")
try:
canonical = str(uuid.UUID(item))
except ValueError as exc:
raise ValueError("member_ids") from exc
if canonical in seen:
raise ValueError("member_ids")
seen.add(canonical)
normalized.append(canonical)
return normalized
class CreateMessage(StrictModel):
text: str
attachment_ids: list = []
@model_validator(mode="before")
@classmethod
def fill_attachments(cls, value):
# Нет поля и явный [] — одно и то же тело для Idempotency-Key.
if not isinstance(value, dict):
return value
data = dict(value)
data.setdefault("attachment_ids", [])
return data
@field_validator("text")
@classmethod
def text_ok(cls, value):
return _visible(value, 4000)
@field_validator("attachment_ids")
@classmethod
def attachments_ok(cls, value):
# Вложения появляются в lab4. Пустой список равен пропуску поля.
# Непустой список здесь отклоняем: хранилища файлов ещё нет.
if not isinstance(value, list) or len(value) != 0:
raise ValueError("attachment_ids")
return []
+601
View File
@@ -0,0 +1,601 @@
import base64
import hashlib
import json
import logging
import os
import secrets
import socket
import time
import uuid
from datetime import datetime, timedelta, timezone
import psycopg
import redis
from psycopg.errors import ForeignKeyViolation, UniqueViolation
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool, PoolTimeout
from errors import DependencyDown, IdempotencyConflict
from passwords import DUMMY_HASH, hash_password, verify_password
LOGGER = logging.getLogger("messenger")
POOL_TIMEOUT_SECONDS = 3
STATEMENT_TIMEOUT_MS = 5000
LOCK_TIMEOUT_MS = 3000
REDIS_MAX_CONNECTIONS = 16
REDIS_SOCKET_TIMEOUT = 2
SCHEMA_VERSION = "002_idempotency"
SQL_MESSAGES_FIRST = """
SELECT id, chat_id, sender_id, body AS text, created_at
FROM messages
WHERE chat_id = %s
ORDER BY created_at, id
LIMIT %s
"""
SQL_MESSAGES_AFTER = """
SELECT id, chat_id, sender_id, body AS text, created_at
FROM messages
WHERE chat_id = %s
AND (created_at, id) > (%s, %s)
ORDER BY created_at, id
LIMIT %s
"""
SQL_MESSAGE_BY_ID = """
SELECT id, chat_id, sender_id, body AS text, created_at
FROM messages
WHERE id = %s
"""
def instance_id():
# Docker без hostname: в контейнере это id контейнера, он не меняется,
# пока живёт этот контейнер. stop-one.sh находит контейнер по этому значению.
return socket.gethostname()
def pool_max():
raw = os.environ.get("POOL_MAX", "10")
try:
value = int(raw)
except ValueError as exc:
raise RuntimeError("POOL_MAX") from exc
if not 1 <= value <= 32:
raise RuntimeError("POOL_MAX")
return value
def utc_now():
return datetime.now(timezone.utc)
def dump_time(value):
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
text = value.astimezone(timezone.utc).isoformat(timespec="microseconds")
if text.endswith("+00:00"):
text = text[:-6] + "Z"
return text
def parse_time(value):
if not isinstance(value, str) or not value.endswith("Z"):
raise ValueError("time")
return datetime.fromisoformat(value[:-1] + "+00:00")
def encode_cursor(scope, created_at, item_id):
raw = "{}|{}|{}".format(scope, created_at, item_id).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def decode_cursor(cursor, expected_scope):
if not isinstance(cursor, str) or not cursor or len(cursor) > 512:
raise ValueError("cursor")
pad = "=" * (-len(cursor) % 4)
try:
decoded = base64.urlsafe_b64decode(cursor + pad).decode("utf-8")
except (ValueError, UnicodeError) as exc:
raise ValueError("cursor") from exc
parts = decoded.split("|")
if len(parts) != 3:
raise ValueError("cursor")
scope, created_at, item_id = parts
if scope != expected_scope:
raise ValueError("cursor")
parse_time(created_at)
try:
uuid.UUID(item_id)
except ValueError as exc:
raise ValueError("cursor") from exc
return created_at, item_id
def session_key(token):
digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
return "sess:" + digest
def message_fingerprint(text):
# Канонический JSON: порядок ключей не важен, пропущенный attachment_ids равен [].
canonical = json.dumps(
{"attachment_ids": [], "text": text},
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def advisory_key(user_id, path, idem_key):
raw = "\0".join((user_id, "POST", path, idem_key)).encode("utf-8")
digest = hashlib.sha256(raw).digest()
return int.from_bytes(digest[:8], "big", signed=True)
def chat_path(chat_id):
return "/api/v1/chats/" + chat_id + "/messages"
def public_user(row):
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": dump_time(row["created_at"]),
}
def public_message(row):
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": dump_time(row["created_at"]),
}
def public_chat(row, member_ids=None):
members = member_ids if member_ids is not None else row["member_ids"]
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(item) for item in members],
"created_at": dump_time(row["created_at"]),
}
def read_secret_file(path):
with open(path, encoding="utf-8") as handle:
return handle.read().strip()
def _db_down(exc):
raise DependencyDown() from exc
class Store:
def __init__(self):
self.pool = None
self.redis = None
self.ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
self.idem_ttl = int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400"))
self.pool_size = pool_max()
self.shutting_down = False
if self.ttl < 1 or self.idem_ttl < 1:
raise RuntimeError("TTL")
kind = os.environ.get("SESSION_STORE", "redis").strip().lower()
if kind != "redis":
raise RuntimeError("SESSION_STORE")
def database_url(self):
path = os.environ.get("DATABASE_URL_FILE")
if path:
return read_secret_file(path)
url = os.environ.get("DATABASE_URL", "").strip()
if not url:
raise RuntimeError("DATABASE_URL_FILE")
return url
def redis_url(self):
path = os.environ.get("CACHE_URL_FILE")
if path:
return read_secret_file(path)
url = os.environ.get("CACHE_URL", "").strip()
if not url:
raise RuntimeError("CACHE_URL_FILE")
return url
def startup(self):
conninfo = self.database_url()
self._wait_schema(conninfo)
self.pool = ConnectionPool(
conninfo,
min_size=1,
max_size=self.pool_size,
timeout=POOL_TIMEOUT_SECONDS,
max_waiting=64,
max_lifetime=300,
kwargs={
"connect_timeout": POOL_TIMEOUT_SECONDS,
"row_factory": dict_row,
"application_name": "mtusi-lab3-" + instance_id(),
"options": "-c statement_timeout={} -c lock_timeout={} -c idle_in_transaction_session_timeout=15000".format(
STATEMENT_TIMEOUT_MS,
LOCK_TIMEOUT_MS,
),
},
open=True,
)
pool = redis.ConnectionPool.from_url(
self.redis_url(),
max_connections=REDIS_MAX_CONNECTIONS,
socket_timeout=REDIS_SOCKET_TIMEOUT,
socket_connect_timeout=REDIS_SOCKET_TIMEOUT,
health_check_interval=30,
decode_responses=True,
)
self.redis = redis.Redis(connection_pool=pool)
self._wait_redis()
LOGGER.info("ready instance=%s ttl=%s pool_max=%s", instance_id(), self.ttl, self.pool_size)
def shutdown(self):
self.shutting_down = True
if self.pool is not None:
self.pool.close()
if self.redis is not None:
self.redis.close()
def ready(self):
if self.shutting_down or self.pool is None or self.redis is None:
return False
try:
with self.pool.connection(timeout=POOL_TIMEOUT_SECONDS) as conn:
row = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(SCHEMA_VERSION,),
).fetchone()
if row is None:
return False
self.redis.ping()
except Exception:
LOGGER.warning("ready check failed")
return False
return True
def _wait_redis(self):
last = None
for _ in range(60):
try:
self.redis.ping()
return
except redis.RedisError as exc:
last = type(exc).__name__
time.sleep(1)
LOGGER.error("redis not ready: %s", last)
raise SystemExit(1)
def _wait_schema(self, conninfo):
# Схему накатывает сервис migrate. Реплики только ждут её, не применяют сами.
last = None
for _ in range(90):
try:
with psycopg.connect(conninfo, connect_timeout=POOL_TIMEOUT_SECONDS, row_factory=dict_row) as conn:
row = conn.execute(
"SELECT 1 FROM schema_migrations WHERE version = %s",
(SCHEMA_VERSION,),
).fetchone()
if row is not None:
return
last = "migration missing"
except psycopg.Error as exc:
last = type(exc).__name__
time.sleep(1)
LOGGER.error("schema not ready: %s", last)
raise SystemExit(1)
def _connect(self):
try:
return self.pool.connection(timeout=POOL_TIMEOUT_SECONDS)
except PoolTimeout as exc:
_db_down(exc)
def create_user(self, username, display_name, password):
password_hash = hash_password(password)
user_id = uuid.uuid4()
created = utc_now()
try:
with self._connect() as conn:
with conn.transaction():
row = conn.execute(
"""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (username) DO NOTHING
RETURNING id, username, display_name, created_at
""",
(user_id, username, display_name, password_hash, created),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_user(row)
def login(self, username, password):
try:
with self._connect() as conn:
row = conn.execute(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE username = %s
""",
(username,),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
verify_password(password, DUMMY_HASH)
return None
if not verify_password(password, row["password_hash"]):
return None
return self._issue(public_user(row))
def _issue(self, user):
token = secrets.token_urlsafe(32)
expires = utc_now() + timedelta(seconds=self.ttl)
payload = json.dumps(
{"user_id": user["id"], "expires_at": dump_time(expires)},
separators=(",", ":"),
)
# pxat — абсолютное время. Рестарт Redis не сдвигает срок.
# В значении тоже лежит expires_at: даже если TTL ключа разъедется, сессия кончится вовремя.
try:
self.redis.set(session_key(token), payload, pxat=int(expires.timestamp() * 1000))
except redis.RedisError as exc:
raise DependencyDown() from exc
return {
"token": token,
"token_type": "Bearer",
"expires_at": dump_time(expires),
"user": user,
}
def user_for_token(self, token):
key = session_key(token)
try:
raw = self.redis.get(key)
except redis.RedisError as exc:
raise DependencyDown() from exc
if not raw:
return None
try:
payload = json.loads(raw)
expires = parse_time(payload["expires_at"])
user_id = payload["user_id"]
uuid.UUID(user_id)
except (ValueError, KeyError, TypeError):
return None
if utc_now() >= expires:
try:
self.redis.delete(key)
except redis.RedisError as exc:
raise DependencyDown() from exc
return None
try:
with self._connect() as conn:
row = conn.execute(
"""
SELECT id, username, display_name, created_at
FROM users
WHERE id = %s
""",
(user_id,),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_user(row)
def revoke(self, token):
try:
deleted = self.redis.delete(session_key(token))
except redis.RedisError as exc:
raise DependencyDown() from exc
return deleted == 1
def create_chat(self, title, member_ids, caller_id):
try:
caller_uuid = uuid.UUID(str(caller_id))
member_uuids = []
seen = set()
for item in member_ids:
member_uuid = uuid.UUID(str(item))
if member_uuid in seen:
raise ValueError("members")
seen.add(member_uuid)
member_uuids.append(member_uuid)
except ValueError as exc:
raise ValueError("members") from exc
if caller_uuid not in seen:
raise ValueError("members")
chat_id = uuid.uuid4()
created = utc_now()
canonical_members = [str(item) for item in member_uuids]
try:
with self._connect() as conn:
try:
with conn.transaction():
conn.execute(
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
(chat_id, title, created),
)
for ordinal, member_id in enumerate(member_uuids):
conn.execute(
"""
INSERT INTO chat_members (chat_id, user_id, ordinal)
VALUES (%s, %s, %s)
""",
(chat_id, member_id, ordinal),
)
row = conn.execute(
"SELECT id, title, created_at FROM chats WHERE id = %s",
(chat_id,),
).fetchone()
except ForeignKeyViolation as exc:
raise ValueError("members") from exc
except UniqueViolation as exc:
raise ValueError("members") from exc
except psycopg.OperationalError as exc:
_db_down(exc)
return public_chat(row, canonical_members)
def _member(self, conn, chat_id, user_id):
return conn.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, user_id),
).fetchone()
def get_chat(self, chat_id, user_id):
try:
with self._connect() as conn:
if self._member(conn, chat_id, user_id) is None:
return None
row = conn.execute(
"""
SELECT c.id, c.title, c.created_at,
array_agg(m.user_id ORDER BY m.ordinal) AS member_ids
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE c.id = %s
GROUP BY c.id
""",
(chat_id,),
).fetchone()
except psycopg.OperationalError as exc:
_db_down(exc)
if row is None:
return None
return public_chat(row)
def list_chats(self, user_id, limit, cursor):
after = None
if cursor is not None:
created_at, item_id = decode_cursor(cursor, "chats:" + user_id)
after = (parse_time(created_at), uuid.UUID(item_id))
sql = """
SELECT c.id, c.title, c.created_at,
array_agg(m.user_id ORDER BY m.ordinal) AS member_ids
FROM chats c
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = %s
JOIN chat_members m ON m.chat_id = c.id
"""
params = [user_id]
if after is not None:
sql += " WHERE (c.created_at, c.id) > (%s, %s)"
params.extend(after)
sql += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT %s"
params.append(limit + 1)
try:
with self._connect() as conn:
rows = conn.execute(sql, params).fetchall()
except psycopg.OperationalError as exc:
_db_down(exc)
page = [public_chat(row) for row in rows[:limit]]
if len(rows) > limit and page:
last = page[-1]
return page, encode_cursor("chats:" + user_id, last["created_at"], last["id"])
return page, None
def add_message(self, chat_id, sender_id, text, idem_key):
# Один ключ сериализуется между репликами через advisory lock в той же
# транзакции, где INSERT сообщения. Откат не оставляет ключ занятым.
path = chat_path(chat_id)
digest = message_fingerprint(text)
lock_key = advisory_key(sender_id, path, idem_key)
message_id = uuid.uuid4()
try:
with self._connect() as conn:
with conn.transaction():
# Иначе lock_timeout сессии (3 с) оборвёт очередь одинаковых ключей.
conn.execute("SET LOCAL lock_timeout = '15s'")
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock_key,))
if self._member(conn, chat_id, sender_id) is None:
return None
existing = conn.execute(
"""
SELECT request_hash, message_id,
created_at >= now() - make_interval(secs => %s) AS fresh
FROM idempotency_keys
WHERE user_id = %s AND http_method = 'POST'
AND request_path = %s AND idem_key = %s
""",
(self.idem_ttl, sender_id, path, idem_key),
).fetchone()
if existing is not None and existing["fresh"]:
if existing["request_hash"] != digest:
raise IdempotencyConflict()
row = conn.execute(SQL_MESSAGE_BY_ID, (existing["message_id"],)).fetchone()
if row is None:
raise RuntimeError("idempotency target missing")
return public_message(row)
if existing is not None:
conn.execute(
"""
DELETE FROM idempotency_keys
WHERE user_id = %s AND http_method = 'POST'
AND request_path = %s AND idem_key = %s
""",
(sender_id, path, idem_key),
)
row = conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, body, created_at)
VALUES (%s, %s, %s, %s, clock_timestamp())
RETURNING id, chat_id, sender_id, body AS text, created_at
""",
(message_id, chat_id, sender_id, text),
).fetchone()
conn.execute(
"""
INSERT INTO idempotency_keys (
user_id, http_method, request_path, idem_key,
request_hash, message_id, created_at
)
VALUES (%s, 'POST', %s, %s, %s, %s, clock_timestamp())
""",
(sender_id, path, idem_key, digest, row["id"]),
)
return public_message(row)
except psycopg.OperationalError as exc:
_db_down(exc)
def list_messages(self, chat_id, user_id, limit, cursor):
after = None
if cursor is not None:
created_at, item_id = decode_cursor(cursor, chat_id)
after = (parse_time(created_at), uuid.UUID(item_id))
try:
with self._connect() as conn:
if self._member(conn, chat_id, user_id) is None:
return None
if after is None:
rows = conn.execute(SQL_MESSAGES_FIRST, (chat_id, limit + 1)).fetchall()
else:
rows = conn.execute(
SQL_MESSAGES_AFTER,
(chat_id, after[0], after[1], limit + 1),
).fetchall()
except psycopg.OperationalError as exc:
_db_down(exc)
page = [public_message(row) for row in rows[:limit]]
if len(rows) > limit and page:
last = page[-1]
return page, encode_cursor(chat_id, last["created_at"], last["id"])
return page, None