Files
mtusi2026lab2/src/main.py
T

399 lines
14 KiB
Python

import base64
import binascii
import logging
import re
import time
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from uuid import UUID, uuid4
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from fastapi import FastAPI, Header, Query, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from psycopg import InterfaceError, OperationalError
from psycopg.errors import ForeignKeyViolation, UniqueViolation
from pydantic import BaseModel, ConfigDict, Field, field_validator
from redis.exceptions import RedisError
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException as StarletteHTTPException
from src.db import pool
from src.errors import ApiError, invalid, unauthorized
from src.pagination import encode_cursor, parse_page
from src.sessions import issue_session, redis_client
log = logging.getLogger("messenger")
password_hasher = PasswordHasher()
ready = False
def parse_uuid(value):
try:
return UUID(value)
except (ValueError, TypeError, AttributeError):
invalid("Некорректный UUID")
def row_response(row):
result = {}
for key, value in row.items():
if isinstance(value, UUID):
value = str(value)
elif isinstance(value, datetime):
value = value.astimezone(timezone.utc).isoformat(
timespec="microseconds"
).replace("+00:00", "Z")
elif key == "member_ids":
value = [str(member) for member in value]
result[key] = value
return result
class InputModel(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
@field_validator("*", check_fields=False)
@classmethod
def reject_blank(cls, value):
if isinstance(value, str) and not value.strip():
raise ValueError("Строка не должна быть пустой")
return value
@field_validator("display_name", "title", "text", check_fields=False)
@classmethod
def reject_nul(cls, value):
if "\u0000" in value:
raise ValueError("Нулевой символ недопустим в текстовом поле")
return value
class CreateUser(InputModel):
username: str = Field(min_length=3, max_length=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 validate_username(cls, value):
if re.fullmatch(r"[a-z0-9_]{3,32}", value) is None:
raise ValueError("Некорректный username")
return value
class CreateChat(InputModel):
title: str = Field(min_length=1, max_length=100)
member_ids: list[str] = Field(min_length=1, max_length=100)
class CreateMessage(InputModel):
text: str = Field(min_length=1, max_length=4000)
def bearer_token(value):
scheme, _, token = (value or "").partition(" ")
if scheme.lower() != "bearer" or not token:
unauthorized()
return token
def current_user(value):
token = bearer_token(value)
user_id = redis_client.get("session:" + token)
if user_id is None:
unauthorized()
with pool.connection() as conn:
user = conn.execute(
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
(UUID(user_id),),
).fetchone()
if user is None:
unauthorized()
return row_response(user)
@asynccontextmanager
async def lifespan(app):
global ready
try:
await run_in_threadpool(pool.open, wait=True, timeout=10)
await run_in_threadpool(redis_client.ping)
ready = True
log.info("startup ready=true")
yield
finally:
ready = False
redis_client.close()
pool.close()
log.info("shutdown complete")
app = FastAPI(title="Lab 2 Messenger", lifespan=lifespan)
def error_response(request, status, code, message):
request_id = request.state.request_id
headers = {"X-Request-Id": request_id}
if status == 401:
if request.method == "POST" and request.url.path == "/api/v1/auth/sessions":
headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"'
else:
headers["WWW-Authenticate"] = 'Bearer realm="messenger"'
return JSONResponse(
status_code=status,
content={"error": {"code": code, "message": message, "request_id": request_id}},
headers=headers,
)
@app.exception_handler(ApiError)
async def api_error(request, exc):
return error_response(request, exc.status, exc.code, exc.message)
@app.exception_handler(RequestValidationError)
async def validation_error(request, exc):
return error_response(request, 400, "invalid_request", "Некорректные поля или JSON")
@app.exception_handler(StarletteHTTPException)
async def http_error(request, exc):
code = "not_found" if exc.status_code == 404 else "invalid_request"
return error_response(request, exc.status_code, code, "Некорректный запрос")
@app.middleware("http")
async def process_request(request: Request, call_next):
request.state.request_id = str(uuid4())
started = time.perf_counter()
try:
is_login = request.method == "POST" and request.url.path == "/api/v1/auth/sessions"
public = request.method == "POST" and request.url.path in (
"/api/v1/users", "/api/v1/auth/sessions"
)
if request.url.path.startswith("/api/v1/") and not public:
request.state.user = await run_in_threadpool(
current_user, request.headers.get("Authorization")
)
if is_login:
if await request.body():
invalid("Для входа тело запроса должно быть пустым")
elif request.method == "POST" and request.url.path.startswith("/api/v1/"):
media_type = request.headers.get("content-type", "").split(";")[0]
if media_type.strip().lower() != "application/json":
raise ApiError(415, "unsupported_media_type", "Нужен application/json")
response = await call_next(request)
except ApiError as exc:
response = error_response(request, exc.status, exc.code, exc.message)
except (OperationalError, InterfaceError, RedisError):
response = error_response(request, 503, "unavailable", "Хранилище недоступно")
except Exception as exc:
# Не пишем body, Authorization, SQL или текст исключения в журнал.
log.error("request_failed type=%s request_id=%s",
type(exc).__name__, request.state.request_id)
response = error_response(request, 500, "internal_error", "Внутренняя ошибка")
response.headers["X-Request-Id"] = request.state.request_id
route = request.scope.get("route")
log.info("request method=%s route=%s status=%s duration_ms=%.2f request_id=%s",
request.method, getattr(route, "path", "unmatched"), response.status_code,
(time.perf_counter() - started) * 1000, request.state.request_id)
return response
@app.get("/health/live")
def live():
return {"status": "ok"}
@app.get("/health/ready")
def readiness():
if not ready:
raise ApiError(503, "unavailable", "Приложение не готово")
with pool.connection() as conn:
conn.execute("SELECT 1")
redis_client.ping()
return {"status": "ok"}
@app.post("/api/v1/users", status_code=201)
def create_user(body: CreateUser):
password_hash = password_hasher.hash(body.password)
try:
with pool.connection() as conn:
user = conn.execute(
"INSERT INTO users (id, username, display_name, password_hash) "
"VALUES (%s, %s, %s, %s) RETURNING id, username, display_name, created_at",
(uuid4(), body.username, body.display_name, password_hash),
).fetchone()
except UniqueViolation as exc:
if exc.diag.constraint_name == "users_username_key":
raise ApiError(409, "conflict", "Username занят") from None
raise
return row_response(user)
@app.post("/api/v1/auth/sessions", status_code=201)
def login(authorization: str | None = Header(default=None)):
scheme, _, encoded = (authorization or "").partition(" ")
if scheme.lower() != "basic" or not encoded:
unauthorized()
try:
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
username, password = decoded.split(":", 1)
except (ValueError, binascii.Error):
unauthorized()
if re.fullmatch(r"[a-z0-9_]{3,32}", username) is None or not 12 <= len(password) <= 128:
unauthorized()
with pool.connection() as conn:
user = conn.execute(
"SELECT id, username, display_name, password_hash, created_at "
"FROM users WHERE username = %s", (username,),
).fetchone()
if user is None:
unauthorized()
try:
password_hasher.verify(user["password_hash"], password)
except VerifyMismatchError:
unauthorized()
token, expires_at = issue_session(user["id"])
del user["password_hash"]
return {"token": token, "token_type": "Bearer", "expires_at": expires_at,
"user": row_response(user)}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def logout(request: Request):
token = bearer_token(request.headers.get("Authorization"))
redis_client.delete("session:" + token)
return Response(status_code=204)
@app.get("/api/v1/users/me")
def get_me(request: Request):
return request.state.user
def require_member(conn, chat_id, user_id):
found = conn.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, UUID(user_id)),
).fetchone()
if found is None:
raise ApiError(404, "not_found", "Чат не найден")
CHAT_SELECT = """
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members
WHERE chat_id = c.id ORDER BY user_id) AS member_ids
FROM chats c
JOIN chat_members mine ON mine.chat_id = c.id
WHERE mine.user_id = %s
"""
HISTORY_FIRST_SQL = """
SELECT id, chat_id, sender_id, text, created_at
FROM messages WHERE chat_id = %s
ORDER BY created_at, id LIMIT %s
"""
HISTORY_AFTER_SQL = """
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
"""
def page_response(rows, size, scope):
items = [row_response(row) for row in rows[:size]]
cursor = encode_cursor(scope, items[-1]) if len(rows) > size else None
return {"items": items, "next_cursor": cursor}
@app.post("/api/v1/chats", status_code=201)
def create_chat(body: CreateChat, request: Request):
members = sorted(parse_uuid(value) for value in body.member_ids)
if len(members) != len(set(members)):
invalid("Участники повторяются")
if UUID(request.state.user["id"]) not in members:
invalid("Вызывающий должен входить в member_ids")
try:
with pool.connection() as conn:
with conn.transaction():
chat = conn.execute(
"INSERT INTO chats (id, title) VALUES (%s, %s) "
"RETURNING id, title, created_at", (uuid4(), body.title),
).fetchone()
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
[(chat["id"], member) for member in members],
)
except ForeignKeyViolation:
invalid("Неизвестный участник")
chat["member_ids"] = members
return row_response(chat)
@app.get("/api/v1/chats")
def list_chats(request: Request, limit: str = Query(default="50"),
cursor: str | None = Query(default=None)):
user_id = request.state.user["id"]
scope = "chats:" + user_id
size, after = parse_page(limit, cursor, scope)
query = CHAT_SELECT
params = [UUID(user_id)]
if after is not None:
query += " AND (c.created_at, c.id) > (%s, %s)"
params.extend(after)
query += " ORDER BY c.created_at, c.id LIMIT %s"
params.append(size + 1)
with pool.connection() as conn:
rows = conn.execute(query, params).fetchall()
return page_response(rows, size, scope)
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: str, request: Request):
with pool.connection() as conn:
chat = conn.execute(
CHAT_SELECT + " AND c.id = %s",
(UUID(request.state.user["id"]), parse_uuid(chat_id)),
).fetchone()
if chat is None:
raise ApiError(404, "not_found", "Чат не найден")
return row_response(chat)
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def create_message(chat_id: str, body: CreateMessage, request: Request):
chat_uuid = parse_uuid(chat_id)
user_id = request.state.user["id"]
with pool.connection() as conn:
require_member(conn, chat_uuid, user_id)
message = conn.execute(
"INSERT INTO messages (id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s) "
"RETURNING id, chat_id, sender_id, text, created_at",
(uuid4(), chat_uuid, UUID(user_id), body.text),
).fetchone()
return row_response(message)
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(chat_id: str, request: Request, limit: str = Query(default="50"),
cursor: str | None = Query(default=None)):
chat_uuid = parse_uuid(chat_id)
scope = "messages:" + str(chat_uuid)
size, after = parse_page(limit, cursor, scope)
with pool.connection() as conn:
require_member(conn, chat_uuid, request.state.user["id"])
if after is None:
rows = conn.execute(HISTORY_FIRST_SQL, (chat_uuid, size + 1)).fetchall()
else:
rows = conn.execute(
HISTORY_AFTER_SQL, (chat_uuid, after[0], after[1], size + 1)
).fetchall()
return page_response(rows, size, scope)