520 lines
16 KiB
Python
520 lines
16 KiB
Python
"""Мессенджер: PostgreSQL хранит данные и сессии, Redis кеширует профили."""
|
||
|
||
import base64
|
||
import binascii
|
||
import json
|
||
from pathlib import Path
|
||
import logging
|
||
import re
|
||
from uuid import UUID, uuid4
|
||
|
||
from fastapi import FastAPI, HTTPException, Request
|
||
from fastapi.exceptions import RequestValidationError
|
||
from fastapi.responses import JSONResponse
|
||
from starlette.concurrency import run_in_threadpool
|
||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||
|
||
|
||
|
||
from psycopg import OperationalError, Error as DatabaseError
|
||
from psycopg_pool import PoolTimeout
|
||
|
||
from .auth import (
|
||
create_token,
|
||
format_datetime,
|
||
hash_password,
|
||
hash_token,
|
||
parse_basic,
|
||
parse_bearer,
|
||
session_expiration,
|
||
verify_password,
|
||
)
|
||
from .database import open_database, close_database, get_connection
|
||
from .user_repository import (
|
||
create_user as insert_user,
|
||
create_session,
|
||
find_session_user_cached,
|
||
find_user_by_username,
|
||
revoke_session,
|
||
serialize_user,
|
||
)
|
||
|
||
from .chat_repository import (
|
||
create_chat as insert_chat,
|
||
get_chat as find_chat,
|
||
list_chats as find_chats,
|
||
create_message as insert_message,
|
||
list_messages as find_messages,
|
||
)
|
||
|
||
app = FastAPI(title="MTUSI Messenger", version="1.5.0")
|
||
# Serve the mandatory contract in Swagger, including auth and request schemas.
|
||
OPENAPI_SCHEMA = json.loads(
|
||
(Path(__file__).resolve().parents[1] / "contracts/openapi.json").read_text()
|
||
)
|
||
app.openapi = lambda: OPENAPI_SCHEMA
|
||
|
||
INSTANCE_ID = str(uuid4())
|
||
|
||
logger = logging.getLogger("uvicorn.error")
|
||
|
||
ERROR_CODES = {
|
||
400: "invalid_request",
|
||
401: "unauthorized",
|
||
404: "not_found",
|
||
409: "conflict",
|
||
413: "payload_too_large",
|
||
415: "unsupported_media_type",
|
||
429: "rate_limited",
|
||
500: "internal_error",
|
||
503: "unavailable",
|
||
}
|
||
|
||
|
||
def error_response(request, status_code, code, message):
|
||
return JSONResponse(
|
||
status_code=status_code,
|
||
content={
|
||
"error": {
|
||
"code": code,
|
||
"message": message,
|
||
"request_id": request.state.request_id,
|
||
}
|
||
},
|
||
)
|
||
|
||
|
||
@app.middleware("http")
|
||
async def request_id_middleware(request: Request, call_next):
|
||
request.state.request_id = str(uuid4())
|
||
try:
|
||
response = await call_next(request)
|
||
except Exception:
|
||
# Логируем путь, метод и request_id, но НЕ тело сообщения.
|
||
await run_in_threadpool(
|
||
logger.error,
|
||
"Unhandled error: %s %s request_id=%s",
|
||
request.method,
|
||
request.url.path,
|
||
request.state.request_id,
|
||
)
|
||
response = error_response(
|
||
request, 500, "internal_error", "Внутренняя ошибка сервера"
|
||
)
|
||
response.headers["X-Request-Id"] = request.state.request_id
|
||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||
return response
|
||
|
||
|
||
@app.exception_handler(StarletteHTTPException)
|
||
async def http_error_handler(request: Request, exc: StarletteHTTPException):
|
||
response = error_response(
|
||
request,
|
||
exc.status_code,
|
||
ERROR_CODES.get(exc.status_code, "invalid_request"),
|
||
str(exc.detail),
|
||
)
|
||
if exc.headers:
|
||
response.headers.update(exc.headers)
|
||
return response
|
||
|
||
|
||
@app.exception_handler(DatabaseError)
|
||
@app.exception_handler(PoolTimeout)
|
||
async def database_error_handler(request: Request, exc):
|
||
return error_response(request, 503, "unavailable", "База данных временно недоступна")
|
||
|
||
|
||
@app.exception_handler(RequestValidationError)
|
||
async def validation_error_handler(request: Request, exc: RequestValidationError):
|
||
return error_response(request, 400, "invalid_request", "Некорректные данные запроса")
|
||
|
||
|
||
async def read_json(request: Request):
|
||
"""415 — только для неправильного Content-Type; 400 — для неверного JSON."""
|
||
content_type = (
|
||
request.headers.get("content-type", "").split(";")[0].strip().lower()
|
||
)
|
||
if content_type != "application/json":
|
||
raise HTTPException(415, "Неподдерживаемый Content-Type")
|
||
|
||
try:
|
||
raw = bytearray()
|
||
async for chunk in request.stream():
|
||
if len(raw) + len(chunk) > 65536:
|
||
raise HTTPException(413, "JSON слишком большой")
|
||
raw.extend(chunk)
|
||
data = json.loads(raw)
|
||
except (ValueError, UnicodeError):
|
||
raise HTTPException(400, "Неверный JSON") from None
|
||
|
||
# [], строка, число, true, false, null — это корректный JSON,
|
||
# но НЕ объект, обязательный по контракту.
|
||
if not isinstance(data, dict):
|
||
raise HTTPException(400, "Ожидается JSON-объект")
|
||
return data
|
||
|
||
|
||
def get_current_user(request: Request):
|
||
token = parse_bearer(request.headers.get("Authorization"))
|
||
if token is None:
|
||
raise HTTPException(
|
||
401,
|
||
"Требуется действующий Bearer-токен",
|
||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||
)
|
||
|
||
try:
|
||
user = find_session_user_cached(hash_token(token))
|
||
except (OperationalError, PoolTimeout):
|
||
raise HTTPException(
|
||
503,
|
||
"База данных временно недоступна",
|
||
) from None
|
||
if user is None:
|
||
raise HTTPException(
|
||
401,
|
||
"Недействительная или истёкшая сессия",
|
||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||
)
|
||
|
||
return user
|
||
|
||
|
||
def get_limit(request: Request):
|
||
"""Проверяем длину ДО int(): 5000 цифр должны дать 400, а не 500."""
|
||
limit_raw = request.query_params.get("limit", "50")
|
||
if not limit_raw.isascii() or not limit_raw.isdecimal():
|
||
raise HTTPException(400, "Неверный limit")
|
||
|
||
significant = limit_raw.lstrip("0")
|
||
if not significant or len(significant) > 3:
|
||
raise HTTPException(400, "Неверный limit")
|
||
|
||
limit = int(significant) # Теперь строка содержит максимум 3 цифры.
|
||
if not 1 <= limit <= 100:
|
||
raise HTTPException(400, "limit должен быть от 1 до 100")
|
||
return limit
|
||
|
||
|
||
def encode_cursor(first_id, last_id):
|
||
raw = f"{first_id}|{last_id}".encode("ascii")
|
||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||
|
||
|
||
def decode_cursor(cursor):
|
||
try:
|
||
if not cursor or len(cursor) > 256:
|
||
raise ValueError("empty or too long")
|
||
padded = cursor + "=" * (-len(cursor) % 4)
|
||
raw = base64.b64decode(
|
||
padded, altchars=b"-_", validate=True
|
||
).decode("ascii")
|
||
first_id, last_id = raw.split("|")
|
||
return str(UUID(first_id)), str(UUID(last_id))
|
||
except (ValueError, UnicodeError, binascii.Error):
|
||
raise HTTPException(400, "Неверный cursor") from None
|
||
|
||
|
||
# ---- Health ----
|
||
|
||
@app.get("/health/live")
|
||
def health_live():
|
||
return {"status": "ok"}
|
||
|
||
|
||
@app.get("/health/ready")
|
||
def health_ready():
|
||
try:
|
||
with get_connection() as conn:
|
||
conn.execute("SELECT 1")
|
||
from .storage import s3, BUCKET
|
||
s3.list_objects_v2(Bucket=BUCKET, Prefix="originals/", MaxKeys=1)
|
||
except (OperationalError, PoolTimeout):
|
||
raise HTTPException(503, "База данных недоступна") from None
|
||
return {"status": "ok"}
|
||
|
||
|
||
# ---- Users ----
|
||
|
||
@app.post("/api/v1/users", status_code=201)
|
||
async def create_user(request: Request):
|
||
data = await read_json(request)
|
||
|
||
if set(data) != {"username", "display_name", "password"}:
|
||
raise HTTPException(400, "Неверные поля пользователя")
|
||
|
||
username = data["username"]
|
||
display_name = data["display_name"]
|
||
password = data["password"]
|
||
|
||
if not isinstance(username, str) or not re.fullmatch(
|
||
r"[a-z0-9_]{3,32}", username
|
||
):
|
||
raise HTTPException(400, "Недопустимый username")
|
||
|
||
if (
|
||
not isinstance(display_name, str)
|
||
or not 1 <= len(display_name) <= 100
|
||
or not display_name.strip()
|
||
):
|
||
raise HTTPException(400, "Недопустимое имя пользователя")
|
||
|
||
if not isinstance(password, str) or not 12 <= len(password) <= 128:
|
||
raise HTTPException(400, "Пароль должен содержать 12–128 символов")
|
||
|
||
password_hash = await run_in_threadpool(hash_password, password)
|
||
user = await run_in_threadpool(insert_user, username, display_name, password_hash)
|
||
if user is None:
|
||
raise HTTPException(409, "Username уже занят")
|
||
|
||
return user
|
||
|
||
|
||
@app.get("/api/v1/users/me")
|
||
def get_me(request: Request):
|
||
return get_current_user(request)
|
||
|
||
|
||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||
def login(request: Request):
|
||
credentials = parse_basic(request.headers.get("Authorization"))
|
||
|
||
if credentials is None:
|
||
raise HTTPException(
|
||
401,
|
||
"Неверные учётные данные",
|
||
headers={
|
||
"WWW-Authenticate":
|
||
'Basic realm="messenger", charset="UTF-8"'
|
||
},
|
||
)
|
||
|
||
username, password = credentials
|
||
user_row = find_user_by_username(username)
|
||
|
||
if user_row is None or not verify_password(
|
||
user_row["password_hash"], password
|
||
):
|
||
raise HTTPException(
|
||
401,
|
||
"Неверные учётные данные",
|
||
headers={
|
||
"WWW-Authenticate":
|
||
'Basic realm="messenger", charset="UTF-8"'
|
||
},
|
||
)
|
||
|
||
token = create_token()
|
||
expires_at = session_expiration()
|
||
|
||
create_session(user_row["id"], hash_token(token), expires_at)
|
||
|
||
return {
|
||
"token": token,
|
||
"token_type": "Bearer",
|
||
"expires_at": format_datetime(expires_at),
|
||
"user": serialize_user(user_row),
|
||
}
|
||
|
||
|
||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||
def logout(request: Request):
|
||
get_current_user(request)
|
||
token = parse_bearer(request.headers.get("Authorization"))
|
||
|
||
from .session_cache import invalidate_session
|
||
|
||
if not revoke_session(hash_token(token)):
|
||
raise HTTPException(
|
||
401,
|
||
"Недействительная сессия",
|
||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||
)
|
||
|
||
invalidate_session(hash_token(token))
|
||
|
||
from fastapi import Response
|
||
return Response(status_code=204)
|
||
|
||
|
||
|
||
# ---- Chats ----
|
||
|
||
|
||
@app.post("/api/v1/chats", status_code=201)
|
||
async def create_chat(request: Request):
|
||
user = await run_in_threadpool(get_current_user, request)
|
||
data = await read_json(request)
|
||
|
||
if set(data) != {"title", "member_ids"}:
|
||
raise HTTPException(400, "Неверные поля чата")
|
||
|
||
title = data["title"]
|
||
member_ids = data["member_ids"]
|
||
|
||
if not isinstance(title, str) or not 1 <= len(title) <= 100 or not title.strip():
|
||
raise HTTPException(400, "Недопустимое название чата")
|
||
|
||
if not isinstance(member_ids, list) or not 1 <= len(member_ids) <= 100:
|
||
raise HTTPException(400, "Неверный список участников")
|
||
|
||
normalized_ids = []
|
||
|
||
for member_id in member_ids:
|
||
if not isinstance(member_id, str):
|
||
raise HTTPException(400, "Неверный ID участника")
|
||
|
||
try:
|
||
normalized_ids.append(str(UUID(member_id)))
|
||
except ValueError:
|
||
raise HTTPException(400, "Неверный UUID участника") from None
|
||
|
||
if len(normalized_ids) != len(set(normalized_ids)):
|
||
raise HTTPException(400, "Участники повторяются")
|
||
|
||
if user["id"] not in normalized_ids:
|
||
raise HTTPException(400, "Создатель должен быть участником")
|
||
|
||
chat = await run_in_threadpool(insert_chat, user["id"], title, normalized_ids)
|
||
|
||
if chat is None:
|
||
raise HTTPException(400, "Неизвестный участник")
|
||
|
||
return chat
|
||
|
||
|
||
@app.get("/api/v1/chats")
|
||
def list_chats(request: Request):
|
||
user = get_current_user(request)
|
||
limit = get_limit(request)
|
||
cursor = request.query_params.get("cursor")
|
||
|
||
last_chat_id = None
|
||
|
||
if cursor is not None:
|
||
cursor_user_id, last_chat_id = decode_cursor(cursor)
|
||
|
||
if cursor_user_id != user["id"]:
|
||
raise HTTPException(400, "Неверный cursor")
|
||
|
||
rows = find_chats(user["id"], limit, last_chat_id)
|
||
|
||
if rows is None:
|
||
raise HTTPException(400, "Неверный cursor")
|
||
|
||
has_more = len(rows) > limit
|
||
page = rows[:limit]
|
||
|
||
next_cursor = (
|
||
encode_cursor(user["id"], page[-1]["id"])
|
||
if has_more and page
|
||
else None
|
||
)
|
||
|
||
return {"items": page, "next_cursor": next_cursor}
|
||
|
||
|
||
@app.get("/api/v1/chats/{chat_id}")
|
||
def get_chat(chat_id: str, request: Request):
|
||
user = get_current_user(request)
|
||
|
||
try:
|
||
chat_id = str(UUID(chat_id))
|
||
except ValueError:
|
||
raise HTTPException(400, "Неверный UUID чата") from None
|
||
|
||
chat = find_chat(chat_id, user["id"])
|
||
|
||
if chat is None:
|
||
raise HTTPException(404, "Чат не найден")
|
||
|
||
return chat
|
||
|
||
|
||
# ---- Messages ----
|
||
|
||
|
||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||
async def send_message(chat_id: str, request: Request):
|
||
user = await run_in_threadpool(get_current_user, request)
|
||
chat = await run_in_threadpool(get_chat, chat_id, request)
|
||
data = await read_json(request)
|
||
|
||
if "text" not in data or set(data) - {"text", "attachment_ids"}:
|
||
raise HTTPException(400, "Неверные поля сообщения")
|
||
|
||
text = data["text"]
|
||
|
||
attachment_ids = data.get("attachment_ids", [])
|
||
if not isinstance(attachment_ids, list) or len(attachment_ids) > 10:
|
||
raise HTTPException(400, "Неверный список вложений")
|
||
try:
|
||
if any(not isinstance(a, str) for a in attachment_ids):
|
||
raise ValueError()
|
||
attachment_ids = [str(UUID(a)) for a in attachment_ids]
|
||
if len(set(attachment_ids)) != len(attachment_ids):
|
||
raise ValueError()
|
||
except ValueError:
|
||
raise HTTPException(400, "Неверные ID вложений") from None
|
||
if not isinstance(text, str) or len(text) > 4000 or (not text.strip() and not attachment_ids):
|
||
raise HTTPException(400, "Недопустимый текст сообщения")
|
||
|
||
key = request.headers.get("Idempotency-Key", "")
|
||
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
|
||
raise HTTPException(400, "Неверный Idempotency-Key")
|
||
message = await run_in_threadpool(insert_message, chat["id"], user["id"], text, key, attachment_ids)
|
||
if message == "attachment_failed":
|
||
raise HTTPException(409, "Обработка вложения завершилась ошибкой")
|
||
if message == "conflict":
|
||
raise HTTPException(409, "Ключ использован для другого сообщения")
|
||
|
||
if message is None:
|
||
raise HTTPException(404, "Чат не найден")
|
||
|
||
return message
|
||
|
||
|
||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||
def list_messages(chat_id: str, request: Request):
|
||
chat = get_chat(chat_id, request)
|
||
limit = get_limit(request)
|
||
cursor = request.query_params.get("cursor")
|
||
|
||
last_message_id = None
|
||
|
||
if cursor is not None:
|
||
cursor_chat_id, last_message_id = decode_cursor(cursor)
|
||
|
||
if cursor_chat_id != chat["id"]:
|
||
raise HTTPException(400, "Неверный cursor")
|
||
|
||
rows = find_messages(chat["id"], limit, last_message_id)
|
||
|
||
if rows is None:
|
||
raise HTTPException(400, "Неверный cursor")
|
||
|
||
has_more = len(rows) > limit
|
||
page = rows[:limit]
|
||
|
||
next_cursor = (
|
||
encode_cursor(chat["id"], page[-1]["id"])
|
||
if has_more and page
|
||
else None
|
||
)
|
||
|
||
return {"items": page, "next_cursor": next_cursor}
|
||
|
||
|
||
@app.on_event("startup")
|
||
async def start_database_pool():
|
||
await run_in_threadpool(open_database)
|
||
|
||
|
||
@app.on_event("shutdown")
|
||
async def stop_database_pool():
|
||
await run_in_threadpool(close_database)
|
||
|
||
from .attachments import register
|
||
register(app, get_current_user, get_chat)
|