forked from mtusi2026/mtusi2026lab2
123 lines
4.1 KiB
Python
123 lines
4.1 KiB
Python
"""Точка входа: FastAPI-приложение, middleware и обработка ошибок."""
|
|
import logging
|
|
import os
|
|
import uuid
|
|
|
|
import redis
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
from .db import apply_migrations, make_pool
|
|
from .errors import ApiError, error_body
|
|
from .handlers import router
|
|
from .sessions import SessionStore
|
|
from .store import Store
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
|
)
|
|
logger = logging.getLogger("messenger")
|
|
|
|
app = FastAPI(title="MTUSI Messenger", version="1.2.0")
|
|
|
|
_pool = make_pool()
|
|
apply_migrations(_pool)
|
|
|
|
_cache: redis.Redis | None = None
|
|
_cache_url = os.environ.get("CACHE_URL")
|
|
if _cache_url:
|
|
_cache = redis.Redis.from_url(
|
|
_cache_url,
|
|
socket_timeout=float(os.environ.get("REDIS_SOCKET_TIMEOUT", "1")),
|
|
socket_connect_timeout=float(os.environ.get("REDIS_SOCKET_TIMEOUT", "1")),
|
|
decode_responses=False,
|
|
)
|
|
|
|
app.state.pool = _pool
|
|
app.state.store = Store(_pool)
|
|
app.state.sessions = SessionStore(_pool, _cache)
|
|
app.include_router(router)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def request_id_middleware(request: Request, call_next):
|
|
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
|
request.state.request_id = request_id
|
|
try:
|
|
response = await call_next(request)
|
|
except ApiError as exc:
|
|
response = JSONResponse(
|
|
error_body(exc.code, exc.message, request_id),
|
|
status_code=exc.status,
|
|
)
|
|
response.headers["X-Request-Id"] = request_id
|
|
return response
|
|
|
|
|
|
@app.exception_handler(ApiError)
|
|
async def api_error_handler(request: Request, exc: ApiError) -> JSONResponse:
|
|
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
|
headers = {"X-Request-Id": request_id}
|
|
challenge = getattr(exc, "challenge", None)
|
|
if challenge:
|
|
headers["WWW-Authenticate"] = challenge
|
|
return JSONResponse(
|
|
error_body(exc.code, exc.message, request_id),
|
|
status_code=exc.status,
|
|
headers=headers,
|
|
)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_error_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
|
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
|
return JSONResponse(
|
|
error_body("invalid_request", "Некорректный запрос", request_id),
|
|
status_code=400,
|
|
headers={"X-Request-Id": request_id},
|
|
)
|
|
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def http_error_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
|
|
"""Ошибки разбора тела (невалидный JSON/байты) FastAPI отдаёт как HTTPException 400."""
|
|
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
|
if exc.status_code == 400:
|
|
return JSONResponse(
|
|
error_body("invalid_request", "Некорректный запрос", request_id),
|
|
status_code=400,
|
|
headers={"X-Request-Id": request_id},
|
|
)
|
|
return JSONResponse(
|
|
error_body("not_found" if exc.status_code == 404 else "internal_error",
|
|
str(exc.detail), request_id),
|
|
status_code=exc.status_code,
|
|
headers={"X-Request-Id": request_id},
|
|
)
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
async def unhandled_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
|
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
|
logger.exception("unhandled error request_id=%s", request_id)
|
|
return JSONResponse(
|
|
error_body("internal_error", "Внутренняя ошибка", request_id),
|
|
status_code=500,
|
|
headers={"X-Request-Id": request_id},
|
|
)
|
|
|
|
|
|
def main() -> None:
|
|
import uvicorn
|
|
|
|
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, log_level="info")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|