ЛР 2: PostgreSQL, сессии в Valkey, трек 2
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import os
|
||||
import socket
|
||||
|
||||
|
||||
def _int(name, default):
|
||||
value = os.environ.get(name)
|
||||
return int(value) if value not in (None, "") else default
|
||||
|
||||
|
||||
def _float(name, default):
|
||||
value = os.environ.get(name)
|
||||
return float(value) if value not in (None, "") else default
|
||||
|
||||
|
||||
def _secret(name, default=""):
|
||||
path = os.environ.get(name + "_FILE")
|
||||
if path:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
return handle.read().strip()
|
||||
return os.environ.get(name, default)
|
||||
|
||||
|
||||
DATABASE_URL = _secret("DATABASE_URL")
|
||||
CACHE_URL = _secret("CACHE_URL")
|
||||
SESSION_STORE = os.environ.get("SESSION_STORE", "postgres")
|
||||
SESSION_TTL_SECONDS = _int("SESSION_TTL_SECONDS", 3600)
|
||||
SESSION_CACHE_TTL_SECONDS = _int("SESSION_CACHE_TTL_SECONDS", 30)
|
||||
SESSION_SWEEP_SECONDS = _int("SESSION_SWEEP_SECONDS", 60)
|
||||
DB_POOL_MIN = _int("DB_POOL_MIN", 1)
|
||||
DB_POOL_MAX = _int("DB_POOL_MAX", 10)
|
||||
DB_POOL_TIMEOUT = _float("DB_POOL_TIMEOUT", 3.0)
|
||||
DB_CONNECT_TIMEOUT = _int("DB_CONNECT_TIMEOUT", 3)
|
||||
DB_STATEMENT_TIMEOUT_MS = _int("DB_STATEMENT_TIMEOUT_MS", 5000)
|
||||
DB_OP_TIMEOUT = _float("DB_OP_TIMEOUT", 6.0)
|
||||
REQUEST_TIMEOUT = _float("REQUEST_TIMEOUT", 8.0)
|
||||
DB_READY_TIMEOUT = _float("DB_READY_TIMEOUT", 1.5)
|
||||
CACHE_TIMEOUT = _float("CACHE_TIMEOUT", 0.2)
|
||||
MAX_INFLIGHT_REQUESTS = _int("MAX_INFLIGHT_REQUESTS", 64)
|
||||
MAX_BODY_BYTES = _int("MAX_BODY_BYTES", 65536)
|
||||
MAX_RSS_MB = _int("MAX_RSS_MB", 0)
|
||||
PASSWORD_MIN = 12
|
||||
PASSWORD_MAX = 128
|
||||
INSTANCE_ID = os.environ.get("INSTANCE_ID") or socket.gethostname()
|
||||
@@ -0,0 +1,43 @@
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
TS_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z")
|
||||
TS_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
|
||||
|
||||
|
||||
class BadCursor(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fmt(ts: datetime) -> str:
|
||||
return ts.astimezone(timezone.utc).strftime(TS_FORMAT)
|
||||
|
||||
|
||||
def encode_cursor(scope: str, created_at: str, item_id: str) -> str:
|
||||
raw = json.dumps({"s": scope, "t": created_at, "i": item_id}, separators=(",", ":")).encode()
|
||||
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(scope: str, cursor: str):
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))
|
||||
data = json.loads(raw)
|
||||
except Exception:
|
||||
raise BadCursor() from None
|
||||
if not isinstance(data, dict) or set(data) != {"s", "t", "i"} or data["s"] != scope:
|
||||
raise BadCursor()
|
||||
ts, item_id = data["t"], data["i"]
|
||||
if not isinstance(ts, str) or not TS_RE.fullmatch(ts) or not isinstance(item_id, str):
|
||||
raise BadCursor()
|
||||
try:
|
||||
parsed = datetime.strptime(ts, TS_FORMAT).replace(tzinfo=timezone.utc)
|
||||
if str(uuid.UUID(item_id)) != item_id:
|
||||
raise BadCursor()
|
||||
except ValueError:
|
||||
raise BadCursor() from None
|
||||
if encode_cursor(scope, ts, item_id) != cursor:
|
||||
raise BadCursor()
|
||||
return parsed, item_id
|
||||
@@ -0,0 +1,99 @@
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import AsyncConnectionPool, PoolTimeout
|
||||
|
||||
from app import config
|
||||
from app.errors import unavailable
|
||||
|
||||
BROKEN = (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout)
|
||||
|
||||
|
||||
async def discard(conn) -> None:
|
||||
try:
|
||||
await conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class Guarded:
|
||||
def __init__(self, conn, timeout: float):
|
||||
self.conn = conn
|
||||
self.timeout = timeout
|
||||
|
||||
async def execute(self, *args, **kwargs):
|
||||
try:
|
||||
return await asyncio.wait_for(self.conn.execute(*args, **kwargs), self.timeout)
|
||||
except asyncio.TimeoutError:
|
||||
await discard(self.conn)
|
||||
raise unavailable("Хранилище не ответило за отведённое время") from None
|
||||
|
||||
def transaction(self):
|
||||
return self.conn.transaction()
|
||||
|
||||
|
||||
class Database:
|
||||
def __init__(self) -> None:
|
||||
options = "-c statement_timeout=%d -c lock_timeout=%d -c idle_in_transaction_session_timeout=%d" % (
|
||||
config.DB_STATEMENT_TIMEOUT_MS,
|
||||
config.DB_STATEMENT_TIMEOUT_MS,
|
||||
config.DB_STATEMENT_TIMEOUT_MS * 2,
|
||||
)
|
||||
self.pool = AsyncConnectionPool(
|
||||
conninfo=config.DATABASE_URL,
|
||||
min_size=config.DB_POOL_MIN,
|
||||
max_size=config.DB_POOL_MAX,
|
||||
timeout=config.DB_POOL_TIMEOUT,
|
||||
max_lifetime=600.0,
|
||||
open=False,
|
||||
kwargs={
|
||||
"autocommit": True,
|
||||
"row_factory": dict_row,
|
||||
"connect_timeout": config.DB_CONNECT_TIMEOUT,
|
||||
"options": options,
|
||||
},
|
||||
)
|
||||
|
||||
async def open(self) -> None:
|
||||
await self.pool.open(wait=False)
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.pool.close()
|
||||
|
||||
@asynccontextmanager
|
||||
async def connection(self):
|
||||
try:
|
||||
async with self.pool.connection(timeout=config.DB_POOL_TIMEOUT) as conn:
|
||||
yield Guarded(conn, config.DB_OP_TIMEOUT)
|
||||
except BROKEN:
|
||||
raise unavailable("Хранилище недоступно") from None
|
||||
|
||||
@asynccontextmanager
|
||||
async def transaction(self):
|
||||
async with self.connection() as conn:
|
||||
async with conn.transaction():
|
||||
yield conn
|
||||
|
||||
async def in_transaction(self, action):
|
||||
async def run():
|
||||
async with self.transaction() as conn:
|
||||
return await action(conn)
|
||||
|
||||
try:
|
||||
return await asyncio.wait_for(run(), config.DB_OP_TIMEOUT)
|
||||
except asyncio.TimeoutError:
|
||||
raise unavailable("Хранилище не ответило за отведённое время") from None
|
||||
|
||||
async def ready(self) -> bool:
|
||||
try:
|
||||
async with self.pool.connection(timeout=config.DB_READY_TIMEOUT) as conn:
|
||||
try:
|
||||
await asyncio.wait_for(conn.execute("SELECT 1"), config.DB_READY_TIMEOUT)
|
||||
except asyncio.TimeoutError:
|
||||
await discard(conn)
|
||||
return False
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
@@ -0,0 +1,37 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str, headers: Optional[dict] = None):
|
||||
self.status, self.code, self.message, self.headers = status, code, message, headers or {}
|
||||
|
||||
|
||||
def bad(message: str) -> ApiError:
|
||||
return ApiError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def unauthorized(scheme: str = "Bearer") -> ApiError:
|
||||
challenge = BASIC_CHALLENGE if scheme == "Basic" else BEARER_CHALLENGE
|
||||
message = "Нужны имя пользователя и пароль" if scheme == "Basic" else "Нужна действующая сессия"
|
||||
return ApiError(401, "unauthorized", message, {"WWW-Authenticate": challenge})
|
||||
|
||||
|
||||
def not_found() -> ApiError:
|
||||
return ApiError(404, "not_found", "Объект не найден")
|
||||
|
||||
|
||||
def unavailable(message: str) -> ApiError:
|
||||
return ApiError(503, "unavailable", message, {"Retry-After": "1"})
|
||||
|
||||
|
||||
def error_body(rid: str, instance: str, status: int, code: str, message: str, headers: Optional[dict] = None) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={"error": {"code": code, "message": message, "request_id": rid}},
|
||||
headers={"X-Request-Id": rid, "X-Instance-Id": instance, **(headers or {})},
|
||||
)
|
||||
+391
@@ -0,0 +1,391 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import resource
|
||||
import signal
|
||||
import sys
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from app import config, passwords, repo
|
||||
from app.cursor import BadCursor, decode_cursor, encode_cursor
|
||||
from app.db import Database
|
||||
from app.errors import ApiError, bad, error_body, not_found, unauthorized, unavailable
|
||||
from app.sessions import SessionStore
|
||||
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
log = logging.getLogger("messenger")
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
ZERO_WIDTH = str.maketrans({char: None for char in "\u200b\u200c\u200d\u2060\ufeff"})
|
||||
EXEMPT_PATHS = ("/health/live", "/health/ready")
|
||||
PAGE_SIZE = os.sysconf("SC_PAGE_SIZE") if hasattr(os, "sysconf") else 4096
|
||||
|
||||
db = Database()
|
||||
sessions = SessionStore(db)
|
||||
state = {"draining": False, "inflight": 0, "rejected": {}}
|
||||
|
||||
|
||||
def rss_mb() -> float:
|
||||
try:
|
||||
with open("/proc/self/statm") as handle:
|
||||
return int(handle.read().split()[1]) * PAGE_SIZE / 1048576
|
||||
except OSError:
|
||||
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
||||
return peak / 1048576 if sys.platform == "darwin" else peak / 1024
|
||||
|
||||
|
||||
def count_rejection(code: str) -> None:
|
||||
state["rejected"][code] = state["rejected"].get(code, 0) + 1
|
||||
|
||||
|
||||
async def sweeper() -> None:
|
||||
while True:
|
||||
await asyncio.sleep(config.SESSION_SWEEP_SECONDS)
|
||||
try:
|
||||
removed = await sessions.sweep()
|
||||
if removed:
|
||||
log.info("sessions_expired removed=%d", removed)
|
||||
except Exception:
|
||||
log.warning("session sweep skipped: storage unavailable")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
previous = {}
|
||||
|
||||
def on_signal(signum, frame):
|
||||
if not state["draining"]:
|
||||
state["draining"] = True
|
||||
log.info("signal %s: draining, new requests get 503", signal.Signals(signum).name)
|
||||
handler = previous.get(signum)
|
||||
if callable(handler):
|
||||
handler(signum, frame)
|
||||
|
||||
for sig in (signal.SIGTERM, signal.SIGINT):
|
||||
previous[sig] = signal.getsignal(sig)
|
||||
signal.signal(sig, on_signal)
|
||||
await db.open()
|
||||
await sessions.open()
|
||||
task = asyncio.create_task(sweeper())
|
||||
log.info(
|
||||
"started: instance=%s session_store=%s session_ttl=%d cache_ttl=%d pool=%d..%d max_inflight=%d max_body=%d",
|
||||
config.INSTANCE_ID, config.SESSION_STORE, config.SESSION_TTL_SECONDS, config.SESSION_CACHE_TTL_SECONDS,
|
||||
config.DB_POOL_MIN, config.DB_POOL_MAX, config.MAX_INFLIGHT_REQUESTS, config.MAX_BODY_BYTES,
|
||||
)
|
||||
yield
|
||||
task.cancel()
|
||||
await sessions.close()
|
||||
await db.close()
|
||||
log.info("stopped: cache=%s rejected=%s", sessions.stats, state["rejected"])
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def guard(request: Request, call_next):
|
||||
rid = uuid.uuid4().hex
|
||||
request.state.rid = rid
|
||||
exempt = request.url.path in EXEMPT_PATHS
|
||||
if state["draining"] and request.url.path != "/health/live":
|
||||
count_rejection("draining")
|
||||
return error_body(rid, config.INSTANCE_ID, 503, "unavailable", "Сервер завершает работу", {"Retry-After": "1", "Connection": "close"})
|
||||
if not exempt and state["inflight"] >= config.MAX_INFLIGHT_REQUESTS:
|
||||
count_rejection("inflight")
|
||||
return error_body(rid, config.INSTANCE_ID, 429, "rate_limited", "Слишком много одновременных запросов", {"Retry-After": "1"})
|
||||
state["inflight"] += 1
|
||||
try:
|
||||
response = await asyncio.wait_for(call_next(request), config.REQUEST_TIMEOUT)
|
||||
except asyncio.TimeoutError:
|
||||
count_rejection("request_timeout")
|
||||
log.warning("request timeout request_id=%s method=%s path=%s", rid, request.method, request.url.path)
|
||||
response = error_body(
|
||||
rid, config.INSTANCE_ID, 503, "unavailable",
|
||||
"Запрос не удалось обработать за отведённое время", {"Retry-After": "1"},
|
||||
)
|
||||
except Exception:
|
||||
log.exception("unhandled error request_id=%s", rid)
|
||||
response = error_body(rid, config.INSTANCE_ID, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||
finally:
|
||||
state["inflight"] -= 1
|
||||
response.headers["X-Request-Id"] = rid
|
||||
response.headers["X-Instance-Id"] = config.INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, exc: ApiError):
|
||||
if exc.status in (413, 429, 503):
|
||||
count_rejection(exc.code)
|
||||
return error_body(request.state.rid, config.INSTANCE_ID, exc.status, exc.code, exc.message, exc.headers)
|
||||
|
||||
|
||||
def parse_uuid(value: object) -> Optional[str]:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def non_blank(value: object, max_len: int) -> bool:
|
||||
if not isinstance(value, str) or not 1 <= len(value) <= max_len:
|
||||
return False
|
||||
return value.translate(ZERO_WIDTH).strip() != ""
|
||||
|
||||
|
||||
async def read_json(request: Request, fields: Tuple[str, ...]) -> dict:
|
||||
if request.headers.get("content-type", "").split(";")[0].strip().lower() != "application/json":
|
||||
raise ApiError(415, "unsupported_media_type", "Ожидается application/json")
|
||||
too_large = ApiError(413, "payload_too_large", "Тело запроса слишком большое", {"Connection": "close"})
|
||||
declared = request.headers.get("content-length")
|
||||
if declared and declared.isdigit() and int(declared) > config.MAX_BODY_BYTES:
|
||||
raise too_large
|
||||
raw = bytearray()
|
||||
async for chunk in request.stream():
|
||||
raw += chunk
|
||||
if len(raw) > config.MAX_BODY_BYTES:
|
||||
raise too_large
|
||||
try:
|
||||
body = json.loads(bytes(raw).decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError, RecursionError):
|
||||
raise bad("Некорректный JSON") from None
|
||||
if not isinstance(body, dict):
|
||||
raise bad("Ожидается JSON-объект")
|
||||
if set(body) - set(fields):
|
||||
raise bad("Лишние поля в запросе")
|
||||
if set(fields) - set(body):
|
||||
raise bad("Отсутствуют обязательные поля")
|
||||
return body
|
||||
|
||||
|
||||
def ensure_capacity() -> None:
|
||||
if config.MAX_RSS_MB and rss_mb() > config.MAX_RSS_MB:
|
||||
raise unavailable("Достигнут лимит памяти процесса, запись недоступна")
|
||||
|
||||
|
||||
def bearer_token(request: Request) -> str:
|
||||
scheme, _, value = request.headers.get("authorization", "").partition(" ")
|
||||
token = value.strip()
|
||||
if scheme.lower() != "bearer" or not token:
|
||||
raise unauthorized()
|
||||
return token
|
||||
|
||||
|
||||
async def actor(request: Request) -> dict:
|
||||
user = await sessions.resolve(bearer_token(request))
|
||||
if user is None:
|
||||
raise unauthorized()
|
||||
return user
|
||||
|
||||
|
||||
def basic_credentials(request: Request) -> Tuple[str, str]:
|
||||
scheme, _, value = request.headers.get("authorization", "").partition(" ")
|
||||
if scheme.lower() != "basic" or not value.strip():
|
||||
raise unauthorized("Basic")
|
||||
try:
|
||||
decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, ValueError, UnicodeDecodeError):
|
||||
raise unauthorized("Basic") from None
|
||||
username, separator, password = decoded.partition(":")
|
||||
if not separator:
|
||||
raise unauthorized("Basic")
|
||||
return username, password
|
||||
|
||||
|
||||
async def member_chat(user: dict, chat_id: str) -> dict:
|
||||
cid = parse_uuid(chat_id)
|
||||
if cid is None:
|
||||
raise bad("chat_id должен быть UUID")
|
||||
async with db.connection() as conn:
|
||||
chat = await repo.chat_for_member(conn, cid, user["id"])
|
||||
if chat is None:
|
||||
raise not_found()
|
||||
return chat
|
||||
|
||||
|
||||
def page_params(request: Request) -> Tuple[int, Optional[str]]:
|
||||
query = request.query_params
|
||||
limit = 50
|
||||
if "limit" in query:
|
||||
if not re.fullmatch(r"[0-9]{1,3}", query["limit"]) or not 1 <= int(query["limit"]) <= 100:
|
||||
raise bad("limit должен быть целым 1..100")
|
||||
limit = int(query["limit"])
|
||||
cursor = query.get("cursor")
|
||||
if cursor is not None and cursor == "":
|
||||
raise bad("Некорректный cursor")
|
||||
return limit, cursor
|
||||
|
||||
|
||||
def keyset(scope: str, cursor: Optional[str]):
|
||||
if cursor is None:
|
||||
return None
|
||||
try:
|
||||
return decode_cursor(scope, cursor)
|
||||
except BadCursor:
|
||||
raise bad("Некорректный cursor") from None
|
||||
|
||||
|
||||
def page(scope: str, items: List[dict], has_more: bool) -> JSONResponse:
|
||||
next_cursor = encode_cursor(scope, items[-1]["created_at"], items[-1]["id"]) if has_more and items else None
|
||||
return JSONResponse({"items": items, "next_cursor": next_cursor})
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
async def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def ready():
|
||||
if not await db.ready():
|
||||
raise unavailable("База данных недоступна")
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
async def create_user(request: Request):
|
||||
body = await read_json(request, ("username", "display_name", "password"))
|
||||
if not isinstance(body["username"], str) or not USERNAME_RE.fullmatch(body["username"]):
|
||||
raise bad("username должен соответствовать [a-z0-9_]{3,32}")
|
||||
if not non_blank(body["display_name"], 100):
|
||||
raise bad("display_name: 1..100 символов, не только пробелы")
|
||||
password = body["password"]
|
||||
if not isinstance(password, str) or not config.PASSWORD_MIN <= len(password) <= config.PASSWORD_MAX:
|
||||
raise bad("password: %d..%d символов" % (config.PASSWORD_MIN, config.PASSWORD_MAX))
|
||||
ensure_capacity()
|
||||
password_hash = await run_in_threadpool(passwords.hash_password, password)
|
||||
async with db.connection() as conn:
|
||||
user = await repo.create_user(conn, body["username"], body["display_name"], password_hash)
|
||||
if user is None:
|
||||
raise ApiError(409, "conflict", "username уже занят")
|
||||
log.info("user_created id=%s", user["id"])
|
||||
return JSONResponse(user, status_code=201)
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||
async def login(request: Request):
|
||||
if await request.body():
|
||||
raise bad("POST /auth/sessions не принимает тело запроса")
|
||||
username, password = basic_credentials(request)
|
||||
row = None
|
||||
if USERNAME_RE.fullmatch(username) and config.PASSWORD_MIN <= len(password) <= config.PASSWORD_MAX:
|
||||
async with db.connection() as conn:
|
||||
row = await repo.credentials(conn, username)
|
||||
stored = row["password_hash"] if row else passwords.DUMMY_HASH
|
||||
matches = await run_in_threadpool(passwords.verify_password, stored, password)
|
||||
if row is None or not matches:
|
||||
log.info("login_failed username_known=%s", row is not None)
|
||||
raise unauthorized("Basic")
|
||||
user = repo.public_user(row)
|
||||
token, expires_at = await sessions.create(user)
|
||||
log.info("session_created user=%s", user["id"])
|
||||
return JSONResponse({"token": token, "token_type": "Bearer", "expires_at": expires_at, "user": user}, status_code=201)
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
async def logout(request: Request):
|
||||
token = bearer_token(request)
|
||||
user = await sessions.resolve(token)
|
||||
if user is None:
|
||||
raise unauthorized()
|
||||
await sessions.revoke(token)
|
||||
log.info("session_revoked user=%s", user["id"])
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
async def me(request: Request):
|
||||
return await actor(request)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
async def create_chat(request: Request):
|
||||
user = await actor(request)
|
||||
body = await read_json(request, ("title", "member_ids"))
|
||||
if not non_blank(body["title"], 100):
|
||||
raise bad("title: 1..100 символов, не только пробелы")
|
||||
raw_ids = body["member_ids"]
|
||||
if not isinstance(raw_ids, list) or not 1 <= len(raw_ids) <= 100:
|
||||
raise bad("member_ids: массив из 1..100 UUID")
|
||||
ids: List[str] = []
|
||||
for value in raw_ids:
|
||||
parsed = parse_uuid(value)
|
||||
if parsed is None:
|
||||
raise bad("member_ids содержит некорректный UUID")
|
||||
ids.append(parsed)
|
||||
if len(set(ids)) != len(ids):
|
||||
raise bad("member_ids содержит дубликаты")
|
||||
if user["id"] not in ids:
|
||||
raise bad("Создатель должен входить в member_ids")
|
||||
ensure_capacity()
|
||||
|
||||
async def insert(conn):
|
||||
return await repo.create_chat(conn, body["title"], ids)
|
||||
|
||||
try:
|
||||
chat = await db.in_transaction(insert)
|
||||
except repo.UnknownMember:
|
||||
raise bad("member_ids содержит неизвестного пользователя") from None
|
||||
log.info("chat_created id=%s members=%d", chat["id"], len(ids))
|
||||
return JSONResponse(chat, status_code=201)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
async def list_chats(request: Request):
|
||||
user = await actor(request)
|
||||
limit, cursor = page_params(request)
|
||||
scope = "chats:" + user["id"]
|
||||
after = keyset(scope, cursor)
|
||||
async with db.connection() as conn:
|
||||
items, has_more = await repo.list_chats(conn, user["id"], limit, after)
|
||||
return page(scope, items, has_more)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(chat_id: str, request: Request):
|
||||
return await member_chat(await actor(request), chat_id)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
async def create_message(chat_id: str, request: Request):
|
||||
user = await actor(request)
|
||||
cid = parse_uuid(chat_id)
|
||||
if cid is None:
|
||||
raise bad("chat_id должен быть UUID")
|
||||
body = await read_json(request, ("text",))
|
||||
if not non_blank(body["text"], 4000):
|
||||
raise bad("text: 1..4000 символов, не только пробелы")
|
||||
ensure_capacity()
|
||||
async with db.connection() as conn:
|
||||
message = await repo.create_message(conn, cid, user["id"], body["text"])
|
||||
if message is None:
|
||||
raise not_found()
|
||||
return JSONResponse(message, status_code=201)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(chat_id: str, request: Request):
|
||||
chat = await member_chat(await actor(request), chat_id)
|
||||
limit, cursor = page_params(request)
|
||||
scope = "messages:" + chat["id"]
|
||||
after = keyset(scope, cursor)
|
||||
async with db.connection() as conn:
|
||||
items, has_more = await repo.list_messages(conn, chat["id"], limit, after)
|
||||
return page(scope, items, has_more)
|
||||
|
||||
|
||||
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"])
|
||||
async def fallback(request: Request):
|
||||
raise not_found()
|
||||
@@ -0,0 +1,16 @@
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import Argon2Error, VerifyMismatchError
|
||||
|
||||
HASHER = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
DUMMY_HASH = HASHER.hash("there-is-no-such-user-password")
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return HASHER.hash(password)
|
||||
|
||||
|
||||
def verify_password(stored: str, password: str) -> bool:
|
||||
try:
|
||||
return HASHER.verify(stored, password)
|
||||
except (VerifyMismatchError, Argon2Error, ValueError):
|
||||
return False
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import psycopg
|
||||
|
||||
from app.cursor import fmt
|
||||
|
||||
MESSAGE_COLUMNS = "id, chat_id, sender_id, text, created_at"
|
||||
CHAT_QUERY = (
|
||||
"SELECT c.id, c.title, c.created_at,"
|
||||
" ARRAY(SELECT m2.user_id FROM chat_members m2 WHERE m2.chat_id = c.id ORDER BY m2.user_id) AS member_ids"
|
||||
)
|
||||
|
||||
|
||||
class UnknownMember(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def decoded(value) -> str:
|
||||
return bytes(value).decode("utf-8")
|
||||
|
||||
|
||||
def public_user(row) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": decoded(row["display_name"]),
|
||||
"created_at": fmt(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _chat(row) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": decoded(row["title"]),
|
||||
"member_ids": [str(value) for value in row["member_ids"]],
|
||||
"created_at": fmt(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _message(row) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": decoded(row["text"]),
|
||||
"created_at": fmt(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
async def create_user(conn, username: str, display_name: str, password_hash: str) -> Optional[dict]:
|
||||
try:
|
||||
cur = await conn.execute(
|
||||
"INSERT INTO users (id, username, display_name, password_hash, created_at)"
|
||||
" VALUES (gen_random_uuid(), %s, %s, %s, clock_timestamp())"
|
||||
" RETURNING id, username, display_name, created_at",
|
||||
(username, display_name.encode("utf-8"), password_hash),
|
||||
)
|
||||
except psycopg.errors.UniqueViolation:
|
||||
return None
|
||||
return public_user(await cur.fetchone())
|
||||
|
||||
|
||||
async def credentials(conn, username: str):
|
||||
cur = await conn.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s",
|
||||
(username,),
|
||||
)
|
||||
return await cur.fetchone()
|
||||
|
||||
|
||||
async def create_chat(conn, title: str, member_ids: List[str]) -> dict:
|
||||
cur = await conn.execute(
|
||||
"INSERT INTO chats (id, title, created_at)"
|
||||
" VALUES (gen_random_uuid(), %s, clock_timestamp())"
|
||||
" RETURNING id, title, created_at",
|
||||
(title.encode("utf-8"),),
|
||||
)
|
||||
chat = await cur.fetchone()
|
||||
cur = await conn.execute(
|
||||
"INSERT INTO chat_members (chat_id, user_id) SELECT %s, u.id FROM users u WHERE u.id = ANY(%s::uuid[])",
|
||||
(chat["id"], member_ids),
|
||||
)
|
||||
if cur.rowcount != len(member_ids):
|
||||
raise UnknownMember()
|
||||
chat["member_ids"] = list(member_ids)
|
||||
return _chat(chat)
|
||||
|
||||
|
||||
async def chat_for_member(conn, chat_id: str, user_id: str) -> Optional[dict]:
|
||||
cur = await conn.execute(
|
||||
CHAT_QUERY + " FROM chats c JOIN chat_members m ON m.chat_id = c.id AND m.user_id = %s WHERE c.id = %s",
|
||||
(user_id, chat_id),
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
return _chat(row) if row else None
|
||||
|
||||
|
||||
async def list_chats(conn, user_id: str, limit: int, after) -> Tuple[List[dict], bool]:
|
||||
ts, last_id = after if after else (None, None)
|
||||
cur = await conn.execute(
|
||||
CHAT_QUERY
|
||||
+ " FROM chats c JOIN chat_members m ON m.chat_id = c.id"
|
||||
" WHERE m.user_id = %s AND (%s::timestamptz IS NULL OR (c.created_at, c.id) > (%s::timestamptz, %s::uuid))"
|
||||
" ORDER BY c.created_at, c.id LIMIT %s",
|
||||
(user_id, ts, ts, last_id, limit + 1),
|
||||
)
|
||||
rows = await cur.fetchall()
|
||||
return [_chat(row) for row in rows[:limit]], len(rows) > limit
|
||||
|
||||
|
||||
async def create_message(conn, chat_id: str, sender_id: str, text: str) -> Optional[dict]:
|
||||
cur = await conn.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at)"
|
||||
" SELECT gen_random_uuid(), %s, %s, %s, clock_timestamp()"
|
||||
" WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s)"
|
||||
" RETURNING " + MESSAGE_COLUMNS,
|
||||
(chat_id, sender_id, text.encode("utf-8"), chat_id, sender_id),
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
return _message(row) if row else None
|
||||
|
||||
|
||||
async def list_messages(conn, chat_id: str, limit: int, after) -> Tuple[List[dict], bool]:
|
||||
ts, last_id = after if after else (None, None)
|
||||
cur = await conn.execute(
|
||||
"SELECT " + MESSAGE_COLUMNS + " FROM messages"
|
||||
" WHERE chat_id = %s AND (%s::timestamptz IS NULL OR (created_at, id) > (%s::timestamptz, %s::uuid))"
|
||||
" ORDER BY created_at, id LIMIT %s",
|
||||
(chat_id, ts, ts, last_id, limit + 1),
|
||||
)
|
||||
rows = await cur.fetchall()
|
||||
return [_message(row) for row in rows[:limit]], len(rows) > limit
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
import valkey.asyncio as valkey
|
||||
|
||||
from app import config
|
||||
from app.cursor import fmt
|
||||
from app.errors import unavailable
|
||||
|
||||
log = logging.getLogger("messenger.sessions")
|
||||
|
||||
|
||||
class SessionStore:
|
||||
def __init__(self, db) -> None:
|
||||
self.db = db
|
||||
self.client = None
|
||||
self.stats = {"hits": 0, "misses": 0, "errors": 0}
|
||||
|
||||
async def open(self) -> None:
|
||||
if not config.CACHE_URL:
|
||||
log.info("session cache disabled: CACHE_URL is empty")
|
||||
return
|
||||
self.client = valkey.Valkey.from_url(
|
||||
config.CACHE_URL,
|
||||
socket_timeout=config.CACHE_TIMEOUT,
|
||||
socket_connect_timeout=config.CACHE_TIMEOUT,
|
||||
decode_responses=True,
|
||||
)
|
||||
|
||||
async def close(self) -> None:
|
||||
if self.client is not None:
|
||||
await self.client.aclose()
|
||||
self.client = None
|
||||
|
||||
@staticmethod
|
||||
def digest(token: str) -> bytes:
|
||||
return hashlib.sha256(token.encode("utf-8")).digest()
|
||||
|
||||
@staticmethod
|
||||
def key(digest: bytes) -> str:
|
||||
return "session:" + digest.hex()
|
||||
|
||||
async def create(self, user: dict) -> tuple:
|
||||
token = secrets.token_urlsafe(32)
|
||||
digest = self.digest(token)
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(seconds=config.SESSION_TTL_SECONDS)
|
||||
async with self.db.connection() as conn:
|
||||
await conn.execute(
|
||||
"INSERT INTO sessions (token_hash, user_id, created_at, expires_at)"
|
||||
" VALUES (%s, %s, clock_timestamp(), %s)",
|
||||
(digest, user["id"], expires_at),
|
||||
)
|
||||
await self._cache_put(digest, user, expires_at)
|
||||
return token, fmt(expires_at)
|
||||
|
||||
async def resolve(self, token: str) -> Optional[dict]:
|
||||
digest = self.digest(token)
|
||||
cached = await self._cache_get(digest)
|
||||
if cached is not None:
|
||||
self.stats["hits"] += 1
|
||||
return cached
|
||||
self.stats["misses"] += 1
|
||||
async with self.db.connection() as conn:
|
||||
cur = await 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.expires_at > now()",
|
||||
(digest,),
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
user = {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": fmt(row["created_at"]),
|
||||
}
|
||||
await self._cache_put(digest, user, row["expires_at"])
|
||||
return user
|
||||
|
||||
async def revoke(self, token: str) -> None:
|
||||
digest = self.digest(token)
|
||||
await self._cache_drop(digest)
|
||||
async with self.db.connection() as conn:
|
||||
await conn.execute("DELETE FROM sessions WHERE token_hash = %s", (digest,))
|
||||
|
||||
async def sweep(self) -> int:
|
||||
async with self.db.connection() as conn:
|
||||
cur = await conn.execute("DELETE FROM sessions WHERE expires_at <= now()")
|
||||
return cur.rowcount
|
||||
|
||||
def _cache_ttl(self, expires_at: datetime) -> int:
|
||||
remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds())
|
||||
return min(config.SESSION_CACHE_TTL_SECONDS, remaining)
|
||||
|
||||
async def _cache_get(self, digest: bytes) -> Optional[dict]:
|
||||
if self.client is None:
|
||||
return None
|
||||
try:
|
||||
raw = await self.client.get(self.key(digest))
|
||||
except Exception:
|
||||
self._cache_failed("get")
|
||||
return None
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
async def _cache_put(self, digest: bytes, user: dict, expires_at: datetime) -> None:
|
||||
if self.client is None:
|
||||
return
|
||||
ttl = self._cache_ttl(expires_at)
|
||||
if ttl <= 0:
|
||||
return
|
||||
try:
|
||||
await self.client.set(self.key(digest), json.dumps(user), ex=ttl)
|
||||
except Exception:
|
||||
self._cache_failed("set")
|
||||
|
||||
async def _cache_drop(self, digest: bytes) -> None:
|
||||
if self.client is None:
|
||||
return
|
||||
try:
|
||||
await self.client.delete(self.key(digest))
|
||||
except Exception:
|
||||
self._cache_failed("delete")
|
||||
raise unavailable("Кэш сессий недоступен, выход из сессии не подтверждён") from None
|
||||
|
||||
def _cache_failed(self, operation: str) -> None:
|
||||
self.stats["errors"] += 1
|
||||
if self.stats["errors"] % 50 == 1:
|
||||
log.warning("session cache %s failed, falling back to postgres (errors=%d)", operation, self.stats["errors"])
|
||||
Reference in New Issue
Block a user