feat: перевести API на password/Basic/Bearer и PostgreSQL с Redis-кэшем
Co-authored-by: aider (deepseek/deepseek-chat) <aider@aider.chat>
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
"""Пул соединений PostgreSQL и применение миграций."""
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
logger = logging.getLogger("messenger.db")
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations"
|
||||
|
||||
|
||||
def make_pool() -> ConnectionPool:
|
||||
dsn = os.environ.get("DATABASE_URL")
|
||||
if not dsn:
|
||||
raise RuntimeError("DATABASE_URL is not set")
|
||||
pool = ConnectionPool(
|
||||
conninfo=dsn,
|
||||
min_size=int(os.environ.get("DB_POOL_MIN", "1")),
|
||||
max_size=int(os.environ.get("DB_POOL_MAX", "10")),
|
||||
timeout=float(os.environ.get("DB_CONNECT_TIMEOUT", "3")),
|
||||
kwargs={"autocommit": False},
|
||||
open=False,
|
||||
)
|
||||
pool.open(wait=True, timeout=float(os.environ.get("DB_CONNECT_TIMEOUT", "3")))
|
||||
return pool
|
||||
|
||||
|
||||
def apply_migrations(pool: ConnectionPool) -> None:
|
||||
"""Идемпотентно применяет *.sql из migrations/ в лексикографическом порядке."""
|
||||
with pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
||||
" version TEXT PRIMARY KEY,"
|
||||
" applied_at TIMESTAMPTZ NOT NULL DEFAULT now())"
|
||||
)
|
||||
conn.commit()
|
||||
cur.execute("SELECT version FROM schema_migrations")
|
||||
applied = {row[0] for row in cur.fetchall()}
|
||||
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
|
||||
version = path.stem
|
||||
if version in applied:
|
||||
continue
|
||||
logger.info("applying migration %s", version)
|
||||
sql = path.read_text(encoding="utf-8")
|
||||
with conn.transaction():
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql)
|
||||
cur.execute(
|
||||
"INSERT INTO schema_migrations(version) VALUES (%s)", (version,)
|
||||
)
|
||||
+128
-46
@@ -1,10 +1,15 @@
|
||||
"""HTTP-обработчики FastAPI для lab1."""
|
||||
"""HTTP-обработчики FastAPI для lab2: Basic/Bearer, PostgreSQL, Redis-кэш сессий."""
|
||||
import base64
|
||||
import binascii
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Body, Header, Query, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .errors import ApiError
|
||||
from .security import hash_password, verify_password
|
||||
from .sessions import SessionStore
|
||||
from .store import Store
|
||||
from .validation import (
|
||||
encode_cursor,
|
||||
@@ -18,19 +23,48 @@ from .validation import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def get_store(request: Request) -> Store:
|
||||
return request.app.state.store
|
||||
|
||||
|
||||
def current_user_id(request: Request, x_user_id: str | None) -> str:
|
||||
"""lab1: X-User-Id — идентификатор существующего пользователя."""
|
||||
if not x_user_id:
|
||||
raise ApiError(401, "unauthorized", "Требуется X-User-Id")
|
||||
store = get_store(request)
|
||||
if store.get_user(x_user_id) is None:
|
||||
raise ApiError(401, "unauthorized", "Неизвестный пользователь")
|
||||
return x_user_id
|
||||
def get_sessions(request: Request) -> SessionStore:
|
||||
return request.app.state.sessions
|
||||
|
||||
|
||||
def _unauthorized(message: str, challenge: str) -> ApiError:
|
||||
err = ApiError(401, "unauthorized", message)
|
||||
err.challenge = challenge # type: ignore[attr-defined]
|
||||
return err
|
||||
|
||||
|
||||
def current_user_id(request: Request, authorization: str | None) -> str:
|
||||
"""lab2: только Bearer. X-User-Id игнорируется."""
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise _unauthorized("Требуется Bearer-токен", BEARER_CHALLENGE)
|
||||
token = authorization[7:].strip()
|
||||
if not token:
|
||||
raise _unauthorized("Пустой Bearer-токен", BEARER_CHALLENGE)
|
||||
user_id = get_sessions(request).resolve(token)
|
||||
if user_id is None:
|
||||
raise _unauthorized("Недействительная сессия", BEARER_CHALLENGE)
|
||||
return user_id
|
||||
|
||||
|
||||
def _parse_basic(authorization: str | None) -> tuple[str, str]:
|
||||
if not authorization or not authorization.lower().startswith("basic "):
|
||||
raise _unauthorized("Требуется Basic-аутентификация", BASIC_CHALLENGE)
|
||||
try:
|
||||
decoded = base64.b64decode(authorization[6:].strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
raise _unauthorized("Некорректный Basic", BASIC_CHALLENGE)
|
||||
if ":" not in decoded:
|
||||
raise _unauthorized("Некорректный Basic", BASIC_CHALLENGE)
|
||||
username, password = decoded.split(":", 1)
|
||||
return username, password
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
@@ -39,25 +73,78 @@ def health_live() -> dict[str, str]:
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
def health_ready() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
def health_ready(request: Request) -> JSONResponse:
|
||||
"""Ready, если доступна БД (обязательный синхронный путь). Redis — кэш."""
|
||||
try:
|
||||
with get_store(request).pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
cur.fetchone()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger_ready = logging.getLogger("messenger.ready")
|
||||
logger_ready.warning("readiness failed: %s", type(exc).__name__)
|
||||
raise ApiError(503, "unavailable", "Зависимость недоступна")
|
||||
return JSONResponse({"status": "ok"})
|
||||
|
||||
|
||||
@router.post("/api/v1/users", status_code=201)
|
||||
def register_user(request: Request, body: Any = Body(...)) -> JSONResponse:
|
||||
username, display_name = validate_create_user(body)
|
||||
username, display_name, password = validate_create_user(body)
|
||||
store = get_store(request)
|
||||
user = store.create_user(username, display_name)
|
||||
user = store.create_user(username, display_name, hash_password(password))
|
||||
if user is None:
|
||||
raise ApiError(409, "conflict", "username уже занят")
|
||||
return JSONResponse(user, status_code=201)
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/sessions", status_code=201)
|
||||
def create_session(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> JSONResponse:
|
||||
username, password = _parse_basic(authorization)
|
||||
store = get_store(request)
|
||||
found = store.get_user_by_username(username)
|
||||
if found is None:
|
||||
# Одинаковый 401 для неверного username и пароля.
|
||||
raise _unauthorized("Неверные учётные данные", BASIC_CHALLENGE)
|
||||
user, password_hash = found
|
||||
if not verify_password(password_hash, password):
|
||||
raise _unauthorized("Неверные учётные данные", BASIC_CHALLENGE)
|
||||
session = get_sessions(request).create(user["id"])
|
||||
return JSONResponse(
|
||||
{
|
||||
"token": session["token"],
|
||||
"token_type": "Bearer",
|
||||
"expires_at": session["expires_at"],
|
||||
"user": user,
|
||||
},
|
||||
status_code=201,
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def revoke_session(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> JSONResponse:
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise _unauthorized("Требуется Bearer-токен", BEARER_CHALLENGE)
|
||||
token = authorization[7:].strip()
|
||||
if not token or get_sessions(request).resolve(token) is None:
|
||||
raise _unauthorized("Недействительная сессия", BEARER_CHALLENGE)
|
||||
get_sessions(request).revoke(token)
|
||||
return JSONResponse(status_code=204)
|
||||
|
||||
|
||||
@router.get("/api/v1/users/me")
|
||||
def current_user(request: Request, x_user_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
user_id = current_user_id(request, x_user_id)
|
||||
def current_user(
|
||||
request: Request, authorization: str | None = Header(default=None)
|
||||
) -> dict[str, Any]:
|
||||
user_id = current_user_id(request, authorization)
|
||||
user = get_store(request).get_user(user_id)
|
||||
assert user is not None
|
||||
if user is None:
|
||||
raise _unauthorized("Недействительная сессия", BEARER_CHALLENGE)
|
||||
return user
|
||||
|
||||
|
||||
@@ -65,9 +152,9 @@ def current_user(request: Request, x_user_id: str | None = Header(default=None))
|
||||
def create_chat(
|
||||
request: Request,
|
||||
body: Any = Body(...),
|
||||
x_user_id: str | None = Header(default=None),
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> JSONResponse:
|
||||
caller = current_user_id(request, x_user_id)
|
||||
caller = current_user_id(request, authorization)
|
||||
title, member_ids = validate_create_chat(body, caller)
|
||||
store = get_store(request)
|
||||
for mid in member_ids:
|
||||
@@ -82,33 +169,33 @@ def list_chats(
|
||||
request: Request,
|
||||
limit: str | None = Query(default=None),
|
||||
cursor: str | None = Query(default=None),
|
||||
x_user_id: str | None = Header(default=None),
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> dict[str, Any]:
|
||||
caller = current_user_id(request, x_user_id)
|
||||
caller = current_user_id(request, authorization)
|
||||
page_size = parse_limit(limit)
|
||||
scope = f"chats:{caller}"
|
||||
after = parse_cursor(cursor, scope)
|
||||
items = get_store(request).list_chats_for(caller)
|
||||
if after is not None:
|
||||
items = [c for c in items if (c["created_at"], c["id"]) > after]
|
||||
page = items[:page_size]
|
||||
items, has_more = get_store(request).list_chats_for(caller, page_size, after)
|
||||
next_cursor = None
|
||||
if len(items) > page_size and page:
|
||||
last = page[-1]
|
||||
if has_more and items:
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(last["created_at"], last["id"], scope)
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}")
|
||||
def get_chat(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
x_user_id: str | None = Header(default=None),
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> dict[str, Any]:
|
||||
caller = current_user_id(request, x_user_id)
|
||||
caller = current_user_id(request, authorization)
|
||||
chat_id = validate_chat_id(chat_id)
|
||||
chat = get_store(request).get_chat(chat_id)
|
||||
if chat is None or caller not in chat["member_ids"]:
|
||||
store = get_store(request)
|
||||
if not store.is_member(chat_id, caller):
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
chat = store.get_chat(chat_id)
|
||||
if chat is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
return chat
|
||||
|
||||
@@ -118,13 +205,12 @@ def create_message(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
body: Any = Body(...),
|
||||
x_user_id: str | None = Header(default=None),
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> JSONResponse:
|
||||
caller = current_user_id(request, x_user_id)
|
||||
caller = current_user_id(request, authorization)
|
||||
chat_id = validate_chat_id(chat_id)
|
||||
store = get_store(request)
|
||||
chat = store.get_chat(chat_id)
|
||||
if chat is None or caller not in chat["member_ids"]:
|
||||
if not store.is_member(chat_id, caller):
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
text = validate_create_message(body)
|
||||
message = store.add_message(chat_id, caller, text)
|
||||
@@ -137,23 +223,19 @@ def list_messages(
|
||||
request: Request,
|
||||
limit: str | None = Query(default=None),
|
||||
cursor: str | None = Query(default=None),
|
||||
x_user_id: str | None = Header(default=None),
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> dict[str, Any]:
|
||||
caller = current_user_id(request, x_user_id)
|
||||
caller = current_user_id(request, authorization)
|
||||
chat_id = validate_chat_id(chat_id)
|
||||
store = get_store(request)
|
||||
chat = store.get_chat(chat_id)
|
||||
if chat is None or caller not in chat["member_ids"]:
|
||||
if not store.is_member(chat_id, caller):
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
page_size = parse_limit(limit)
|
||||
scope = f"messages:{chat_id}"
|
||||
after = parse_cursor(cursor, scope)
|
||||
items = store.list_messages(chat_id)
|
||||
if after is not None:
|
||||
items = [m for m in items if (m["created_at"], m["id"]) > after]
|
||||
page = items[:page_size]
|
||||
items, has_more = store.list_messages(chat_id, page_size, after)
|
||||
next_cursor = None
|
||||
if len(items) > page_size and page:
|
||||
last = page[-1]
|
||||
if has_more and items:
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(last["created_at"], last["id"], scope)
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
+26
-3
@@ -3,13 +3,16 @@ import logging
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import redis
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .db import apply_migrations, make_pool
|
||||
from .errors import ApiError, error_body
|
||||
from .handlers import router
|
||||
from .sessions import SessionStore
|
||||
from .store import Store
|
||||
|
||||
logging.basicConfig(
|
||||
@@ -18,8 +21,24 @@ logging.basicConfig(
|
||||
)
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger", version="1.1.0")
|
||||
app.state.store = Store()
|
||||
app = FastAPI(title="MTUSI Messenger", version="1.2.0")
|
||||
|
||||
_pool = make_pool()
|
||||
apply_migrations(_pool)
|
||||
|
||||
_cache: redis.Redis | None = None
|
||||
_cache_url = os.environ.get("CACHE_URL")
|
||||
if _cache_url:
|
||||
_cache = redis.Redis.from_url(
|
||||
_cache_url,
|
||||
socket_timeout=float(os.environ.get("REDIS_SOCKET_TIMEOUT", "1")),
|
||||
socket_connect_timeout=float(os.environ.get("REDIS_SOCKET_TIMEOUT", "1")),
|
||||
decode_responses=False,
|
||||
)
|
||||
|
||||
app.state.pool = _pool
|
||||
app.state.store = Store(_pool)
|
||||
app.state.sessions = SessionStore(_pool, _cache)
|
||||
app.include_router(router)
|
||||
|
||||
|
||||
@@ -41,10 +60,14 @@ async def request_id_middleware(request: Request, call_next):
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, exc: ApiError) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
headers = {"X-Request-Id": request_id}
|
||||
challenge = getattr(exc, "challenge", None)
|
||||
if challenge:
|
||||
headers["WWW-Authenticate"] = challenge
|
||||
return JSONResponse(
|
||||
error_body(exc.code, exc.message, request_id),
|
||||
status_code=exc.status,
|
||||
headers={"X-Request-Id": request_id},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Хеширование паролей (Argon2id) и генерация opaque-токенов сессий."""
|
||||
import hashlib
|
||||
import secrets
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
|
||||
|
||||
_hasher = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return _hasher.verify(password_hash, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
"""256 бит энтропии, URL-safe."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_hash(token: str) -> str:
|
||||
"""В БД/Redis храним только SHA-256 от токена, не сам токен."""
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
"""Сессии: PostgreSQL — источник истины, Redis — кэш с TTL.
|
||||
|
||||
При недоступности Redis работаем напрямую с БД (не принимаем анонимов).
|
||||
При logout инвалидируем и БД, и кэш.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
import redis
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from .security import new_token, token_hash
|
||||
|
||||
logger = logging.getLogger("messenger.sessions")
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _ttl_seconds() -> int:
|
||||
return int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
|
||||
class SessionStore:
|
||||
def __init__(self, pool: ConnectionPool, cache: redis.Redis | None) -> None:
|
||||
self.pool = pool
|
||||
self.cache = cache
|
||||
|
||||
# --- кэш --------------------------------------------------------------
|
||||
def _cache_get(self, th: str) -> dict[str, Any] | None:
|
||||
if self.cache is None:
|
||||
return None
|
||||
try:
|
||||
raw = self.cache.hgetall("session:" + th)
|
||||
except redis.RedisError as exc:
|
||||
logger.warning("redis get failed: %s", type(exc).__name__)
|
||||
return None
|
||||
if not raw:
|
||||
return None
|
||||
return {
|
||||
"user_id": raw[b"user_id"].decode(),
|
||||
"expires_at": raw[b"expires_at"].decode(),
|
||||
}
|
||||
|
||||
def _cache_put(self, th: str, user_id: str, expires_at: datetime) -> None:
|
||||
if self.cache is None:
|
||||
return
|
||||
ttl = max(1, int((expires_at - _now()).total_seconds()))
|
||||
try:
|
||||
pipe = self.cache.pipeline()
|
||||
pipe.hset(
|
||||
"session:" + th,
|
||||
mapping={
|
||||
"user_id": user_id,
|
||||
"expires_at": expires_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
},
|
||||
)
|
||||
pipe.expire("session:" + th, ttl)
|
||||
pipe.execute()
|
||||
except redis.RedisError as exc:
|
||||
logger.warning("redis put failed: %s", type(exc).__name__)
|
||||
|
||||
def _cache_del(self, th: str) -> None:
|
||||
if self.cache is None:
|
||||
return
|
||||
try:
|
||||
self.cache.delete("session:" + th)
|
||||
except redis.RedisError as exc:
|
||||
logger.warning("redis del failed: %s", type(exc).__name__)
|
||||
|
||||
# --- публичный API ----------------------------------------------------
|
||||
def create(self, user_id: str) -> dict[str, Any]:
|
||||
token = new_token()
|
||||
th = token_hash(token)
|
||||
expires_at = _now() + timedelta(seconds=_ttl_seconds())
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO sessions(token_hash, user_id, created_at, expires_at)"
|
||||
" VALUES (%s, %s, now(), %s)",
|
||||
(th, user_id, expires_at),
|
||||
)
|
||||
conn.commit()
|
||||
self._cache_put(th, user_id, expires_at)
|
||||
return {
|
||||
"token": token,
|
||||
"expires_at": expires_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
}
|
||||
|
||||
def resolve(self, token: str) -> str | None:
|
||||
"""Возвращает user_id для действующей сессии или None."""
|
||||
th = token_hash(token)
|
||||
cached = self._cache_get(th)
|
||||
if cached is not None:
|
||||
try:
|
||||
exp = datetime.strptime(cached["expires_at"], "%Y-%m-%dT%H:%M:%SZ").replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
except ValueError:
|
||||
exp = None
|
||||
if exp is not None and exp > _now():
|
||||
return cached["user_id"]
|
||||
self._cache_del(th)
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT user_id, expires_at FROM sessions WHERE token_hash = %s",
|
||||
(th,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
user_id, expires_at = row
|
||||
if expires_at <= _now():
|
||||
self.revoke(token)
|
||||
return None
|
||||
self._cache_put(th, str(user_id), expires_at)
|
||||
return str(user_id)
|
||||
|
||||
def revoke(self, token: str) -> None:
|
||||
th = token_hash(token)
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM sessions WHERE token_hash = %s", (th,))
|
||||
conn.commit()
|
||||
self._cache_del(th)
|
||||
+174
-59
@@ -1,9 +1,11 @@
|
||||
"""Потокобезопасное in-memory хранилище пользователей, чатов и сообщений."""
|
||||
import threading
|
||||
"""Хранилище на PostgreSQL: пользователи, чаты, участники, сообщения."""
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psycopg
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
"""RFC 3339 UTC с суффиксом Z, секунды — как в примерах контракта."""
|
||||
@@ -14,75 +16,188 @@ def new_id() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
class Store:
|
||||
"""Все данные живут в памяти одного процесса и исчезают при рестарте."""
|
||||
def _iso(dt: datetime) -> str:
|
||||
return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.RLock()
|
||||
self.users: dict[str, dict[str, Any]] = {}
|
||||
self.usernames: dict[str, str] = {}
|
||||
self.chats: dict[str, dict[str, Any]] = {}
|
||||
self.messages: dict[str, list[dict[str, Any]]] = {}
|
||||
|
||||
def _user_row(row: tuple) -> dict[str, Any]:
|
||||
uid, username, display_name, created_at = row
|
||||
return {
|
||||
"id": str(uid),
|
||||
"username": username,
|
||||
"display_name": display_name,
|
||||
"created_at": _iso(created_at),
|
||||
}
|
||||
|
||||
|
||||
def _chat_row(row: tuple, member_ids: list[str]) -> dict[str, Any]:
|
||||
cid, title, created_at = row
|
||||
return {
|
||||
"id": str(cid),
|
||||
"title": title,
|
||||
"member_ids": member_ids,
|
||||
"created_at": _iso(created_at),
|
||||
}
|
||||
|
||||
|
||||
def _message_row(row: tuple) -> dict[str, Any]:
|
||||
mid, chat_id, sender_id, text, created_at = row
|
||||
return {
|
||||
"id": str(mid),
|
||||
"chat_id": str(chat_id),
|
||||
"sender_id": str(sender_id),
|
||||
"text": text,
|
||||
"created_at": _iso(created_at),
|
||||
}
|
||||
|
||||
|
||||
class Store:
|
||||
"""Все данные в PostgreSQL; соединения берутся из пула."""
|
||||
|
||||
def __init__(self, pool: ConnectionPool) -> None:
|
||||
self.pool = pool
|
||||
|
||||
# --- пользователи -----------------------------------------------------
|
||||
def create_user(self, username: str, display_name: str) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
if username in self.usernames:
|
||||
return None # сигнал конфликта
|
||||
user = {
|
||||
"id": new_id(),
|
||||
"username": username,
|
||||
"display_name": display_name,
|
||||
"created_at": utc_now(),
|
||||
}
|
||||
self.users[user["id"]] = user
|
||||
self.usernames[username] = user["id"]
|
||||
return dict(user)
|
||||
def create_user(
|
||||
self, username: str, display_name: str, password_hash: str
|
||||
) -> dict[str, Any] | None:
|
||||
user_id = new_id()
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO users(id, username, display_name, password_hash, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, now())"
|
||||
" RETURNING id, username, display_name, created_at",
|
||||
(user_id, username, display_name, password_hash),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
except psycopg.errors.UniqueViolation:
|
||||
return None
|
||||
return _user_row(row)
|
||||
|
||||
def get_user(self, user_id: str) -> dict[str, Any] | None:
|
||||
with self._lock:
|
||||
user = self.users.get(user_id)
|
||||
return dict(user) if user else None
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _user_row(row) if row else None
|
||||
|
||||
def get_user_by_username(self, username: str) -> tuple[dict[str, Any], str] | None:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash"
|
||||
" FROM users WHERE username = %s",
|
||||
(username,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return _user_row(row[:4]), row[4]
|
||||
|
||||
# --- чаты -------------------------------------------------------------
|
||||
def create_chat(self, title: str, member_ids: list[str]) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
chat = {
|
||||
"id": new_id(),
|
||||
"title": title,
|
||||
"member_ids": list(member_ids),
|
||||
"created_at": utc_now(),
|
||||
}
|
||||
self.chats[chat["id"]] = chat
|
||||
self.messages[chat["id"]] = []
|
||||
return dict(chat)
|
||||
chat_id = new_id()
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO chats(id, title, created_at) VALUES (%s, %s, now())"
|
||||
" RETURNING id, title, created_at",
|
||||
(chat_id, title),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members(chat_id, user_id) VALUES (%s, %s)",
|
||||
[(chat_id, mid) for mid in member_ids],
|
||||
)
|
||||
return _chat_row(row, list(member_ids))
|
||||
|
||||
def _members(self, cur, chat_id: str) -> list[str]:
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||
(chat_id,),
|
||||
)
|
||||
return [str(r[0]) for r in cur.fetchall()]
|
||||
|
||||
def get_chat(self, chat_id: str) -> dict[str, Any] | None:
|
||||
with self._lock:
|
||||
chat = self.chats.get(chat_id)
|
||||
return dict(chat) if chat else None
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, title, created_at FROM chats WHERE id = %s", (chat_id,)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
members = self._members(cur, chat_id)
|
||||
return _chat_row(row, members)
|
||||
|
||||
def list_chats_for(self, user_id: str) -> list[dict[str, Any]]:
|
||||
with self._lock:
|
||||
items = [dict(c) for c in self.chats.values() if user_id in c["member_ids"]]
|
||||
items.sort(key=lambda c: (c["created_at"], c["id"]))
|
||||
return items
|
||||
def is_member(self, chat_id: str, user_id: str) -> bool:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, user_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
|
||||
def list_chats_for(
|
||||
self, user_id: str, limit: int, after: tuple[str, str] | None
|
||||
) -> tuple[list[dict[str, Any]], bool]:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
sql = (
|
||||
"SELECT c.id, c.title, c.created_at FROM chats c"
|
||||
" JOIN chat_members m ON m.chat_id = c.id"
|
||||
" WHERE m.user_id = %s"
|
||||
)
|
||||
params: list[Any] = [user_id]
|
||||
if after is not None:
|
||||
sql += " AND (c.created_at, c.id) > (%s, %s)"
|
||||
params.extend(after)
|
||||
sql += " ORDER BY c.created_at, c.id LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
cur.execute(sql, params)
|
||||
rows = cur.fetchall()
|
||||
items = []
|
||||
for row in rows[:limit]:
|
||||
items.append(_chat_row(row, self._members(cur, str(row[0]))))
|
||||
return items, len(rows) > limit
|
||||
|
||||
# --- сообщения --------------------------------------------------------
|
||||
def add_message(self, chat_id: str, sender_id: str, text: str) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
message = {
|
||||
"id": new_id(),
|
||||
"chat_id": chat_id,
|
||||
"sender_id": sender_id,
|
||||
"text": text,
|
||||
"created_at": utc_now(),
|
||||
}
|
||||
self.messages.setdefault(chat_id, []).append(message)
|
||||
return dict(message)
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO messages(id, chat_id, sender_id, text, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, now())"
|
||||
" RETURNING id, chat_id, sender_id, text, created_at",
|
||||
(new_id(), chat_id, sender_id, text),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return _message_row(row)
|
||||
|
||||
def list_messages(self, chat_id: str) -> list[dict[str, Any]]:
|
||||
with self._lock:
|
||||
items = [dict(m) for m in self.messages.get(chat_id, [])]
|
||||
items.sort(key=lambda m: (m["created_at"], m["id"]))
|
||||
return items
|
||||
def list_messages(
|
||||
self, chat_id: str, limit: int, after: tuple[str, str] | None
|
||||
) -> tuple[list[dict[str, Any]], bool]:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
sql = (
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s"
|
||||
)
|
||||
params: list[Any] = [chat_id]
|
||||
if after is not None:
|
||||
sql += " AND (created_at, id) > (%s, %s)"
|
||||
params.extend(after)
|
||||
sql += " ORDER BY created_at, id LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
cur.execute(sql, params)
|
||||
rows = cur.fetchall()
|
||||
return [_message_row(r) for r in rows[:limit]], len(rows) > limit
|
||||
|
||||
+13
-13
@@ -8,10 +8,6 @@ from .errors import ApiError
|
||||
|
||||
USERNAME_RE = re.compile(r"\A[a-z0-9_]{3,32}\Z")
|
||||
|
||||
# Уникальный идентификатор жизни процесса: cursors, выданные до рестарта,
|
||||
# становятся недействительными.
|
||||
CURSOR_EPOCH = uuid.uuid4().hex
|
||||
|
||||
|
||||
def _is_blank(value: str) -> bool:
|
||||
return value.strip() == ""
|
||||
@@ -28,16 +24,19 @@ def reject_extra(body: dict[str, Any], allowed: set[str]) -> None:
|
||||
raise ApiError(400, "invalid_request", "Неизвестные поля в теле запроса")
|
||||
|
||||
|
||||
def validate_create_user(body: Any) -> tuple[str, str]:
|
||||
def validate_create_user(body: Any) -> tuple[str, str, str]:
|
||||
body = require_object(body)
|
||||
reject_extra(body, {"username", "display_name"})
|
||||
reject_extra(body, {"username", "display_name", "password"})
|
||||
username = body.get("username")
|
||||
display_name = body.get("display_name")
|
||||
password = body.get("password")
|
||||
if not isinstance(username, str) or not USERNAME_RE.match(username):
|
||||
raise ApiError(400, "invalid_request", "Некорректный username")
|
||||
if not isinstance(display_name, str) or not (1 <= len(display_name) <= 100) or _is_blank(display_name):
|
||||
raise ApiError(400, "invalid_request", "Некорректный display_name")
|
||||
return username, display_name
|
||||
if not isinstance(password, str) or not (12 <= len(password) <= 128):
|
||||
raise ApiError(400, "invalid_request", "Пароль должен быть 12..128 символов")
|
||||
return username, display_name, password
|
||||
|
||||
|
||||
def validate_create_chat(body: Any, caller_id: str) -> tuple[str, list[str]]:
|
||||
@@ -96,9 +95,10 @@ def parse_limit(raw: str | None, default: int = 50) -> int:
|
||||
|
||||
|
||||
def parse_cursor(raw: str | None, scope: str) -> tuple[str, str] | None:
|
||||
"""Cursor — непрозрачная строка base64url от 'epoch|scope|created_at|id'.
|
||||
"""Cursor — непрозрачная строка base64url от 'scope|created_at|id'.
|
||||
|
||||
Cursor привязан к ресурсу (scope) и к жизни процесса (epoch).
|
||||
Cursor привязан к ресурсу (scope). Значения created_at/id — из БД,
|
||||
поэтому cursor переживает рестарт процесса.
|
||||
"""
|
||||
if raw is None:
|
||||
return None
|
||||
@@ -107,10 +107,10 @@ def parse_cursor(raw: str | None, scope: str) -> tuple[str, str] | None:
|
||||
except Exception:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
parts = decoded.split("|")
|
||||
if len(parts) != 4:
|
||||
if len(parts) != 3:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
epoch, cursor_scope, created_at, item_id = parts
|
||||
if epoch != CURSOR_EPOCH or cursor_scope != scope:
|
||||
cursor_scope, created_at, item_id = parts
|
||||
if cursor_scope != scope:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
if not created_at or not item_id:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
@@ -118,5 +118,5 @@ def parse_cursor(raw: str | None, scope: str) -> tuple[str, str] | None:
|
||||
|
||||
|
||||
def encode_cursor(created_at: str, item_id: str, scope: str) -> str:
|
||||
raw = "|".join([CURSOR_EPOCH, scope, created_at, item_id]).encode("utf-8")
|
||||
raw = "|".join([scope, created_at, item_id]).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii")
|
||||
|
||||
Reference in New Issue
Block a user