ЛР2: PostgreSQL + Valkey, сессии Basic/Bearer, миграции, compose, тесты, отчёт

This commit is contained in:
2026-10-15 19:17:22 +03:00
parent 65003b6119
commit 6808ed8c98
44 changed files with 2370 additions and 19 deletions
+1
View File
@@ -0,0 +1 @@
"""MTUSI Messenger lab2 application package."""
+348
View File
@@ -0,0 +1,348 @@
"""FastAPI application implementing the lab2 HTTP contract.
Canonical contract: ``contracts/openapi.json`` and ``contracts/README.md``.
PostgreSQL is the source of truth; Valkey is a best-effort session cache.
Every response carries a non-empty ``X-Request-Id``.
"""
from __future__ import annotations
import base64
import binascii
import logging
import re
import uuid
from typing import Dict, List, Optional
from fastapi import Depends, FastAPI, Query, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field, field_validator
from psycopg import InterfaceError, OperationalError
from psycopg_pool import PoolTimeout
from starlette.exceptions import HTTPException as StarletteHTTPException
from . import repositories as repo
from . import security, sessions
from .db import pool
from .errors import ApiError
from .pagination import bound_cursor, encode_cursor
logger = logging.getLogger("messenger")
BEARER_CHALLENGE = 'Bearer realm="messenger"'
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
_BEARER_RE = re.compile(r"^Bearer\s+(\S+)$", re.IGNORECASE)
_STATUS_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
405: "invalid_request",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
503: "unavailable",
}
app = FastAPI(
title="MTUSI Messenger — лабораторная 2",
version="1.2.0",
docs_url=None,
redoc_url=None,
openapi_url=None,
)
# --------------------------------------------------------------------------- #
# Error envelope
# --------------------------------------------------------------------------- #
def _request_id(request: Request) -> str:
return getattr(request.state, "request_id", None) or uuid.uuid4().hex
def error_response(
request: Request, status: int, code: str, message: str, challenge: Optional[str] = None
) -> JSONResponse:
rid = _request_id(request)
headers = {"X-Request-Id": rid}
if challenge:
headers["WWW-Authenticate"] = challenge
return JSONResponse(
status_code=status,
content={"error": {"code": code, "message": message, "request_id": rid}},
headers=headers,
)
@app.middleware("http")
async def request_context(request: Request, call_next):
rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex
request.state.request_id = rid
try:
response = await call_next(request)
except Exception as exc: # noqa: BLE001 - never leak internals
logging.getLogger("messenger").error("unhandled error: %s", type(exc).__name__)
logging.getLogger("messenger").debug("traceback", exc_info=exc)
response = error_response(request, 500, "internal_error", "Внутренняя ошибка")
response.headers["X-Request-Id"] = rid
return response
@app.exception_handler(ApiError)
async def handle_api_error(request: Request, exc: ApiError) -> JSONResponse:
challenge = exc.challenge or (BEARER_CHALLENGE if exc.status == 401 else None)
return error_response(request, exc.status, exc.code, exc.message, challenge)
@app.exception_handler(RequestValidationError)
async def handle_validation(request: Request, exc: RequestValidationError) -> JSONResponse:
return error_response(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(StarletteHTTPException)
async def handle_http_error(request: Request, exc: StarletteHTTPException) -> JSONResponse:
code = _STATUS_CODES.get(exc.status_code, "invalid_request")
challenge = BEARER_CHALLENGE if exc.status_code == 401 else None
return error_response(request, exc.status_code, code, "Ошибка запроса", challenge)
def _handle_db_error(request: Request, exc: Exception) -> JSONResponse:
logger.warning("database unavailable: %s", type(exc).__name__)
return error_response(request, 503, "unavailable", "База данных недоступна")
app.add_exception_handler(OperationalError, _handle_db_error)
app.add_exception_handler(InterfaceError, _handle_db_error)
app.add_exception_handler(PoolTimeout, _handle_db_error)
# --------------------------------------------------------------------------- #
# Request schemas
# --------------------------------------------------------------------------- #
class CreateUser(BaseModel):
model_config = ConfigDict(extra="forbid")
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
@field_validator("display_name")
@classmethod
def _not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("display_name must not be blank")
return value
class CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(min_length=1, max_length=100)
member_ids: List[uuid.UUID] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def _not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("title must not be blank")
return value
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(min_length=1, max_length=4000)
@field_validator("text")
@classmethod
def _not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("text must not be blank")
return value
# --------------------------------------------------------------------------- #
# Dependencies and helpers
# --------------------------------------------------------------------------- #
def get_conn():
with pool().connection() as conn:
yield conn
def _canonical_uuid(value: str) -> str:
try:
return str(uuid.UUID(value))
except (ValueError, AttributeError, TypeError):
raise ApiError(400, "invalid_request", "Некорректный идентификатор")
def _parse_basic(request: Request) -> tuple[str, str]:
header = request.headers.get("Authorization", "").strip()
if not header.lower().startswith("basic "):
raise ApiError(401, "unauthorized", "Требуется Basic-аутентификация", challenge=BASIC_CHALLENGE)
encoded = header[6:].strip()
try:
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
except (binascii.Error, ValueError, UnicodeDecodeError):
raise ApiError(401, "unauthorized", "Неверные учётные данные", challenge=BASIC_CHALLENGE)
if ":" not in decoded:
raise ApiError(401, "unauthorized", "Неверные учётные данные", challenge=BASIC_CHALLENGE)
username, password = decoded.split(":", 1)
return username, password
def _bearer_token(request: Request) -> str:
header = request.headers.get("Authorization", "").strip()
match = _BEARER_RE.match(header)
if not match:
raise ApiError(401, "unauthorized", "Требуется Bearer-токен", challenge=BEARER_CHALLENGE)
return match.group(1)
def current_user(request: Request, conn=Depends(get_conn)) -> Dict:
token = _bearer_token(request)
user_id = sessions.resolve(conn, token)
if user_id is None:
raise ApiError(401, "unauthorized", "Сессия недействительна", challenge=BEARER_CHALLENGE)
row = repo.get_user_by_id(conn, user_id)
if row is None:
raise ApiError(401, "unauthorized", "Сессия недействительна", challenge=BEARER_CHALLENGE)
return row
def _require_chat(conn, chat_id: str, user_id: str) -> str:
canonical = _canonical_uuid(chat_id)
if repo.get_chat_for(conn, canonical, user_id) is None:
raise ApiError(404, "not_found", "Чат недоступен")
return canonical
# --------------------------------------------------------------------------- #
# Health
# --------------------------------------------------------------------------- #
@app.get("/health/live")
def liveness() -> dict:
return {"status": "ok"}
@app.get("/health/ready")
def readiness() -> dict:
try:
with pool().connection(timeout=2) as conn:
conn.execute("select 1")
except (OperationalError, InterfaceError, PoolTimeout):
raise ApiError(503, "unavailable", "База данных недоступна")
return {"status": "ok"}
# --------------------------------------------------------------------------- #
# Users and sessions
# --------------------------------------------------------------------------- #
@app.post("/api/v1/users", status_code=201)
def register_user(payload: CreateUser, conn=Depends(get_conn)) -> dict:
password_hash = security.hash_password(payload.password)
row = repo.create_user(conn, payload.username, payload.display_name, password_hash)
return repo.user_json(row)
@app.post("/api/v1/auth/sessions", status_code=201)
def create_session(request: Request, conn=Depends(get_conn)) -> dict:
username, password = _parse_basic(request)
row = repo.get_user_with_hash_by_username(conn, username)
if row is None or not security.verify_password(row["password_hash"], password):
raise ApiError(401, "unauthorized", "Неверные учётные данные", challenge=BASIC_CHALLENGE)
token, expires_at = sessions.create(conn, str(row["id"]))
return {
"token": token,
"token_type": "Bearer",
"expires_at": repo.rfc3339(expires_at),
"user": repo.user_json(row),
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def revoke_session(
request: Request,
user: Dict = Depends(current_user),
conn=Depends(get_conn),
) -> Response:
sessions.revoke(conn, _bearer_token(request))
return Response(status_code=204)
@app.get("/api/v1/users/me")
def current_user_endpoint(user: Dict = Depends(current_user)) -> dict:
return repo.user_json(user)
# --------------------------------------------------------------------------- #
# Chats
# --------------------------------------------------------------------------- #
@app.post("/api/v1/chats", status_code=201)
def create_chat(payload: CreateChat, user: Dict = Depends(current_user), conn=Depends(get_conn)) -> dict:
members = [str(member) for member in payload.member_ids]
if len(set(members)) != len(members):
raise ApiError(400, "invalid_request", "Дубликаты участников")
if str(user["id"]) not in members:
raise ApiError(400, "invalid_request", "Вызывающий должен входить в участников")
if repo.count_users(conn, members) != len(set(members)):
raise ApiError(400, "invalid_request", "Неизвестный участник")
row = repo.create_chat(conn, payload.title, members)
return repo.chat_json(row)
@app.get("/api/v1/chats")
def list_chats(
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None),
user: Dict = Depends(current_user),
conn=Depends(get_conn),
) -> dict:
key = bound_cursor(cursor, "chats")
rows = repo.list_chats(conn, str(user["id"]), limit + 1, key)
page = rows[:limit]
next_cursor = None
if len(rows) > limit:
next_cursor = encode_cursor("chats", page[-1]["created_at"], str(page[-1]["id"]))
return {"items": [repo.chat_json(row) for row in page], "next_cursor": next_cursor}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: str, user: Dict = Depends(current_user), conn=Depends(get_conn)) -> dict:
canonical = _require_chat(conn, chat_id, str(user["id"]))
row = repo.get_chat_for(conn, canonical, str(user["id"]))
return repo.chat_json(row)
# --------------------------------------------------------------------------- #
# Messages
# --------------------------------------------------------------------------- #
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def create_message(
chat_id: str,
payload: CreateMessage,
user: Dict = Depends(current_user),
conn=Depends(get_conn),
) -> dict:
canonical = _require_chat(conn, chat_id, str(user["id"]))
row = repo.insert_message(conn, canonical, str(user["id"]), payload.text)
return repo.message_json(row)
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(
chat_id: str,
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None),
user: Dict = Depends(current_user),
conn=Depends(get_conn),
) -> dict:
canonical = _require_chat(conn, chat_id, str(user["id"]))
key = bound_cursor(cursor, canonical)
rows = repo.list_messages(conn, canonical, limit + 1, key)
page = rows[:limit]
next_cursor = None
if len(rows) > limit:
next_cursor = encode_cursor(canonical, page[-1]["created_at"], str(page[-1]["id"]))
return {"items": [repo.message_json(row) for row in page], "next_cursor": next_cursor}
+59
View File
@@ -0,0 +1,59 @@
"""Runtime configuration from environment variables / secret files.
Only logical interface names from ``.env.example`` are consumed; secret values
are read from files (``*_FILE``) so that no credential is baked into the image
or committed. The mapping is documented in REPORT.md.
"""
from __future__ import annotations
import os
from dataclasses import dataclass
from pathlib import Path
def _read_secret(file_key: str, value_key: str, default: str = "") -> str:
path = os.environ.get(file_key)
if path:
try:
return Path(path).read_text(encoding="utf-8").strip()
except OSError:
return default
return os.environ.get(value_key, default)
@dataclass(frozen=True)
class Settings:
app_host: str
app_port: int
app_env: str
session_ttl_seconds: int
session_store: str
database_url: str
cache_url: str
db_pool_min: int
db_pool_max: int
db_pool_timeout: float
db_statement_timeout_ms: int
@property
def cache_enabled(self) -> bool:
return bool(self.cache_url) and self.session_store in {"valkey", "redis"}
def load_settings() -> Settings:
return Settings(
app_host=os.environ.get("APP_HOST", "0.0.0.0"),
app_port=int(os.environ.get("APP_PORT", "8080")),
app_env=os.environ.get("APP_ENV", "lab"),
session_ttl_seconds=int(os.environ.get("SESSION_TTL_SECONDS", "3600")),
session_store=os.environ.get("SESSION_STORE", "postgres").lower(),
database_url=_read_secret("DATABASE_URL_FILE", "DATABASE_URL"),
cache_url=_read_secret("CACHE_URL_FILE", "CACHE_URL"),
db_pool_min=int(os.environ.get("DB_POOL_MIN", "1")),
db_pool_max=int(os.environ.get("DB_POOL_MAX", "10")),
db_pool_timeout=float(os.environ.get("DB_POOL_TIMEOUT", "5")),
db_statement_timeout_ms=int(os.environ.get("DB_STATEMENT_TIMEOUT_MS", "5000")),
)
settings = load_settings()
+42
View File
@@ -0,0 +1,42 @@
"""PostgreSQL access: a bounded connection pool with timeouts.
All queries elsewhere are parameterized; this module only owns the pool.
A statement timeout and a bounded pool are part of the grade-4 requirements.
"""
from __future__ import annotations
import logging
from typing import Optional
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from .config import settings
logger = logging.getLogger("messenger.db")
_pool: Optional[ConnectionPool] = None
def pool() -> ConnectionPool:
global _pool
if _pool is None:
_pool = ConnectionPool(
conninfo=settings.database_url,
min_size=settings.db_pool_min,
max_size=settings.db_pool_max,
timeout=settings.db_pool_timeout,
kwargs={
"row_factory": dict_row,
"options": f"-c statement_timeout={settings.db_statement_timeout_ms}",
},
open=True,
)
return _pool
def close_pool() -> None:
global _pool
if _pool is not None:
_pool.close()
_pool = None
+20
View File
@@ -0,0 +1,20 @@
"""Shared error type mapped to the contract error envelope."""
from __future__ import annotations
from typing import Optional
class ApiError(Exception):
def __init__(
self,
status: int,
code: str,
message: str,
challenge: Optional[str] = None,
) -> None:
super().__init__(message)
self.status = status
self.code = code
self.message = message
# Optional WWW-Authenticate value (used by 401 responses).
self.challenge = challenge
+38
View File
@@ -0,0 +1,38 @@
"""Container entrypoint: migrate, then run the HTTP server as PID 1."""
from __future__ import annotations
import logging
import os
import uvicorn
from .config import settings
from .migrate import apply_migrations
def main() -> None:
logging.basicConfig(
level=os.environ.get("LOG_LEVEL", "INFO").upper(),
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logging.getLogger("messenger").info(
"starting messenger api env=%s host=%s port=%s sessions=%s cache=%s",
settings.app_env,
settings.app_host,
settings.app_port,
settings.session_store,
"on" if settings.cache_enabled else "off",
)
apply_migrations()
uvicorn.run(
"src.app:app",
host=settings.app_host,
port=settings.app_port,
log_level=os.environ.get("LOG_LEVEL", "info").lower(),
access_log=True,
timeout_graceful_shutdown=10,
)
if __name__ == "__main__":
main()
+66
View File
@@ -0,0 +1,66 @@
"""Versioned, idempotent migration runner.
Applied versions are recorded in ``schema_migrations``; a transaction-scoped
advisory lock serializes concurrent API replicas, so re-running never
duplicates schema or data.
"""
from __future__ import annotations
import logging
import time
from pathlib import Path
import psycopg
from psycopg_pool import PoolTimeout
from .db import pool
logger = logging.getLogger("messenger.migrate")
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
LOCK_KEY = 776_2026
def _apply_once() -> None:
files = sorted(MIGRATIONS_DIR.glob("*.sql"))
with pool().connection() as conn:
conn.execute("select pg_advisory_xact_lock(%s)", (LOCK_KEY,))
conn.execute(
"""
create table if not exists schema_migrations (
version text primary key,
applied_at timestamptz not null default now()
)
"""
)
applied = {
row["version"]
for row in conn.execute("select version from schema_migrations").fetchall()
}
for path in files:
if path.name in applied:
continue
logger.info("applying migration %s", path.name)
conn.execute(path.read_text(encoding="utf-8"))
conn.execute(
"insert into schema_migrations (version) values (%s)", (path.name,)
)
def apply_migrations(attempts: int = 30, delay: float = 1.0) -> None:
last: Exception | None = None
for attempt in range(1, attempts + 1):
try:
_apply_once()
logger.info("migrations up to date")
return
except (psycopg.OperationalError, PoolTimeout) as exc:
last = exc
logger.warning("database not ready (attempt %s/%s): %s", attempt, attempts, exc)
time.sleep(delay)
raise RuntimeError(f"database unavailable after {attempts} attempts: {last}")
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
apply_migrations()
+53
View File
@@ -0,0 +1,53 @@
"""Opaque keyset cursors for ``(created_at, id)`` ascending pagination."""
from __future__ import annotations
import base64
import binascii
import datetime as dt
import json
import uuid
from typing import Optional, Tuple
from .errors import ApiError
CursorKey = Tuple[dt.datetime, str]
def encode_cursor(resource_id: str, created_at: dt.datetime, item_id: str) -> str:
payload = json.dumps(
{
"r": resource_id,
"t": created_at.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
"i": item_id,
},
separators=(",", ":"),
).encode("utf-8")
return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")
def decode_cursor(cursor: str) -> Tuple[str, CursorKey]:
try:
padded = cursor + "=" * (-len(cursor) % 4)
data = json.loads(base64.urlsafe_b64decode(padded).decode("utf-8"))
if not isinstance(data, dict):
raise ValueError("cursor payload must be an object")
resource = data["r"]
item_id = data["i"]
if not isinstance(resource, str) or not isinstance(item_id, str):
raise ValueError("cursor fields must be strings")
created = dt.datetime.strptime(data["t"], "%Y-%m-%dT%H:%M:%S.%fZ").replace(
tzinfo=dt.timezone.utc
)
return resource, (created, str(uuid.UUID(item_id)))
except (binascii.Error, ValueError, KeyError, TypeError, AttributeError, UnicodeDecodeError):
raise ApiError(400, "invalid_request", "Некорректный cursor")
def bound_cursor(cursor: str, expected_resource: str) -> Optional[CursorKey]:
"""Validate resource binding and return the key, or None for empty cursor."""
if cursor is None:
return None
resource, key = decode_cursor(cursor)
if resource != expected_resource:
raise ApiError(400, "invalid_request", "cursor относится к другому ресурсу")
return key
+240
View File
@@ -0,0 +1,240 @@
"""Parameterized SQL for users, chats, members, messages and sessions.
Every statement uses bound parameters (no string concatenation). Composite
writes happen inside one transaction so the caller gets all-or-nothing.
"""
from __future__ import annotations
import datetime as dt
import uuid
from typing import Dict, List, Optional, Sequence
from psycopg.errors import UniqueViolation
from .errors import ApiError
from .pagination import CursorKey
def utcnow() -> dt.datetime:
return dt.datetime.now(dt.timezone.utc)
def rfc3339(value: dt.datetime) -> str:
return value.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z"
def _members(value) -> List[str]:
if value is None:
return []
return [str(item) for item in value]
def user_json(row: Dict) -> Dict:
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": rfc3339(row["created_at"]),
}
def chat_json(row: Dict) -> Dict:
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": _members(row["member_ids"]),
"created_at": rfc3339(row["created_at"]),
}
def message_json(row: Dict) -> Dict:
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": rfc3339(row["created_at"]),
}
# --------------------------------------------------------------------------- #
# Users
# --------------------------------------------------------------------------- #
def create_user(conn, username: str, display_name: str, password_hash: str) -> Dict:
try:
row = conn.execute(
"""
insert into users (id, username, display_name, password_hash, created_at)
values (%s, %s, %s, %s, %s)
returning id, username, display_name, created_at
""",
(str(uuid.uuid4()), username, display_name, password_hash, utcnow()),
).fetchone()
except UniqueViolation:
raise ApiError(409, "conflict", "Имя пользователя уже занято")
return row
def get_user_by_id(conn, user_id: str) -> Optional[Dict]:
return conn.execute(
"select id, username, display_name, created_at from users where id = %s",
(user_id,),
).fetchone()
def get_user_with_hash_by_username(conn, username: str) -> Optional[Dict]:
return conn.execute(
"select id, username, display_name, created_at, password_hash from users where username = %s",
(username,),
).fetchone()
def count_users(conn, user_ids: Sequence[str]) -> int:
row = conn.execute(
"select count(*) as n from users where id = any(%s::uuid[])", (list(user_ids),)
).fetchone()
return int(row["n"])
# --------------------------------------------------------------------------- #
# Chats
# --------------------------------------------------------------------------- #
def create_chat(conn, title: str, member_ids: Sequence[str]) -> Dict:
chat_id = str(uuid.uuid4())
created = utcnow()
conn.execute(
"insert into chats (id, title, created_at) values (%s, %s, %s)",
(chat_id, title, created),
)
with conn.cursor() as cur:
cur.executemany(
"insert into chat_members (chat_id, user_id) values (%s, %s)",
[(chat_id, member) for member in member_ids],
)
return {
"id": chat_id,
"title": title,
"member_ids": list(member_ids),
"created_at": created,
}
_MEMBER_SUBQUERY = (
"(select array_agg(m.user_id) from chat_members m where m.chat_id = c.id)"
)
def get_chat_for(conn, chat_id: str, user_id: str) -> Optional[Dict]:
return conn.execute(
f"""
select c.id, c.title, c.created_at, {_MEMBER_SUBQUERY} as member_ids
from chats c
where c.id = %s
and exists (
select 1 from chat_members cm
where cm.chat_id = c.id and cm.user_id = %s
)
""",
(chat_id, user_id),
).fetchone()
def list_chats(conn, user_id: str, limit: int, cursor: Optional[CursorKey]) -> List[Dict]:
if cursor is None:
return conn.execute(
f"""
select c.id, c.title, c.created_at, {_MEMBER_SUBQUERY} as member_ids
from chats c
join chat_members cm on cm.chat_id = c.id
where cm.user_id = %s
order by c.created_at, c.id
limit %s
""",
(user_id, limit),
).fetchall()
return conn.execute(
f"""
select c.id, c.title, c.created_at, {_MEMBER_SUBQUERY} as member_ids
from chats c
join chat_members cm on cm.chat_id = c.id
where cm.user_id = %s and (c.created_at, c.id) > (%s, %s)
order by c.created_at, c.id
limit %s
""",
(user_id, cursor[0], cursor[1], limit),
).fetchall()
# --------------------------------------------------------------------------- #
# Messages
# --------------------------------------------------------------------------- #
def insert_message(conn, chat_id: str, sender_id: str, text: str) -> Dict:
return conn.execute(
"""
insert into messages (id, chat_id, sender_id, text, created_at)
values (%s, %s, %s, %s, %s)
returning id, chat_id, sender_id, text, created_at
""",
(str(uuid.uuid4()), chat_id, sender_id, text, utcnow()),
).fetchone()
def list_messages(
conn, chat_id: str, limit: int, cursor: Optional[CursorKey]
) -> List[Dict]:
if cursor is None:
return conn.execute(
"""
select id, chat_id, sender_id, text, created_at
from messages
where chat_id = %s
order by created_at, id
limit %s
""",
(chat_id, limit),
).fetchall()
return conn.execute(
"""
select id, chat_id, sender_id, text, created_at
from messages
where chat_id = %s and (created_at, id) > (%s, %s)
order by created_at, id
limit %s
""",
(chat_id, cursor[0], cursor[1], limit),
).fetchall()
# --------------------------------------------------------------------------- #
# Sessions (PostgreSQL is the source of truth)
# --------------------------------------------------------------------------- #
def insert_session(conn, token_hash: str, user_id: str, expires_at: dt.datetime) -> None:
conn.execute(
"""
insert into sessions (token_hash, user_id, created_at, expires_at)
values (%s, %s, %s, %s)
""",
(token_hash, user_id, utcnow(), expires_at),
)
def get_valid_session(conn, token_hash: str) -> Optional[Dict]:
return conn.execute(
"""
select token_hash, user_id, expires_at
from sessions
where token_hash = %s and expires_at > now()
""",
(token_hash,),
).fetchone()
def delete_session(conn, token_hash: str) -> None:
conn.execute("delete from sessions where token_hash = %s", (token_hash,))
def purge_expired_sessions(conn) -> int:
row = conn.execute(
"delete from sessions where expires_at <= now() returning token_hash"
).fetchall()
return len(row)
+33
View File
@@ -0,0 +1,33 @@
"""Password KDF (Argon2id) and opaque bearer-token helpers."""
from __future__ import annotations
import hashlib
import secrets
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerifyMismatchError, VerificationError
# Argon2id is the default of argon2-cffi's PasswordHasher. Parameters are kept
# modest so the local test suite stays fast while still using a real KDF.
_hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
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:
"""Opaque bearer token with >= 256 bits of entropy."""
return secrets.token_urlsafe(32)
def token_hash(token: str) -> str:
"""Sessions are identified by a SHA-256 of the token, never the token itself."""
return hashlib.sha256(token.encode("utf-8")).hexdigest()
+87
View File
@@ -0,0 +1,87 @@
"""Synthetic data seeder for EXPLAIN evidence (never used by the public smoke).
Runs INSIDE the api container so it can reach PostgreSQL over the compose
network:
docker compose exec -T api python -m src.seed --messages 10000
It writes a small number of users/chats and one "hot" chat with many messages,
then prints the hot chat id so the operator can run EXPLAIN against it.
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import uuid
from .db import pool
def _now() -> dt.datetime:
return dt.datetime.now(dt.timezone.utc)
def main() -> None:
parser = argparse.ArgumentParser(description="Seed synthetic chat history")
parser.add_argument("--users", type=int, default=10)
parser.add_argument("--chats", type=int, default=3)
parser.add_argument("--messages", type=int, default=10000)
args = parser.parse_args()
user_ids = [str(uuid.uuid4()) for _ in range(args.users)]
chat_ids = [str(uuid.uuid4()) for _ in range(args.chats)]
base = _now()
with pool().connection() as conn:
with conn.cursor() as cur:
cur.executemany(
"""
insert into users (id, username, display_name, password_hash, created_at)
values (%s, %s, %s, %s, %s)
""",
[
(uid, f"seed_{i}_{uuid.uuid4().hex[:6]}", f"Seed {i}", "seed-not-loginable", base)
for i, uid in enumerate(user_ids)
],
)
cur.executemany(
"insert into chats (id, title, created_at) values (%s, %s, %s)",
[(cid, f"Seed chat {i}", base) for i, cid in enumerate(chat_ids)],
)
cur.executemany(
"insert into chat_members (chat_id, user_id) values (%s, %s)",
[(cid, uid) for cid in chat_ids for uid in user_ids],
)
hot_chat = chat_ids[0]
per_chat = max(1, args.messages // len(chat_ids))
rows = []
total = 0
for chat_index, cid in enumerate(chat_ids):
count = args.messages - total if chat_index == len(chat_ids) - 1 else per_chat
count = max(0, count)
for _ in range(count):
rows.append(
(
str(uuid.uuid4()),
cid,
user_ids[0],
"synthetic history message",
base,
)
)
total += count
cur.executemany(
"""
insert into messages (id, chat_id, sender_id, text, created_at)
values (%s, %s, %s, %s, %s)
""",
rows,
)
print(json.dumps({"hot_chat_id": hot_chat, "messages": args.messages, "chats": chat_ids}))
if __name__ == "__main__":
main()
+131
View File
@@ -0,0 +1,131 @@
"""Sessions: PostgreSQL is the source of truth, Valkey is a read-through cache.
Design:
* ``sessions`` rows in PostgreSQL decide validity (``expires_at > now()``).
* Valkey caches ``session:{token_hash} -> user_id`` with a TTL equal to the
remaining session lifetime.
* If Valkey is unreachable the cache is bypassed transparently and the API
keeps authenticating from PostgreSQL (Valkey is never trusted as authority).
Every cache operation is bounded by a hard timeout and guarded by a tiny
circuit breaker. A stopped Valkey container can make Docker DNS itself block
for several seconds; without this guard a cache outage would stall request
handling. On any failure the breaker skips the cache for a few seconds.
"""
from __future__ import annotations
import concurrent.futures
import datetime as dt
import logging
import time
from typing import Optional, Tuple
import redis
from redis.backoff import NoBackoff
from redis.retry import Retry
from . import repositories as repo
from . import security
from .config import settings
logger = logging.getLogger("messenger.sessions")
_client: Optional[redis.Redis] = None
_client_disabled = False
_executor = concurrent.futures.ThreadPoolExecutor(max_workers=2, thread_name_prefix="cache")
_OP_TIMEOUT = 0.5
_BREAKER_SECONDS = 5.0
_breaker_until = 0.0
def _cache() -> Optional[redis.Redis]:
global _client, _client_disabled
if not settings.cache_enabled or _client_disabled:
return None
if _client is None:
try:
_client = redis.Redis.from_url(
settings.cache_url,
socket_timeout=0.2,
socket_connect_timeout=0.2,
health_check_interval=0,
retry_on_timeout=False,
retry=Retry(NoBackoff(), 0),
)
except (ValueError, redis.RedisError):
logger.warning("valkey client init failed; cache disabled")
_client_disabled = True
return None
return _client
def _guard(fn, *args):
"""Run a cache operation with a hard deadline and a small breaker."""
global _breaker_until
if time.monotonic() < _breaker_until:
return None
try:
return _executor.submit(fn, *args).result(timeout=_OP_TIMEOUT)
except (concurrent.futures.TimeoutError, redis.RedisError, OSError):
_breaker_until = time.monotonic() + _BREAKER_SECONDS
logger.warning("valkey unavailable; cache bypassed for %.0fs", _BREAKER_SECONDS)
return None
def _key(token_hash: str) -> str:
return f"session:{token_hash}"
def _cache_get(token_hash: str) -> Optional[str]:
client = _cache()
if client is None:
return None
value = _guard(lambda: client.get(_key(token_hash)))
if value is None:
return None
return value.decode("utf-8") if isinstance(value, bytes) else str(value)
def _cache_set(token_hash: str, user_id: str, ttl_seconds: float) -> None:
client = _cache()
if client is None:
return
_guard(lambda: client.set(_key(token_hash), user_id, ex=max(1, int(ttl_seconds))))
def _cache_delete(token_hash: str) -> None:
client = _cache()
if client is None:
return
_guard(lambda: client.delete(_key(token_hash)))
def create(conn, user_id: str) -> Tuple[str, dt.datetime]:
token = security.new_token()
hashed = security.token_hash(token)
expires_at = repo.utcnow() + dt.timedelta(seconds=settings.session_ttl_seconds)
repo.insert_session(conn, hashed, user_id, expires_at)
_cache_set(hashed, user_id, settings.session_ttl_seconds)
return token, expires_at
def resolve(conn, token: str) -> Optional[str]:
hashed = security.token_hash(token)
cached = _cache_get(hashed)
if cached is not None:
return cached
row = repo.get_valid_session(conn, hashed)
if row is None:
return None
user_id = str(row["user_id"])
remaining = (row["expires_at"] - repo.utcnow()).total_seconds()
if remaining > 0:
_cache_set(hashed, user_id, remaining)
return user_id
def revoke(conn, token: str) -> None:
hashed = security.token_hash(token)
repo.delete_session(conn, hashed)
_cache_delete(hashed)