Files
mtusi2026lab3/src/main.py
T

211 lines
8.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import asyncio
import logging
import re
import sys
import uuid
from contextlib import asynccontextmanager
import asyncpg
import signal
from fastapi import Depends, FastAPI, Request, Response
from fastapi.exceptions import RequestValidationError
from pydantic import BaseModel, ConfigDict
from starlette.exceptions import HTTPException
from . import config
from .auth import (BASIC_CHALLENGE, current_user, hash_password, new_token,
parse_basic, token_hash, verify_password)
from .chats import router as chats_router
from .common import iso, make_error_response, user_dict
from .db import create_pool_with_retry
from .cache import SessionCache
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] [req_id=%(request_id)s] %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
class RequestIdFilter(logging.Filter):
def filter(self, record):
if not hasattr(record, "request_id"):
record.request_id = "-"
return True
logger = logging.getLogger("messenger")
logger.addFilter(RequestIdFilter())
is_shutting_down = False
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}")
def _install_drain_handler(app: FastAPI) -> None:
"""SIGTERM: сначала /health/ready -> 503, и только через DRAIN_SECONDS обычное завершение uvicorn."""
loop = asyncio.get_running_loop()
original = signal.getsignal(signal.SIGTERM)
if not callable(original):
return
def on_sigterm(signum, frame):
if app.state.draining:
return
app.state.draining = True
logger.info("SIGTERM received: draining for %s s", config.DRAIN_SECONDS)
loop.call_soon_threadsafe(loop.call_later, config.DRAIN_SECONDS, original, signum, frame)
try:
signal.signal(signal.SIGTERM, on_sigterm)
except ValueError: # не главный поток (например, в тестах)
pass
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.draining = False
app.state.pool = await create_pool_with_retry()
app.state.cache = SessionCache(config.CACHE_URL)
_install_drain_handler(app)
yield
global is_shutting_down
is_shutting_down = True
await app.state.cache.close()
await app.state.pool.close()
logger.info("Application shutdown complete")
app = FastAPI(title="MTUSI Messenger - Lab 2", lifespan=lifespan)
app.include_router(chats_router, prefix="/api/v1")
@app.middleware("http")
async def middleware_pipeline(request: Request, call_next):
req_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = req_id
if is_shutting_down and request.url.path != "/health/live":
return make_error_response(503, "unavailable", "Server is shutting down", req_id)
logger.info(f"Incoming request {request.method} {request.url.path}", extra={"request_id": req_id})
response: Response = await call_next(request)
response.headers["X-Request-Id"] = req_id
response.headers["X-Instance-Id"] = config.INSTANCE_ID
response.headers["X-App-Version"] = config.APP_VERSION
logger.info(f"Completed {request.method} {request.url.path} with status {response.status_code}",
extra={"request_id": req_id})
return response
def _req_id(request: Request) -> str:
return getattr(request.state, "request_id", str(uuid.uuid4()))
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return make_error_response(400, "invalid_request", "Validation error", _req_id(request))
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
code = {
400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict",
413: "payload_too_large", 415: "unsupported_media_type", 429: "rate_limited", 503: "unavailable",
}.get(exc.status_code, "internal_error" if exc.status_code >= 500 else "invalid_request")
return make_error_response(exc.status_code, code, "Request failed", _req_id(request), exc.headers)
async def dependency_unavailable_handler(request: Request, exc: Exception):
"""БД недоступна или не ответила в срок: ограниченная 503, без деталей и без доверия анониму."""
logger.error("Dependency failure: %s", type(exc).__name__, extra={"request_id": _req_id(request)})
return make_error_response(503, "unavailable", "Service temporarily unavailable", _req_id(request))
for _exc in (asyncpg.PostgresError, asyncpg.InterfaceError, OSError, asyncio.TimeoutError):
app.add_exception_handler(_exc, dependency_unavailable_handler)
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
logger.error("Unhandled exception: %s", type(exc).__name__, extra={"request_id": _req_id(request)})
return make_error_response(500, "internal_error", "Internal server error", _req_id(request))
class StrictRequest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
class CreateUserRequest(StrictRequest):
username: str
display_name: str
password: str
@app.get("/health/live")
async def health_live():
return {"status": "ok"}
@app.get("/health/ready")
async def health_ready(request: Request):
# Критичная зависимость для готовности - PostgreSQL. При SIGTERM реплика сразу «не готова».
if request.app.state.draining:
return make_error_response(503, "unavailable", "Draining", _req_id(request))
await request.app.state.pool.fetchval("SELECT 1", timeout=2)
return {"status": "ok"}
@app.post("/api/v1/users", status_code=201)
async def register_user(req: CreateUserRequest, request: Request):
req_id = _req_id(request)
if not USERNAME_RE.fullmatch(req.username):
return make_error_response(400, "invalid_request", "Invalid username format", req_id)
if not (1 <= len(req.display_name) <= 100) or not req.display_name.strip() or "\x00" in req.display_name:
return make_error_response(400, "invalid_request", "Invalid display_name", req_id)
if not (12 <= len(req.password) <= 128):
return make_error_response(400, "invalid_request", "Invalid password length", req_id)
pw_hash = await hash_password(req.password)
try:
row = await request.app.state.pool.fetchrow(
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
"VALUES ($1, $2, $3, $4, clock_timestamp()) "
"RETURNING id, username, display_name, created_at",
uuid.uuid4(), req.username, req.display_name, pw_hash,
)
except asyncpg.UniqueViolationError: # гонку одинаковых username решает UNIQUE, а не SELECT
return make_error_response(409, "conflict", "Username already exists", req_id)
return user_dict(row)
@app.get("/api/v1/users/me")
async def get_current_user(user=Depends(current_user)):
return user_dict(user)
@app.post("/api/v1/auth/sessions", status_code=201)
async def create_session(request: Request):
req_id = _req_id(request)
creds = parse_basic(request.headers.get("Authorization"))
if creds is None:
return make_error_response(401, "unauthorized", "Unauthorized", req_id, BASIC_CHALLENGE)
username, password = creds
pool = request.app.state.pool
row = await pool.fetchrow(
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1", username
)
ok = await verify_password(row["password_hash"] if row else None, password)
if row is None or not ok:
return make_error_response(401, "unauthorized", "Unauthorized", req_id, BASIC_CHALLENGE)
token = new_token()
expires_at = await pool.fetchval(
"INSERT INTO sessions (token_hash, user_id, created_at, expires_at) "
"VALUES ($1, $2, now(), now() + make_interval(secs => $3)) RETURNING expires_at",
token_hash(token), row["id"], float(config.SESSION_TTL_SECONDS),
)
return {"token": token, "token_type": "Bearer", "expires_at": iso(expires_at), "user": user_dict(row)}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def logout(request: Request, user=Depends(current_user)):
await request.app.state.pool.execute(
"UPDATE sessions SET revoked_at = now() WHERE token_hash = $1", request.state.token_hash
)
await request.app.state.cache.delete(request.state.token_hash)
return Response(status_code=204)