forked from mtusi2026/mtusi2026lab3
191 lines
6.4 KiB
Python
191 lines
6.4 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()
|
|
import logging
|
|
import signal
|
|
import sys
|
|
import uuid
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
from .config import settings
|
|
from .errors import ApiError, error_response
|
|
from .routers import auth, chats, health, messages, users
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
|
log = logging.getLogger("app")
|
|
|
|
app = FastAPI(title="Messenger", version="1.3.0", docs_url=None, redoc_url=None, openapi_url=None)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def add_headers(request: Request, call_next):
|
|
rid = request.headers.get("x-request-id") or uuid.uuid4().hex
|
|
request.state.request_id = rid
|
|
try:
|
|
response = await call_next(request)
|
|
except ApiError as exc:
|
|
response = error_response(request, exc.status, exc.code, exc.message)
|
|
response.headers["X-Request-Id"] = rid
|
|
response.headers["X-Instance-Id"] = settings.instance_id
|
|
return response
|
|
|
|
|
|
@app.exception_handler(ApiError)
|
|
async def api_error_handler(request: Request, exc: ApiError):
|
|
return error_response(request, exc.status, exc.code, exc.message)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_handler(request: Request, exc: RequestValidationError):
|
|
return error_response(request, 400, "invalid_request", "Некорректный запрос")
|
|
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def http_handler(request: Request, exc: StarletteHTTPException):
|
|
code = {401: "unauthorized", 404: "not_found", 405: "invalid_request"}.get(exc.status_code, "invalid_request")
|
|
return error_response(request, exc.status_code, code, str(exc.detail) or "Ошибка")
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
async def unhandled(request: Request, exc: Exception):
|
|
log.exception("unhandled error")
|
|
return error_response(request, 500, "internal_error", "Внутренняя ошибка")
|
|
|
|
|
|
app.include_router(health.router)
|
|
app.include_router(users.router)
|
|
app.include_router(auth.router)
|
|
app.include_router(chats.router)
|
|
app.include_router(messages.router)
|
|
|
|
|
|
def _shutdown(signum, frame):
|
|
log.info("received signal %s, shutting down", signum)
|
|
sys.exit(0)
|
|
|
|
|
|
signal.signal(signal.SIGTERM, _shutdown)
|