forked from mtusi2026/mtusi2026lab2
156 lines
6.1 KiB
Python
156 lines
6.1 KiB
Python
from contextlib import asynccontextmanager
|
|
import logging
|
|
import re
|
|
from uuid import UUID, uuid4
|
|
|
|
from fastapi import FastAPI, Request, Response
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.concurrency import run_in_threadpool
|
|
from starlette.exceptions import HTTPException
|
|
|
|
from .errors import ApiError, invalid
|
|
from .models import CreateChat, CreateMessage, CreateUser
|
|
from .security import basic_credentials, bearer_token
|
|
from .storage import PostgresStore
|
|
|
|
|
|
logger = logging.getLogger("messenger")
|
|
SESSION_PATH = "/api/v1/auth/sessions"
|
|
|
|
|
|
def uuid_value(value):
|
|
try:
|
|
return UUID(value)
|
|
except ValueError:
|
|
raise invalid("Неверный UUID") from None
|
|
|
|
|
|
def page_args(request):
|
|
raw = request.query_params.get("limit", "50")
|
|
normalized = raw.lstrip("0") or "0"
|
|
if re.fullmatch(r"[0-9]+", raw) is None or len(normalized) > 3 or not 1 <= int(normalized) <= 100:
|
|
raise invalid("Limit должен быть от 1 до 100")
|
|
return int(normalized), request.query_params.get("cursor")
|
|
|
|
|
|
def create_app():
|
|
store = PostgresStore()
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app):
|
|
await run_in_threadpool(store.open)
|
|
try:
|
|
yield
|
|
finally:
|
|
await run_in_threadpool(store.close)
|
|
|
|
app = FastAPI(redirect_slashes=False, docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
|
|
app.state.store = store
|
|
|
|
def error_response(request, error):
|
|
request_id = request.state.request_id
|
|
headers = {}
|
|
if error.status == 401:
|
|
headers["WWW-Authenticate"] = (
|
|
'Basic realm="messenger", charset="UTF-8"' if request.url.path == SESSION_PATH
|
|
else 'Bearer realm="messenger"'
|
|
)
|
|
return JSONResponse(
|
|
status_code=error.status, headers=headers,
|
|
content={"error": {"code": error.code, "message": error.message, "request_id": request_id}},
|
|
)
|
|
|
|
@app.middleware("http")
|
|
async def request_context(request, call_next):
|
|
request.state.request_id = str(uuid4())
|
|
try:
|
|
path = request.url.path
|
|
registration = path == "/api/v1/users" and request.method == "POST"
|
|
login = path == SESSION_PATH and request.method == "POST"
|
|
if login:
|
|
request.state.credentials = basic_credentials(request.headers.get("Authorization"))
|
|
if await request.body():
|
|
raise invalid("Вход не принимает тело запроса")
|
|
elif path.startswith("/api/v1/") and not registration:
|
|
token = bearer_token(request.headers.get("Authorization"))
|
|
request.state.user_id = await run_in_threadpool(store.authenticate, token)
|
|
request.state.token = token
|
|
if request.method == "POST" and path.startswith("/api/v1/") and not login:
|
|
media_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
|
|
if media_type != "application/json":
|
|
raise ApiError(415, "unsupported_media_type", "Нужен application/json")
|
|
try:
|
|
(await request.body()).decode("utf-8")
|
|
except UnicodeDecodeError:
|
|
raise invalid("JSON должен быть в UTF-8") from None
|
|
response = await call_next(request)
|
|
except ApiError as error:
|
|
response = error_response(request, error)
|
|
except Exception as error:
|
|
logger.error("request failed: %s", type(error).__name__)
|
|
response = error_response(request, ApiError(500, "internal_error", "Внутренняя ошибка"))
|
|
response.headers["X-Request-Id"] = request.state.request_id
|
|
logger.info("%s %s %s request_id=%s", request.method, request.url.path, response.status_code, request.state.request_id)
|
|
return response
|
|
|
|
@app.exception_handler(ApiError)
|
|
async def api_error(request, error):
|
|
return error_response(request, error)
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_error(request, error):
|
|
return error_response(request, invalid("Неверные поля запроса"))
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_error(request, error):
|
|
code = "not_found" if error.status_code == 404 else "invalid_request"
|
|
return error_response(request, ApiError(error.status_code, code, "Неверный запрос"))
|
|
|
|
@app.get("/health/live")
|
|
def live():
|
|
return {"status": "ok"}
|
|
|
|
@app.get("/health/ready")
|
|
def ready():
|
|
return store.ready()
|
|
|
|
@app.post("/api/v1/users", status_code=201)
|
|
def create_user(body: CreateUser):
|
|
return store.create_user(body)
|
|
|
|
@app.post(SESSION_PATH, status_code=201)
|
|
def login(request: Request):
|
|
return store.create_session(*request.state.credentials)
|
|
|
|
@app.delete(SESSION_PATH + "/current", status_code=204)
|
|
def logout(request: Request):
|
|
store.logout(request.state.token)
|
|
return Response(status_code=204)
|
|
|
|
@app.get("/api/v1/users/me")
|
|
def me(request: Request):
|
|
return store.user(request.state.user_id)
|
|
|
|
@app.post("/api/v1/chats", status_code=201)
|
|
def create_chat(body: CreateChat, request: Request):
|
|
return store.create_chat(request.state.user_id, body)
|
|
|
|
@app.get("/api/v1/chats")
|
|
def list_chats(request: Request):
|
|
return store.list_chats(request.state.user_id, *page_args(request))
|
|
|
|
@app.get("/api/v1/chats/{chat_id}")
|
|
def chat(chat_id: str, request: Request):
|
|
return store.chat(request.state.user_id, uuid_value(chat_id))
|
|
|
|
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
|
def create_message(chat_id: str, body: CreateMessage, request: Request):
|
|
return store.create_message(request.state.user_id, uuid_value(chat_id), body)
|
|
|
|
@app.get("/api/v1/chats/{chat_id}/messages")
|
|
def messages(chat_id: str, request: Request):
|
|
return store.list_messages(request.state.user_id, uuid_value(chat_id), *page_args(request))
|
|
|
|
return app
|