361 lines
12 KiB
Python
361 lines
12 KiB
Python
import json
|
|
import logging
|
|
import os
|
|
import re
|
|
import uuid
|
|
from contextlib import asynccontextmanager
|
|
|
|
import anyio
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse, Response
|
|
from pydantic import ValidationError
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
from errors import ApiError, DependencyDown, IdempotencyConflict, error_body
|
|
from schemas import CreateChat, CreateMessage, CreateUser
|
|
from store import Store, instance_id
|
|
|
|
LOGGER = logging.getLogger("messenger")
|
|
store = Store()
|
|
INSTANCE_ID = instance_id()
|
|
|
|
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
|
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
|
IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
|
MAX_JSON_BYTES = 65536
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(_app):
|
|
await anyio.to_thread.run_sync(store.startup)
|
|
yield
|
|
store.shutting_down = True
|
|
await anyio.to_thread.run_sync(store.shutdown)
|
|
|
|
|
|
app = FastAPI(
|
|
title="mtusi-messenger",
|
|
version="lab3",
|
|
lifespan=lifespan,
|
|
redirect_slashes=False,
|
|
docs_url="/docs",
|
|
redoc_url=None,
|
|
openapi_url="/openapi.json",
|
|
)
|
|
|
|
|
|
def request_id_of(request: Request):
|
|
rid = getattr(request.state, "request_id", None)
|
|
if rid:
|
|
return rid
|
|
return str(uuid.uuid4())
|
|
|
|
|
|
def stamp(request: Request, response):
|
|
response.headers["X-Request-Id"] = request_id_of(request)
|
|
response.headers["X-Instance-Id"] = INSTANCE_ID
|
|
return response
|
|
|
|
|
|
def json_ok(request: Request, payload, status_code=200):
|
|
return stamp(request, JSONResponse(payload, status_code=status_code))
|
|
|
|
|
|
def json_error(request: Request, status, code, message, extra_headers=None):
|
|
headers = {"X-Request-Id": request_id_of(request), "X-Instance-Id": INSTANCE_ID}
|
|
if extra_headers:
|
|
headers.update(extra_headers)
|
|
return JSONResponse(error_body(code, message, request_id_of(request)), status_code=status, headers=headers)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def wrap_request(request: Request, call_next):
|
|
incoming = request.headers.get("X-Request-Id", "")
|
|
if incoming and len(incoming) <= 200 and incoming.isprintable() and incoming.strip():
|
|
request.state.request_id = incoming.strip()
|
|
else:
|
|
request.state.request_id = str(uuid.uuid4())
|
|
if store.shutting_down and request.url.path != "/health/live":
|
|
return json_error(request, 503, "unavailable", "Сервис временно недоступен")
|
|
response = await call_next(request)
|
|
return stamp(request, response)
|
|
|
|
|
|
@app.exception_handler(ApiError)
|
|
async def api_error_handler(request: Request, exc: ApiError):
|
|
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def request_validation_handler(request: Request, _exc: RequestValidationError):
|
|
return json_error(request, 400, "invalid_request", "Некорректный запрос")
|
|
|
|
|
|
@app.exception_handler(ValidationError)
|
|
async def pydantic_handler(request: Request, _exc: ValidationError):
|
|
return json_error(request, 400, "invalid_request", "Некорректный запрос")
|
|
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
|
if exc.status_code == 404:
|
|
return json_error(request, 404, "not_found", "Объект не найден")
|
|
return json_error(request, exc.status_code if exc.status_code < 500 else 500, "invalid_request", "Некорректный запрос")
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
async def unexpected_handler(request: Request, exc: Exception):
|
|
if isinstance(exc, ApiError):
|
|
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
|
|
LOGGER.exception("unhandled")
|
|
return json_error(request, 500, "internal_error", "Внутренняя ошибка")
|
|
|
|
|
|
def unavailable():
|
|
raise ApiError(503, "unavailable", "Сервис временно недоступен")
|
|
|
|
|
|
def bearer_unauthorized():
|
|
raise ApiError(401, "unauthorized", "Требуется авторизация", {"WWW-Authenticate": BEARER_CHALLENGE})
|
|
|
|
|
|
def basic_unauthorized():
|
|
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": BASIC_CHALLENGE})
|
|
|
|
|
|
def invalid():
|
|
raise ApiError(400, "invalid_request", "Некорректный запрос")
|
|
|
|
|
|
async def call_store(func, *args):
|
|
try:
|
|
return await anyio.to_thread.run_sync(func, *args)
|
|
except DependencyDown:
|
|
unavailable()
|
|
except IdempotencyConflict:
|
|
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
|
|
|
|
|
|
def parse_basic(request: Request):
|
|
header = request.headers.get("Authorization", "")
|
|
if not header.lower().startswith("basic "):
|
|
basic_unauthorized()
|
|
raw = header.split(" ", 1)[1].strip()
|
|
try:
|
|
import base64
|
|
|
|
decoded = base64.b64decode(raw, validate=True).decode("utf-8")
|
|
except (ValueError, UnicodeError):
|
|
basic_unauthorized()
|
|
if ":" not in decoded:
|
|
basic_unauthorized()
|
|
username, password = decoded.split(":", 1)
|
|
return username, password
|
|
|
|
|
|
def parse_bearer(request: Request):
|
|
header = request.headers.get("Authorization", "")
|
|
# Basic на бизнес-методе не открывает сессию. X-User-Id не смотрим.
|
|
if not header.lower().startswith("bearer "):
|
|
bearer_unauthorized()
|
|
token = header.split(" ", 1)[1].strip()
|
|
if len(token) < 32 or len(token) > 512 or any(ch.isspace() for ch in token):
|
|
bearer_unauthorized()
|
|
return token
|
|
|
|
|
|
async def current_user(request: Request):
|
|
token = parse_bearer(request)
|
|
user = await call_store(store.user_for_token, token)
|
|
if user is None:
|
|
bearer_unauthorized()
|
|
request.state.user_id = user["id"]
|
|
request.state.token = token
|
|
return user
|
|
|
|
|
|
def parse_chat_id(chat_id):
|
|
try:
|
|
return str(uuid.UUID(chat_id))
|
|
except ValueError:
|
|
invalid()
|
|
|
|
|
|
def parse_limit(raw):
|
|
if raw is None:
|
|
return 50
|
|
if not isinstance(raw, str) or len(raw) > 3 or not raw.isdigit():
|
|
invalid()
|
|
value = int(raw)
|
|
if value < 1 or value > 100:
|
|
invalid()
|
|
return value
|
|
|
|
|
|
async def read_json(request: Request):
|
|
ctype = request.headers.get("content-type", "")
|
|
if "application/json" not in ctype.lower():
|
|
raise ApiError(415, "unsupported_media_type", "Нужен application/json")
|
|
length = request.headers.get("content-length")
|
|
if length is not None and (not length.isdigit() or int(length) > MAX_JSON_BYTES):
|
|
raise ApiError(413, "payload_too_large", "Слишком большое тело")
|
|
raw = await request.body()
|
|
if len(raw) > MAX_JSON_BYTES:
|
|
raise ApiError(413, "payload_too_large", "Слишком большое тело")
|
|
try:
|
|
payload = json.loads(raw)
|
|
except (ValueError, UnicodeError):
|
|
invalid()
|
|
if not isinstance(payload, dict):
|
|
invalid()
|
|
return payload
|
|
|
|
|
|
def parse_idempotency_key(request: Request):
|
|
key = request.headers.get("Idempotency-Key")
|
|
if key is None or not IDEMPOTENCY_RE.fullmatch(key):
|
|
invalid()
|
|
return key
|
|
|
|
|
|
@app.get("/health/live")
|
|
async def liveness(request: Request):
|
|
return json_ok(request, {"status": "ok"})
|
|
|
|
|
|
@app.get("/health/ready")
|
|
async def readiness(request: Request):
|
|
if store.shutting_down:
|
|
raise ApiError(503, "unavailable", "Сервис временно недоступен")
|
|
ok = await call_store(store.ready)
|
|
if not ok:
|
|
unavailable()
|
|
return json_ok(request, {"status": "ok"})
|
|
|
|
|
|
@app.post("/api/v1/users", status_code=201)
|
|
async def register_user(request: Request, body: CreateUser):
|
|
user = await call_store(store.create_user, body.username, body.display_name, body.password)
|
|
if user is None:
|
|
raise ApiError(409, "conflict", "Имя пользователя занято")
|
|
return json_ok(request, user, 201)
|
|
|
|
|
|
@app.post("/api/v1/auth/sessions", status_code=201)
|
|
async def create_session(request: Request):
|
|
username, password = parse_basic(request)
|
|
session = await call_store(store.login, username, password)
|
|
if session is None:
|
|
basic_unauthorized()
|
|
request.state.user_id = session["user"]["id"]
|
|
return json_ok(request, session, 201)
|
|
|
|
|
|
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
|
async def revoke_session(request: Request):
|
|
user = await current_user(request)
|
|
request.state.user_id = user["id"]
|
|
removed = await call_store(store.revoke, request.state.token)
|
|
if not removed:
|
|
bearer_unauthorized()
|
|
return stamp(request, Response(status_code=204))
|
|
|
|
|
|
@app.get("/api/v1/users/me")
|
|
async def me(request: Request):
|
|
user = await current_user(request)
|
|
return json_ok(request, user)
|
|
|
|
|
|
@app.post("/api/v1/chats", status_code=201)
|
|
async def create_chat(request: Request):
|
|
user = await current_user(request)
|
|
payload = await read_json(request)
|
|
try:
|
|
body = CreateChat.model_validate(payload)
|
|
except ValidationError:
|
|
invalid()
|
|
try:
|
|
chat = await call_store(store.create_chat, body.title, body.member_ids, user["id"])
|
|
except ValueError:
|
|
invalid()
|
|
return json_ok(request, chat, 201)
|
|
|
|
|
|
@app.get("/api/v1/chats")
|
|
async def list_chats(request: Request):
|
|
user = await current_user(request)
|
|
limit = parse_limit(request.query_params.get("limit"))
|
|
cursor = request.query_params.get("cursor")
|
|
if cursor is not None and (not cursor or len(cursor) > 512):
|
|
invalid()
|
|
try:
|
|
items, next_cursor = await call_store(store.list_chats, user["id"], limit, cursor)
|
|
except ValueError:
|
|
invalid()
|
|
return json_ok(request, {"items": items, "next_cursor": next_cursor})
|
|
|
|
|
|
@app.get("/api/v1/chats/{chat_id}")
|
|
async def get_chat(request: Request, chat_id: str):
|
|
user = await current_user(request)
|
|
chat = await call_store(store.get_chat, parse_chat_id(chat_id), user["id"])
|
|
if chat is None:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
return json_ok(request, chat)
|
|
|
|
|
|
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
|
async def create_message(request: Request, chat_id: str):
|
|
user = await current_user(request)
|
|
canonical = parse_chat_id(chat_id)
|
|
payload = await read_json(request)
|
|
key = parse_idempotency_key(request)
|
|
try:
|
|
body = CreateMessage.model_validate(payload)
|
|
except ValidationError:
|
|
invalid()
|
|
message = await call_store(store.add_message, canonical, user["id"], body.text, key)
|
|
if message is None:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
return json_ok(request, message, 201)
|
|
|
|
|
|
@app.get("/api/v1/chats/{chat_id}/messages")
|
|
async def list_messages(request: Request, chat_id: str):
|
|
user = await current_user(request)
|
|
canonical = parse_chat_id(chat_id)
|
|
limit = parse_limit(request.query_params.get("limit"))
|
|
cursor = request.query_params.get("cursor")
|
|
if cursor is not None and (not cursor or len(cursor) > 512):
|
|
invalid()
|
|
try:
|
|
result = await call_store(store.list_messages, canonical, user["id"], limit, cursor)
|
|
except ValueError:
|
|
invalid()
|
|
if result is None:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
items, next_cursor = result
|
|
return json_ok(request, {"items": items, "next_cursor": next_cursor})
|
|
|
|
|
|
def setup_logging():
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
|
|
setup_logging()
|
|
host = os.environ.get("APP_HOST", "0.0.0.0")
|
|
port = int(os.environ.get("APP_PORT", "8080"))
|
|
uvicorn.run(
|
|
app,
|
|
host=host,
|
|
port=port,
|
|
timeout_graceful_shutdown=5,
|
|
timeout_keep_alive=2,
|
|
access_log=False,
|
|
)
|