forked from mtusi2026/mtusi2026lab4
Реализовала требования лабы 4 на оценку 4
This commit is contained in:
+14
-24
@@ -12,7 +12,7 @@ from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import psycopg
|
||||
import uvicorn
|
||||
from .api import auth, chats, health, messages, users
|
||||
from .api import attachments, auth, chats, health, messages, users
|
||||
from .storage.db import init_pool, close_pool
|
||||
|
||||
|
||||
@@ -31,8 +31,7 @@ INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12]
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_pool() # пул соединений PostgreSQL с таймаутами (уровень 4)
|
||||
# Схему готовит отдельный сервис migrate (service_completed_successfully)
|
||||
init_pool() # пул соединений PostgreSQL с таймаутами
|
||||
logger.info(
|
||||
"event=startup app_env=%s session_store=%s instance_id=%s",
|
||||
os.environ.get("APP_ENV", "lab"),
|
||||
@@ -45,8 +44,8 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUCI Messenger — lab3",
|
||||
version="1.3.0",
|
||||
title="MTUCI Messenger — lab4",
|
||||
version="1.4.0",
|
||||
lifespan=lifespan,
|
||||
swagger_ui_parameters={"persistAuthorization": True},
|
||||
)
|
||||
@@ -76,12 +75,8 @@ async def observability_middleware(request: Request, call_next):
|
||||
path = request.url.path
|
||||
logger.info(
|
||||
"event=http method=%s path=%s status=%s duration_ms=%s request_id=%s instance_id=%s",
|
||||
request.method,
|
||||
path,
|
||||
response.status_code,
|
||||
duration_ms,
|
||||
request_id,
|
||||
INSTANCE_ID,
|
||||
request.method, path, response.status_code,
|
||||
duration_ms, request_id, INSTANCE_ID,
|
||||
)
|
||||
return response
|
||||
|
||||
@@ -143,34 +138,28 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
||||
async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError):
|
||||
"""PostgreSQL недоступен → 503 unavailable, без внутренних деталей."""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.error(
|
||||
"event=db_unavailable type=%s request_id=%s",
|
||||
type(exc).__name__,
|
||||
request_id,
|
||||
)
|
||||
logger.error("event=db_unavailable type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(RuntimeError)
|
||||
async def runtime_error_handler(request: Request, exc: RuntimeError):
|
||||
"""Redis недоступен или конфигурация битая."""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
text = str(exc)
|
||||
if "redis_unavailable" in text:
|
||||
logger.error("event=redis_unavailable request_id=%s", request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
logger.error(
|
||||
"event=runtime_error type=%s request_id=%s",
|
||||
type(exc).__name__,
|
||||
request_id,
|
||||
)
|
||||
logger.error("event=runtime_error type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.error("event=unhandled_exception type=%s request_id=%s", type(exc).__name__, request_id)
|
||||
logger.error("event=unhandled_exception type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id, request.url.path)
|
||||
|
||||
|
||||
@@ -179,6 +168,7 @@ app.include_router(auth.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
app.include_router(attachments.router)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -186,7 +176,7 @@ if __name__ == "__main__":
|
||||
"app.main:app",
|
||||
host="0.0.0.0",
|
||||
port=8080,
|
||||
log_level="info",
|
||||
log_level="info"
|
||||
)
|
||||
server = uvicorn.Server(config)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user