This commit is contained in:
2026-10-13 19:11:11 +03:00
parent 0ab3a341aa
commit 4d877e0120
55 changed files with 4879 additions and 51 deletions
View File
+179
View File
@@ -0,0 +1,179 @@
"""Valkey session cache.
PostgreSQL is the source of truth for sessions. Valkey only keeps a short
lived copy of "token hash -> user" to avoid a SQL lookup on every request:
- key: messenger:session:<sha256(token)>, the raw token is never stored;
- value TTL: min(SESSION_CACHE_TTL_SECONDS, remaining session lifetime),
and expires_at is checked again on every read;
- logout writes a "revoked" tombstone (SET ... EX, overwrite), while cache
population uses SET ... NX, so a concurrent request cannot resurrect a
revoked session in the cache;
- any Valkey error or timeout is a cache miss: requests go to PostgreSQL and
the cache is skipped for CACHE_RETRY_AFTER_SECONDS. After such an error,
and on every API process start, the cache is flushed before its next use,
because an invalidation may have been lost while Valkey was unreachable
(also by a previous API process).
"""
from __future__ import annotations
import asyncio
import json
import logging
import math
import time
from datetime import datetime, timezone
from typing import Any
from uuid import UUID
from redis.asyncio import ConnectionPool, Redis
from redis.exceptions import RedisError
from app.config import settings
logger = logging.getLogger("messenger.cache")
KEY_PREFIX = "messenger:session:"
REVOKED = "revoked"
class Revoked:
"""Marker returned when the cache knows the session was revoked."""
REVOKED_SESSION = Revoked()
def _key(token_hash: str) -> str:
return KEY_PREFIX + token_hash
def _serialize(user: dict[str, Any], expires_at: datetime) -> str:
return json.dumps(
{
"id": str(user["id"]),
"username": user["username"],
"display_name": user["display_name"],
"created_at": user["created_at"].isoformat(),
"expires_at": expires_at.isoformat(),
},
separators=(",", ":"),
)
def _deserialize(raw: str) -> tuple[dict[str, Any], datetime]:
payload = json.loads(raw)
user = {
"id": UUID(payload["id"]),
"username": payload["username"],
"display_name": payload["display_name"],
"created_at": datetime.fromisoformat(payload["created_at"]),
}
return user, datetime.fromisoformat(payload["expires_at"])
class SessionCache:
def __init__(self, url: str | None) -> None:
self._client: Redis | None = None
self._unavailable_until = 0.0
# A process never trusts a cache it has not flushed itself: an
# earlier process may have lost an invalidation (logout while
# Valkey was unreachable) and that knowledge died with it.
# Cleared only after a successful FLUSHDB.
self._needs_flush = True
if url:
pool = ConnectionPool.from_url(
url,
max_connections=settings.cache_max_connections,
socket_timeout=settings.cache_timeout_seconds,
socket_connect_timeout=settings.cache_timeout_seconds,
decode_responses=True,
)
self._client = Redis(connection_pool=pool)
@property
def enabled(self) -> bool:
return self._client is not None
async def _run(self, operation):
"""Run one cache operation; return (ok, result)."""
if self._client is None:
return False, None
if time.monotonic() < self._unavailable_until:
return False, None
try:
async with asyncio.timeout(settings.cache_timeout_seconds * 2):
if self._needs_flush:
await self._client.flushdb()
self._needs_flush = False
logger.warning("session cache flushed before use")
return True, await operation(self._client)
except (RedisError, OSError, TimeoutError) as exc:
self._unavailable_until = (
time.monotonic() + settings.cache_retry_after_seconds
)
self._needs_flush = True
logger.warning(
"session cache unavailable, falling back to PostgreSQL: %s",
type(exc).__name__,
)
return False, None
async def get(
self,
token_hash: str,
) -> dict[str, Any] | Revoked | None:
ok, raw = await self._run(lambda client: client.get(_key(token_hash)))
if not ok or raw is None:
return None
if raw == REVOKED:
return REVOKED_SESSION
try:
user, expires_at = _deserialize(raw)
except (ValueError, KeyError, TypeError):
return None
if expires_at <= datetime.now(timezone.utc):
return None
return user
async def put(
self,
token_hash: str,
user: dict[str, Any],
expires_at: datetime,
) -> None:
remaining = (expires_at - datetime.now(timezone.utc)).total_seconds()
ttl = min(settings.session_cache_ttl_seconds, math.floor(remaining))
if ttl < 1:
return
value = _serialize(user, expires_at)
await self._run(
lambda client: client.set(_key(token_hash), value, ex=ttl, nx=True)
)
async def revoke(self, token_hash: str) -> None:
await self._run(
lambda client: client.set(
_key(token_hash),
REVOKED,
ex=settings.session_cache_ttl_seconds,
)
)
async def close(self) -> None:
if self._client is not None:
await self._client.aclose()
session_cache = SessionCache(settings.cache_url)
+112
View File
@@ -0,0 +1,112 @@
from dataclasses import dataclass
from pathlib import Path
import os
import socket
def read_value(name: str, default: str | None = None) -> str:
file_name = os.getenv(f"{name}_FILE")
if file_name:
return Path(file_name).read_text(encoding="utf-8").strip()
value = os.getenv(name, default)
if value is None:
raise RuntimeError(f"{name} is required.")
return value
def read_positive_int(name: str, default: str) -> int:
value = int(os.getenv(name, default))
if value < 1:
raise RuntimeError(f"{name} must be positive.")
return value
def read_positive_float(name: str, default: str) -> float:
value = float(os.getenv(name, default))
if value <= 0:
raise RuntimeError(f"{name} must be positive.")
return value
@dataclass(frozen=True)
class Settings:
app_host: str
app_port: int
database_url: str
session_ttl_seconds: int
# PostgreSQL connection pool and timeouts.
db_pool_size: int
db_max_overflow: int
db_pool_timeout_seconds: float
db_connect_timeout_seconds: float
db_statement_timeout_ms: int
# Valkey is a session cache; PostgreSQL stays the source of truth.
cache_url: str | None
session_cache_ttl_seconds: int
cache_timeout_seconds: float
cache_max_connections: int
cache_retry_after_seconds: float
# Lab3: X-Instance-Id is the container hostname (short Docker ID), stable
# for the process lifetime; scripts/stop-one.sh maps it to a container.
instance_id: str
idempotency_ttl_seconds: int
# Graceful shutdown: readiness answers 503 for shutdown_drain_seconds so
# the LB drops this replica, then uvicorn closes the listener and waits
# for in-flight requests up to shutdown_timeout_seconds.
shutdown_drain_seconds: float
shutdown_timeout_seconds: int
def load_settings() -> Settings:
session_store = os.getenv("SESSION_STORE", "postgres").lower()
if session_store not in {"postgres", "valkey", "redis"}:
raise RuntimeError("SESSION_STORE must be postgres, valkey or redis.")
cache_url = None
if session_store != "postgres":
cache_url = read_value("CACHE_URL")
return Settings(
app_host=os.getenv("APP_HOST", "0.0.0.0"),
app_port=int(os.getenv("APP_PORT", "8080")),
database_url=read_value("DATABASE_URL"),
session_ttl_seconds=read_positive_int("SESSION_TTL_SECONDS", "3600"),
db_pool_size=read_positive_int("DB_POOL_SIZE", "10"),
db_max_overflow=int(os.getenv("DB_MAX_OVERFLOW", "5")),
db_pool_timeout_seconds=read_positive_float("DB_POOL_TIMEOUT_SECONDS", "3"),
db_connect_timeout_seconds=read_positive_float(
"DB_CONNECT_TIMEOUT_SECONDS", "3"
),
db_statement_timeout_ms=read_positive_int("DB_STATEMENT_TIMEOUT_MS", "5000"),
cache_url=cache_url,
session_cache_ttl_seconds=read_positive_int(
"SESSION_CACHE_TTL_SECONDS", "60"
),
cache_timeout_seconds=read_positive_float("CACHE_TIMEOUT_SECONDS", "0.25"),
cache_max_connections=read_positive_int("CACHE_MAX_CONNECTIONS", "20"),
cache_retry_after_seconds=read_positive_float(
"CACHE_RETRY_AFTER_SECONDS", "5"
),
instance_id=os.getenv("INSTANCE_ID") or socket.gethostname(),
idempotency_ttl_seconds=read_positive_int(
"IDEMPOTENCY_TTL_SECONDS", "86400"
),
shutdown_drain_seconds=read_positive_float(
"SHUTDOWN_DRAIN_SECONDS", "3"
),
shutdown_timeout_seconds=read_positive_int(
"SHUTDOWN_TIMEOUT_SECONDS", "8"
),
)
settings = load_settings()
+57
View File
@@ -0,0 +1,57 @@
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from app.config import settings
database_url = settings.database_url.replace(
"postgresql://",
"postgresql+asyncpg://",
1,
)
# Bounded pool: at most db_pool_size + db_max_overflow connections per API
# process. Waiting for a free connection, connecting and every statement are
# limited, so an unavailable database produces a fast 503 instead of a hang.
engine = create_async_engine(
database_url,
pool_pre_ping=True,
pool_size=settings.db_pool_size,
max_overflow=settings.db_max_overflow,
pool_timeout=settings.db_pool_timeout_seconds,
pool_recycle=1800,
connect_args={
"timeout": settings.db_connect_timeout_seconds,
"command_timeout": settings.db_statement_timeout_ms / 1000 + 1,
"server_settings": {
"statement_timeout": str(settings.db_statement_timeout_ms),
"idle_in_transaction_session_timeout": "10000",
"application_name": "messenger-api",
},
},
)
SessionLocal = async_sessionmaker(
bind=engine,
expire_on_commit=False,
autoflush=False,
)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with SessionLocal() as session:
yield session
async def check_database_ready() -> bool:
try:
async with engine.connect() as connection:
await connection.exec_driver_sql("SELECT 1")
return True
except Exception:
return False
+61
View File
@@ -0,0 +1,61 @@
"""
FastAPI dependencies for Lab2:
- Bearer authentication;
- pagination query parameters.
"""
from typing import Optional
from fastapi import Depends, Query, Request, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPBasic, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from app.db import get_db
from app.errors import Unauthorized
from app.services import current_user_from_bearer_token
# Security schemes make the "Authorize" button in /docs send real
# Authorization headers. Errors keep the contract format: auto_error=False
# and our own 401 responses.
bearer_scheme = HTTPBearer(
scheme_name="Bearer",
auto_error=False,
description="Opaque session token from POST /api/v1/auth/sessions.",
)
class BasicForDocs(HTTPBasic):
"""Documents Basic auth; the header is parsed by app.security."""
async def __call__(self, request: Request) -> None: # type: ignore[override]
return None
basic_scheme = BasicForDocs(
scheme_name="Basic",
auto_error=False,
description="Only for POST /api/v1/auth/sessions.",
)
async def require_user(
credentials: Optional[HTTPAuthorizationCredentials] = Security(
bearer_scheme
),
db: AsyncSession = Depends(get_db),
) -> dict:
if credentials is None or not credentials.credentials.strip():
raise Unauthorized("Bearer")
return await current_user_from_bearer_token(
db,
credentials.credentials.strip(),
)
def pagination_params(
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None, min_length=1),
) -> tuple[int, Optional[str]]:
return limit, cursor
+107
View File
@@ -0,0 +1,107 @@
import re
from fastapi import Request
from fastapi.responses import JSONResponse
from uuid import uuid4
from app.config import settings
from app.lifecycle import draining
class ApiError(Exception):
def __init__(
self,
status_code: int,
code: str,
message: str,
headers: dict[str, str] | None = None,
) -> None:
self.status_code = status_code
self.code = code
self.message = message
self.headers = headers or {}
class InvalidRequest(ApiError):
def __init__(self, message: str = "Invalid request.") -> None:
super().__init__(400, "invalid_request", message)
class Unauthorized(ApiError):
def __init__(self, scheme: str = "Bearer") -> None:
if scheme == "Basic":
challenge = 'Basic realm="messenger", charset="UTF-8"'
else:
challenge = 'Bearer realm="messenger"'
super().__init__(
401,
"unauthorized",
"Authentication is required.",
{"WWW-Authenticate": challenge},
)
class NotFound(ApiError):
def __init__(self, message: str = "Object not found.") -> None:
super().__init__(404, "not_found", message)
class Conflict(ApiError):
def __init__(self, message: str = "Conflict.") -> None:
super().__init__(409, "conflict", message)
class Unavailable(ApiError):
def __init__(self) -> None:
super().__init__(503, "unavailable", "Service is unavailable.")
# X-Request-Id from HAProxy (or the client) is reused only if it is short and
# printable; anything else is replaced, so it cannot inject into logs.
REQUEST_ID_PATTERN = re.compile(r"[A-Za-z0-9._:-]{1,128}")
def incoming_request_id(request: Request) -> str:
value = request.headers.get("X-Request-Id", "")
if REQUEST_ID_PATTERN.fullmatch(value):
return value
return str(uuid4())
def request_id(request: Request) -> str:
return getattr(request.state, "request_id", str(uuid4()))
def common_headers(request: Request) -> dict[str, str]:
"""Headers of every API response, including errors (lab3: X-Instance-Id)."""
headers = {
"X-Request-Id": request_id(request),
"X-Instance-Id": settings.instance_id,
}
if draining.is_set():
# Ask HAProxy not to reuse the connection to a replica that is stopping.
headers["Connection"] = "close"
return headers
async def api_error_handler(
request: Request,
exc: ApiError,
) -> JSONResponse:
rid = request_id(request)
headers = {
**common_headers(request),
**exc.headers,
}
return JSONResponse(
status_code=exc.status_code,
content={
"error": {
"code": exc.code,
"message": exc.message,
"request_id": rid,
}
},
headers=headers,
)
+6
View File
@@ -0,0 +1,6 @@
"""Process lifecycle state shared by the server and request handlers."""
import threading
# Set on the first SIGTERM/SIGINT. While draining, /health/ready answers 503
# and responses carry "Connection: close", but requests are still served.
draining = threading.Event()
+356
View File
@@ -0,0 +1,356 @@
from __future__ import annotations
import logging
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from uuid import UUID
from fastapi import Depends, FastAPI, Header, Request, Response, Security
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from sqlalchemy import exc as sa_exc
from starlette.exceptions import HTTPException as StarletteHTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from app.cache import session_cache
from app.db import check_database_ready, engine, get_db
from app.deps import basic_scheme, pagination_params, require_user
from app.errors import (
ApiError,
Unavailable,
api_error_handler,
common_headers,
incoming_request_id,
)
from app.lifecycle import draining
from app.models import (
Chat,
ChatPage,
CreateChat,
CreateMessage,
CreateUser,
Health,
Message,
MessagePage,
Session,
User,
)
from app.services import (
create_chat,
create_message,
create_user_session,
get_chat,
list_chats,
list_messages,
logout_current_session,
register_user,
)
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
yield
await session_cache.close()
await engine.dispose()
app = FastAPI(
title="MTUSI Messenger — лабораторная 3",
version="1.3.0",
lifespan=lifespan,
)
@app.middleware("http")
async def add_request_id(request: Request, call_next):
request.state.request_id = incoming_request_id(request)
response = await call_next(request)
response.headers.update(common_headers(request))
return response
@app.exception_handler(ApiError)
async def handle_api_error(
request: Request,
exc: Exception,
) -> JSONResponse:
if not isinstance(exc, ApiError):
raise exc
return await api_error_handler(request, exc)
@app.exception_handler(StarletteHTTPException)
async def http_error_handler(
request: Request,
exc: StarletteHTTPException,
) -> JSONResponse:
# Unknown routes/methods: the contract error format instead of
# FastAPI's default {"detail": ...}.
if exc.status_code == 404:
error = ApiError(404, "not_found", "Route not found.")
else:
error = ApiError(exc.status_code, "invalid_request", "Invalid request.")
return await api_error_handler(request, error)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(
request: Request,
_exc: RequestValidationError,
) -> JSONResponse:
return JSONResponse(
status_code=400,
content={
"error": {
"code": "invalid_request",
"message": "Invalid request.",
"request_id": common_headers(request)["X-Request-Id"],
}
},
headers=common_headers(request),
)
logger = logging.getLogger("messenger.api")
def is_dependency_failure(exc: Exception) -> bool:
"""PostgreSQL is unreachable, restarting, overloaded or timed out."""
if isinstance(
exc,
(
sa_exc.OperationalError,
sa_exc.InterfaceError,
sa_exc.TimeoutError, # connection pool exhausted
OSError,
TimeoutError,
),
):
return True
return isinstance(exc, sa_exc.DBAPIError) and exc.connection_invalidated
async def dependency_error_handler(
request: Request,
exc: Exception,
) -> JSONResponse:
if not is_dependency_failure(exc):
return await unexpected_error_handler(request, exc)
logger.warning("database unavailable: %s", type(exc).__name__)
return await api_error_handler(request, Unavailable())
for _exc_class in (sa_exc.DBAPIError, sa_exc.TimeoutError, OSError, TimeoutError):
app.add_exception_handler(_exc_class, dependency_error_handler)
@app.exception_handler(Exception)
async def unexpected_error_handler(
request: Request,
exc: Exception,
) -> JSONResponse:
headers = common_headers(request)
# Only the type: SQL parameters and headers may contain secrets.
logger.error("unexpected error: %s", type(exc).__name__)
return JSONResponse(
status_code=500,
content={
"error": {
"code": "internal_error",
"message": "Internal server error.",
"request_id": headers["X-Request-Id"],
}
},
headers=headers,
)
@app.get(
"/health/live",
response_model=Health,
)
async def liveness() -> dict[str, str]:
return {"status": "ok"}
@app.get(
"/health/ready",
response_model=Health,
)
async def readiness() -> dict[str, str]:
# A draining replica reports "not ready" so HAProxy stops sending new
# requests to it before the listener is closed.
if draining.is_set() or not await check_database_ready():
raise Unavailable()
return {"status": "ok"}
@app.post(
"/api/v1/users",
status_code=201,
response_model=User,
)
async def register_user_route(
payload: CreateUser,
db: AsyncSession = Depends(get_db),
):
return await register_user(
db,
username=payload.username,
display_name=payload.display_name,
password=payload.password,
)
@app.post(
"/api/v1/auth/sessions",
status_code=201,
response_model=Session,
)
async def login(
request: Request,
db: AsyncSession = Depends(get_db),
_basic: None = Security(basic_scheme),
):
return await create_user_session(
db,
request.headers.get("Authorization"),
)
@app.delete(
"/api/v1/auth/sessions/current",
status_code=204,
)
async def logout(
request: Request,
db: AsyncSession = Depends(get_db),
_current_user: dict = Depends(require_user),
) -> Response:
_, _, token = request.headers["Authorization"].partition(" ")
await logout_current_session(
db,
token.strip(),
)
return Response(status_code=204)
@app.get(
"/api/v1/users/me",
response_model=User,
)
async def current_user_route(
current_user: dict = Depends(require_user),
):
return current_user
@app.post(
"/api/v1/chats",
status_code=201,
response_model=Chat,
)
async def create_chat_route(
payload: CreateChat,
current_user: dict = Depends(require_user),
db: AsyncSession = Depends(get_db),
):
return await create_chat(
db,
title=payload.title,
member_ids=payload.member_ids,
current_user=current_user,
)
@app.get(
"/api/v1/chats",
response_model=ChatPage,
)
async def list_chats_route(
page: tuple[int, str | None] = Depends(pagination_params),
current_user: dict = Depends(require_user),
db: AsyncSession = Depends(get_db),
):
limit, cursor = page
return await list_chats(
db,
limit=limit,
cursor=cursor,
current_user=current_user,
)
@app.get(
"/api/v1/chats/{chat_id}",
response_model=Chat,
)
async def get_chat_route(
chat_id: UUID,
current_user: dict = Depends(require_user),
db: AsyncSession = Depends(get_db),
):
return await get_chat(
db,
chat_id=chat_id,
current_user=current_user,
)
@app.post(
"/api/v1/chats/{chat_id}/messages",
status_code=201,
response_model=Message,
)
async def create_message_route(
chat_id: UUID,
payload: CreateMessage,
response: Response,
idempotency_key: str | None = Header(
default=None,
alias="Idempotency-Key",
),
current_user: dict = Depends(require_user),
db: AsyncSession = Depends(get_db),
):
message, replayed = await create_message(
db,
chat_id=chat_id,
text_value=payload.text,
idempotency_key=idempotency_key,
current_user=current_user,
)
if replayed:
response.headers["Idempotent-Replayed"] = "true"
return message
@app.get(
"/api/v1/chats/{chat_id}/messages",
response_model=MessagePage,
)
async def list_messages_route(
chat_id: UUID,
page: tuple[int, str | None] = Depends(pagination_params),
current_user: dict = Depends(require_user),
db: AsyncSession = Depends(get_db),
):
limit, cursor = page
return await list_messages(
db,
chat_id=chat_id,
limit=limit,
cursor=cursor,
current_user=current_user,
)
+149
View File
@@ -0,0 +1,149 @@
from __future__ import annotations
from datetime import datetime, timezone
from typing import Literal
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator
class ApiModel(BaseModel):
model_config = ConfigDict(extra="forbid")
class CreateUser(ApiModel):
username: str = Field(
min_length=3,
max_length=32,
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("username")
@classmethod
def username_is_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("username must not contain only spaces.")
return value
@field_validator("display_name")
@classmethod
def display_name_is_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError(
"display_name must not contain only spaces."
)
return value
@field_validator("password")
@classmethod
def password_is_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("password must not contain only spaces.")
return value
class User(ApiModel):
id: UUID
username: str
display_name: str
created_at: datetime
@field_validator("created_at")
@classmethod
def user_time_is_utc(cls, value: datetime) -> datetime:
if value.tzinfo is None:
raise ValueError("created_at must include UTC timezone.")
return value.astimezone(timezone.utc)
class CreateChat(ApiModel):
# Contract: 1-100 code points (lab2 allowed 255 by mistake).
title: str = Field(min_length=1, max_length=100)
member_ids: list[UUID] = Field(min_length=1)
@field_validator("title")
@classmethod
def title_is_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("title must not contain only spaces.")
return value
class Chat(ApiModel):
id: UUID
title: str
member_ids: list[UUID]
created_at: datetime
@field_validator("created_at")
@classmethod
def chat_time_is_utc(cls, value: datetime) -> datetime:
if value.tzinfo is None:
raise ValueError("created_at must include UTC timezone.")
return value.astimezone(timezone.utc)
class ChatPage(ApiModel):
items: list[Chat]
next_cursor: str | None = None
class CreateMessage(ApiModel):
text: str = Field(min_length=1, max_length=4000)
@field_validator("text")
@classmethod
def text_is_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("text must not contain only spaces.")
return value
class Message(ApiModel):
id: UUID
chat_id: UUID
sender_id: UUID
text: str
created_at: datetime
@field_validator("created_at")
@classmethod
def message_time_is_utc(cls, value: datetime) -> datetime:
if value.tzinfo is None:
raise ValueError("created_at must include UTC timezone.")
return value.astimezone(timezone.utc)
class MessagePage(ApiModel):
items: list[Message]
next_cursor: str | None = None
class Session(ApiModel):
token: str = Field(min_length=1)
token_type: Literal["Bearer"]
expires_at: datetime
user: User
@field_validator("expires_at")
@classmethod
def expiry_time_is_utc(cls, value: datetime) -> datetime:
if value.tzinfo is None:
raise ValueError("expires_at must include UTC timezone.")
return value.astimezone(timezone.utc)
class Health(ApiModel):
status: Literal["ok"]
class ErrorInner(ApiModel):
code: str = Field(min_length=1)
message: str = Field(min_length=1)
request_id: str = Field(min_length=1)
class Error(ApiModel):
error: ErrorInner
+446
View File
@@ -0,0 +1,446 @@
"""PostgreSQL repository functions for MTUSI Messenger Lab3."""
from __future__ import annotations
from collections.abc import Iterable
from datetime import datetime
from typing import Any
from uuid import UUID, uuid4
from sqlalchemy import text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
async def create_user(
db: AsyncSession,
*,
username: str,
display_name: str,
password_hash: str,
) -> dict[str, Any] | None:
user_id = uuid4()
try:
result = await db.execute(
text(
"""
INSERT INTO users (id, username, display_name, password_hash)
VALUES (:id, :username, :display_name, :password_hash)
RETURNING id, username, display_name, created_at
"""
),
{
"id": user_id,
"username": username,
"display_name": display_name,
"password_hash": password_hash,
},
)
await db.commit()
return dict(result.mappings().one())
except IntegrityError:
await db.rollback()
return None
async def get_user_by_username(
db: AsyncSession,
username: str,
) -> dict[str, Any] | None:
result = await db.execute(
text(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE username = :username
"""
),
{"username": username},
)
row = result.mappings().first()
return dict(row) if row is not None else None
async def get_user_by_id(
db: AsyncSession,
user_id: UUID,
) -> dict[str, Any] | None:
result = await db.execute(
text(
"""
SELECT id, username, display_name, created_at
FROM users
WHERE id = :user_id
"""
),
{"user_id": user_id},
)
row = result.mappings().first()
return dict(row) if row is not None else None
async def user_ids_that_exist(
db: AsyncSession,
member_ids: Iterable[UUID],
) -> set[UUID]:
values = list(member_ids)
if not values:
return set()
result = await db.execute(
text("SELECT id FROM users WHERE id = ANY(CAST(:member_ids AS uuid[]))"),
{"member_ids": values},
)
return {row.id for row in result}
async def create_session(
db: AsyncSession,
*,
user_id: UUID,
token_hash: str,
expires_at: datetime,
) -> None:
await db.execute(
text(
"""
INSERT INTO sessions (id, user_id, token_hash, expires_at)
VALUES (:id, :user_id, :token_hash, :expires_at)
"""
),
{
"id": uuid4(),
"user_id": user_id,
"token_hash": token_hash,
"expires_at": expires_at,
},
)
await db.commit()
async def get_active_session_user(
db: AsyncSession,
token_hash: str,
) -> dict[str, Any] | None:
result = await db.execute(
text(
"""
SELECT
s.id AS session_id,
s.token_hash,
s.expires_at,
u.id,
u.username,
u.display_name,
u.created_at
FROM sessions AS s
JOIN users AS u ON u.id = s.user_id
WHERE s.token_hash = :token_hash
AND s.revoked_at IS NULL
AND s.expires_at > now()
"""
),
{"token_hash": token_hash},
)
row = result.mappings().first()
return dict(row) if row is not None else None
async def revoke_active_session(
db: AsyncSession,
token_hash: str,
) -> bool:
result = await db.execute(
text(
"""
UPDATE sessions
SET revoked_at = now()
WHERE token_hash = :token_hash
AND revoked_at IS NULL
AND expires_at > now()
"""
),
{"token_hash": token_hash},
)
await db.commit()
return result.rowcount == 1
async def create_chat_with_members(
db: AsyncSession,
*,
title: str,
member_ids: Iterable[UUID],
) -> dict[str, Any]:
chat_id = uuid4()
members = list(member_ids)
try:
result = await db.execute(
text(
"""
INSERT INTO chats (id, title)
VALUES (:id, :title)
RETURNING id, title, created_at
"""
),
{"id": chat_id, "title": title},
)
chat = dict(result.mappings().one())
await db.execute(
text(
"""
INSERT INTO chat_members (chat_id, user_id)
VALUES (:chat_id, :user_id)
"""
),
[{"chat_id": chat_id, "user_id": user_id} for user_id in members],
)
await db.commit()
except Exception:
await db.rollback()
raise
chat["member_ids"] = members
return chat
async def get_accessible_chat(
db: AsyncSession,
*,
chat_id: UUID,
user_id: UUID,
) -> dict[str, Any] | None:
result = await db.execute(
text(
"""
SELECT c.id, c.title, c.created_at
FROM chats AS c
JOIN chat_members AS own_membership
ON own_membership.chat_id = c.id
AND own_membership.user_id = :user_id
WHERE c.id = :chat_id
"""
),
{"chat_id": chat_id, "user_id": user_id},
)
chat_row = result.mappings().first()
if chat_row is None:
return None
members_result = await db.execute(
text(
"""
SELECT user_id
FROM chat_members
WHERE chat_id = :chat_id
ORDER BY user_id ASC
"""
),
{"chat_id": chat_id},
)
chat = dict(chat_row)
chat["member_ids"] = [row.user_id for row in members_result]
return chat
async def list_chats_for_user(
db: AsyncSession,
*,
user_id: UUID,
limit: int,
cursor_created_at: datetime | None,
cursor_id: UUID | None,
) -> list[dict[str, Any]]:
query = """
SELECT c.id, c.title, c.created_at
FROM chats AS c
JOIN chat_members AS own_membership
ON own_membership.chat_id = c.id
AND own_membership.user_id = :user_id \
"""
params: dict[str, Any] = {
"user_id": user_id,
"limit_plus_one": limit + 1,
}
if cursor_created_at is not None and cursor_id is not None:
query += """
WHERE (c.created_at, c.id) > (:cursor_created_at, :cursor_id)
"""
params["cursor_created_at"] = cursor_created_at
params["cursor_id"] = cursor_id
query += " ORDER BY c.created_at ASC, c.id ASC LIMIT :limit_plus_one"
result = await db.execute(text(query), params)
chats = [dict(row) for row in result.mappings().all()]
if not chats:
return []
chat_ids = [chat["id"] for chat in chats]
members_result = await db.execute(
text(
"""
SELECT chat_id, user_id
FROM chat_members
WHERE chat_id = ANY(CAST(:chat_ids AS uuid[]))
ORDER BY chat_id ASC, user_id ASC
"""
),
{"chat_ids": chat_ids},
)
members_by_chat: dict[UUID, list[UUID]] = {chat_id: [] for chat_id in chat_ids}
for row in members_result:
members_by_chat[row.chat_id].append(row.user_id)
for chat in chats:
chat["member_ids"] = members_by_chat[chat["id"]]
return chats
async def create_message_idempotent(
db: AsyncSession,
*,
chat_id: UUID,
sender_id: UUID,
text_value: str,
idempotency_key: str,
request_hash: str,
ttl_seconds: int,
) -> tuple[dict[str, Any], bool] | None:
"""Insert a message at most once per idempotency key; one transaction.
1. INSERT the key row. Its primary key (user, chat, method, key) lives in
the shared PostgreSQL, so a concurrent request with the same key on
ANY replica blocks on this INSERT until the first transaction ends.
2. If the key was claimed: INSERT the message, link it to the key and
COMMIT both together. A failure before COMMIT rolls back both, so a
transient error is never stored as the final answer and a retry with
the same key simply runs again.
3. If the key already exists (committed by someone else): return the
stored message, or None when the body differs (-> 409).
A key older than ttl_seconds is reclaimed by the ON CONFLICT ... WHERE.
Returns (message, replayed) or None on a body mismatch.
"""
key_params = {
"user_id": sender_id,
"chat_id": chat_id,
"key": idempotency_key,
}
try:
claimed = await db.execute(
text(
"""
INSERT INTO idempotency_keys AS k
(user_id, chat_id, method, key, request_hash)
VALUES (:user_id, :chat_id, 'POST', :key, :request_hash)
ON CONFLICT (user_id, chat_id, method, key) DO UPDATE
SET request_hash = EXCLUDED.request_hash,
message_id = NULL,
created_at = now()
WHERE k.created_at < now() - make_interval(secs => :ttl)
RETURNING 1
"""
),
{**key_params, "request_hash": request_hash, "ttl": ttl_seconds},
)
if claimed.first() is not None:
result = await db.execute(
text(
"""
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES (:id, :chat_id, :sender_id, :text)
RETURNING id, chat_id, sender_id, text, created_at
"""
),
{
"id": uuid4(),
"chat_id": chat_id,
"sender_id": sender_id,
"text": text_value,
},
)
message = dict(result.mappings().one())
await db.execute(
text(
"""
UPDATE idempotency_keys
SET message_id = :message_id
WHERE user_id = :user_id
AND chat_id = :chat_id
AND method = 'POST'
AND key = :key
"""
),
{**key_params, "message_id": message["id"]},
)
await db.commit()
return message, False
stored = await db.execute(
text(
"""
SELECT k.request_hash,
m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM idempotency_keys AS k
JOIN messages AS m ON m.id = k.message_id
WHERE k.user_id = :user_id
AND k.chat_id = :chat_id
AND k.method = 'POST'
AND k.key = :key
"""
),
key_params,
)
row = stored.mappings().first()
await db.commit()
except Exception:
await db.rollback()
raise
if row is None:
# Not reachable while the key row and the message commit together.
raise RuntimeError("idempotency key without a message")
message = dict(row)
if message.pop("request_hash") != request_hash:
return None
return message, True
async def list_messages_keyset(
db: AsyncSession,
*,
chat_id: UUID,
limit: int,
cursor_created_at: datetime | None,
cursor_id: UUID | None,
) -> list[dict[str, Any]]:
query = """
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = :chat_id \
"""
params: dict[str, Any] = {
"chat_id": chat_id,
"limit_plus_one": limit + 1,
}
if cursor_created_at is not None and cursor_id is not None:
query += """
AND (created_at, id) > (:cursor_created_at, :cursor_id)
"""
params["cursor_created_at"] = cursor_created_at
params["cursor_id"] = cursor_id
query += " ORDER BY created_at ASC, id ASC LIMIT :limit_plus_one"
result = await db.execute(text(query), params)
return [dict(row) for row in result.mappings().all()]
+162
View File
@@ -0,0 +1,162 @@
from __future__ import annotations
import base64
import binascii
import hashlib
import json
import secrets
from datetime import datetime, timezone
from uuid import UUID
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerifyMismatchError
password_hasher = PasswordHasher()
def hash_password(password: str) -> str:
return password_hasher.hash(password)
def verify_password(password_hash: str, password: str) -> bool:
try:
return password_hasher.verify(password_hash, password)
except (VerifyMismatchError, InvalidHashError):
return False
def generate_session_token() -> str:
return secrets.token_urlsafe(32)
def hash_session_token(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def parse_basic_authorization(value: str | None) -> tuple[str, str] | None:
if value is None or not value.startswith("Basic "):
return None
try:
encoded_credentials = value[len("Basic "):]
decoded = base64.b64decode(
encoded_credentials,
validate=True,
).decode("utf-8")
username, password = decoded.split(":", 1)
except (
ValueError,
UnicodeDecodeError,
binascii.Error,
):
return None
if not username or not username.isascii():
return None
return username, password
def _encode_cursor_payload(payload: dict[str, str]) -> str:
raw = json.dumps(
payload,
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii")
def _decode_cursor_payload(cursor: str) -> dict[str, str] | None:
try:
raw = base64.urlsafe_b64decode(cursor.encode("ascii"))
payload = json.loads(raw.decode("utf-8"))
if not isinstance(payload, dict):
return None
return payload
except (
ValueError,
TypeError,
UnicodeDecodeError,
binascii.Error,
):
return None
def _utc_timestamp(value: datetime) -> str:
if value.tzinfo is None:
raise ValueError("Cursor datetime must be timezone-aware.")
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def encode_chat_cursor(
created_at: datetime,
chat_id: UUID,
) -> str:
return _encode_cursor_payload(
{
"kind": "chat",
"created_at": _utc_timestamp(created_at),
"id": str(chat_id),
}
)
def decode_chat_cursor(
cursor: str,
) -> tuple[datetime, UUID] | None:
payload = _decode_cursor_payload(cursor)
if payload is None or payload.get("kind") != "chat":
return None
try:
created_at = datetime.fromisoformat(
payload["created_at"].replace("Z", "+00:00")
)
chat_id = UUID(payload["id"])
except (KeyError, ValueError, AttributeError):
return None
return created_at, chat_id
def encode_message_cursor(
chat_id: UUID,
created_at: datetime,
message_id: UUID,
) -> str:
return _encode_cursor_payload(
{
"kind": "message",
"chat_id": str(chat_id),
"created_at": _utc_timestamp(created_at),
"id": str(message_id),
}
)
def decode_message_cursor(
cursor: str,
) -> tuple[UUID, datetime, UUID] | None:
payload = _decode_cursor_payload(cursor)
if payload is None or payload.get("kind") != "message":
return None
try:
chat_id = UUID(payload["chat_id"])
created_at = datetime.fromisoformat(
payload["created_at"].replace("Z", "+00:00")
)
message_id = UUID(payload["id"])
except (KeyError, ValueError, AttributeError):
return None
return chat_id, created_at, message_id
+70
View File
@@ -0,0 +1,70 @@
"""Entry point: uvicorn with a drain phase before the graceful shutdown.
Plain uvicorn stops accepting connections immediately on SIGTERM. Behind
HAProxy that turns every stop into a burst of refused connections until the
active health check notices. Instead, on the first signal:
t = 0 readiness -> 503, keep serving (Connection: close);
t = drain (3 s) HAProxy has marked the server DOWN (inter 1 s x fall 2),
uvicorn closes the listener and waits for in-flight
requests up to SHUTDOWN_TIMEOUT_SECONDS (8 s).
stop_grace_period in compose.yaml (15 s) is larger than 3 + 8 s.
A second signal skips the drain phase.
"""
import logging
import threading
import uvicorn
from app.config import settings
from app.lifecycle import draining
logger = logging.getLogger("messenger.server")
class DrainingServer(uvicorn.Server):
def handle_exit(self, sig, frame) -> None:
if draining.is_set():
super().handle_exit(sig, frame)
return
draining.set()
logger.warning(
"signal %s: draining for %.1f s before shutdown",
sig,
settings.shutdown_drain_seconds,
)
# Set should_exit directly instead of super().handle_exit(): uvicorn
# would re-raise the captured SIGTERM after shutdown and the process
# would exit with 143 instead of a clean 0.
timer = threading.Timer(
settings.shutdown_drain_seconds,
self._begin_shutdown,
)
timer.daemon = True
timer.start()
def _begin_shutdown(self) -> None:
logger.warning("drain finished: closing listener")
self.should_exit = True
def main() -> None:
config = uvicorn.Config(
"app.main:app",
host=settings.app_host,
port=settings.app_port,
proxy_headers=False,
# Longer than HAProxy "timeout http-keep-alive 10s": the LB closes an
# idle connection first, so it never reuses one the API just closed.
timeout_keep_alive=30,
timeout_graceful_shutdown=settings.shutdown_timeout_seconds,
log_level="info",
)
DrainingServer(config).run()
if __name__ == "__main__":
main()
+415
View File
@@ -0,0 +1,415 @@
"""Business rules for MTUSI Messenger Lab3."""
from __future__ import annotations
import hashlib
import json
import re
from datetime import datetime, timedelta, timezone
from typing import Any
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from app import repositories
from app.cache import REVOKED_SESSION, session_cache
from app.config import settings
from app.errors import ApiError
from app.security import (
decode_chat_cursor,
decode_message_cursor,
encode_chat_cursor,
encode_message_cursor,
generate_session_token,
hash_password,
hash_session_token,
parse_basic_authorization,
verify_password,
)
def _utc_now() -> datetime:
return datetime.now(timezone.utc)
def _to_user(row: dict[str, Any]) -> dict[str, Any]:
return {
"id": row["id"],
"username": row["username"],
"display_name": row["display_name"],
"created_at": row["created_at"],
}
def _to_chat(row: dict[str, Any]) -> dict[str, Any]:
return {
"id": row["id"],
"title": row["title"],
"member_ids": row["member_ids"],
"created_at": row["created_at"],
}
def _to_message(row: dict[str, Any]) -> dict[str, Any]:
return {
"id": row["id"],
"chat_id": row["chat_id"],
"sender_id": row["sender_id"],
"text": row["text"],
"created_at": row["created_at"],
}
def _bearer_unauthorized() -> ApiError:
return ApiError(
401,
"unauthorized",
"Authentication is required.",
headers={
"WWW-Authenticate": 'Bearer realm="messenger"',
},
)
def _basic_unauthorized() -> ApiError:
return ApiError(
401,
"unauthorized",
"Invalid credentials.",
headers={
"WWW-Authenticate": (
'Basic realm="messenger", charset="UTF-8"'
),
},
)
# Lab3 contract: ASCII [A-Za-z0-9._:-]{1,128}.
IDEMPOTENCY_KEY_PATTERN = re.compile(r"[A-Za-z0-9._:-]{1,128}")
def _invalid_request(message: str) -> ApiError:
return ApiError(400, "invalid_request", message)
def _not_found() -> ApiError:
return ApiError(404, "not_found", "Object not found.")
async def register_user(
db: AsyncSession,
*,
username: str,
display_name: str,
password: str,
) -> dict[str, Any]:
user = await repositories.create_user(
db,
username=username,
display_name=display_name,
password_hash=hash_password(password),
)
if user is None:
raise ApiError(
409,
"conflict",
"Username is already taken.",
)
return _to_user(user)
async def create_user_session(
db: AsyncSession,
authorization: str | None,
) -> dict[str, Any]:
credentials = parse_basic_authorization(authorization)
if credentials is None:
raise _basic_unauthorized()
username, password = credentials
user = await repositories.get_user_by_username(db, username)
if user is None or not verify_password(
user["password_hash"],
password,
):
raise _basic_unauthorized()
token = generate_session_token()
expires_at = _utc_now() + timedelta(
seconds=settings.session_ttl_seconds
)
await repositories.create_session(
db,
user_id=user["id"],
token_hash=hash_session_token(token),
expires_at=expires_at,
)
return {
"token": token,
"token_type": "Bearer",
"expires_at": expires_at,
"user": _to_user(user),
}
async def current_user_from_bearer_token(
db: AsyncSession,
token: str,
) -> dict[str, Any]:
token_hash = hash_session_token(token)
cached = await session_cache.get(token_hash)
if cached is REVOKED_SESSION:
raise _bearer_unauthorized()
if cached is not None:
return cached
# Cache miss or cache unavailable: PostgreSQL decides.
session_user = await repositories.get_active_session_user(db, token_hash)
if session_user is None:
raise _bearer_unauthorized()
user = _to_user(session_user)
await session_cache.put(token_hash, user, session_user["expires_at"])
return user
async def logout_current_session(
db: AsyncSession,
token: str,
) -> None:
token_hash = hash_session_token(token)
revoked = await repositories.revoke_active_session(db, token_hash)
if not revoked:
raise _bearer_unauthorized()
# Invalidate after COMMIT in the source of truth.
await session_cache.revoke(token_hash)
async def create_chat(
db: AsyncSession,
*,
title: str,
member_ids: list[UUID],
current_user: dict[str, Any],
) -> dict[str, Any]:
unique_member_ids = set(member_ids)
if len(unique_member_ids) != len(member_ids):
raise _invalid_request(
"member_ids must not contain duplicates."
)
if current_user["id"] not in unique_member_ids:
raise _invalid_request(
"The current user must be included in member_ids."
)
existing_ids = await repositories.user_ids_that_exist(
db,
unique_member_ids,
)
if existing_ids != unique_member_ids:
raise _invalid_request(
"One or more member_ids do not exist."
)
chat = await repositories.create_chat_with_members(
db,
title=title,
member_ids=member_ids,
)
return _to_chat(chat)
async def get_chat(
db: AsyncSession,
*,
chat_id: UUID,
current_user: dict[str, Any],
) -> dict[str, Any]:
chat = await repositories.get_accessible_chat(
db,
chat_id=chat_id,
user_id=current_user["id"],
)
if chat is None:
raise _not_found()
return _to_chat(chat)
async def list_chats(
db: AsyncSession,
*,
limit: int,
cursor: str | None,
current_user: dict[str, Any],
) -> dict[str, Any]:
cursor_created_at: datetime | None = None
cursor_id: UUID | None = None
if cursor is not None:
decoded = decode_chat_cursor(cursor)
if decoded is None:
raise _invalid_request("Invalid cursor.")
cursor_created_at, cursor_id = decoded
rows = await repositories.list_chats_for_user(
db,
user_id=current_user["id"],
limit=limit,
cursor_created_at=cursor_created_at,
cursor_id=cursor_id,
)
has_more = len(rows) > limit
page = rows[:limit]
next_cursor = None
if has_more and page:
last = page[-1]
next_cursor = encode_chat_cursor(
last["created_at"],
last["id"],
)
return {
"items": [_to_chat(row) for row in page],
"next_cursor": next_cursor,
}
def _request_fingerprint(text_value: str) -> str:
"""Hash of the validated body: key order and whitespace do not matter."""
canonical = json.dumps(
{"text": text_value},
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
async def create_message(
db: AsyncSession,
*,
chat_id: UUID,
text_value: str,
idempotency_key: str | None,
current_user: dict[str, Any],
) -> tuple[dict[str, Any], bool]:
"""Send a message once per (user, POST, chat, Idempotency-Key).
Returns (message, replayed). A replay re-checks the session (done by
require_user) and chat membership before returning the stored result.
"""
if idempotency_key is None or not IDEMPOTENCY_KEY_PATTERN.fullmatch(
idempotency_key
):
raise _invalid_request(
"Idempotency-Key header is required: [A-Za-z0-9._:-]{1,128}."
)
chat = await repositories.get_accessible_chat(
db,
chat_id=chat_id,
user_id=current_user["id"],
)
if chat is None:
raise _not_found()
result = await repositories.create_message_idempotent(
db,
chat_id=chat_id,
sender_id=current_user["id"],
text_value=text_value,
idempotency_key=idempotency_key,
request_hash=_request_fingerprint(text_value),
ttl_seconds=settings.idempotency_ttl_seconds,
)
if result is None:
raise ApiError(
409,
"conflict",
"Idempotency-Key was already used with a different body.",
)
message, replayed = result
return _to_message(message), replayed
async def list_messages(
db: AsyncSession,
*,
chat_id: UUID,
limit: int,
cursor: str | None,
current_user: dict[str, Any],
) -> dict[str, Any]:
chat = await repositories.get_accessible_chat(
db,
chat_id=chat_id,
user_id=current_user["id"],
)
if chat is None:
raise _not_found()
cursor_created_at: datetime | None = None
cursor_id: UUID | None = None
if cursor is not None:
decoded = decode_message_cursor(cursor)
if decoded is None:
raise _invalid_request("Invalid cursor.")
cursor_chat_id, cursor_created_at, cursor_id = decoded
if cursor_chat_id != chat_id:
raise _invalid_request(
"Cursor belongs to another chat."
)
rows = await repositories.list_messages_keyset(
db,
chat_id=chat_id,
limit=limit,
cursor_created_at=cursor_created_at,
cursor_id=cursor_id,
)
has_more = len(rows) > limit
page = rows[:limit]
next_cursor = None
if has_more and page:
last = page[-1]
next_cursor = encode_message_cursor(
chat_id,
last["created_at"],
last["id"],
)
return {
"items": [_to_message(row) for row in page],
"next_cursor": next_cursor,
}