forked from mtusi2026/mtusi2026lab2
64 lines
1.9 KiB
Python
64 lines
1.9 KiB
Python
from contextlib import asynccontextmanager
|
|
from uuid import uuid4
|
|
from fastapi import FastAPI, Request, HTTPException
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from psycopg import OperationalError
|
|
from app.routers import users,chats,messages
|
|
from app.storage import db,migrate
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app):
|
|
migrate()
|
|
yield
|
|
|
|
app=FastAPI(lifespan=lifespan)
|
|
|
|
|
|
def error_code(status):
|
|
return {400:'invalid_request',401:'unauthorized',404:'not_found',409:'conflict',503:'unavailable'}.get(status,'internal_error')
|
|
|
|
|
|
def error_response(request,status,message,headers=None):
|
|
result=JSONResponse(status_code=status,content={'error':{
|
|
'code':error_code(status),'message':message,'request_id':request.state.request_id}},headers=headers)
|
|
result.headers['X-Request-Id']=request.state.request_id
|
|
return result
|
|
|
|
|
|
@app.middleware('http')
|
|
async def add_request_id(request:Request,call_next):
|
|
request.state.request_id=str(uuid4())
|
|
try:
|
|
response=await call_next(request)
|
|
except OperationalError:
|
|
response=error_response(request,503,'Database unavailable')
|
|
except Exception:
|
|
response=error_response(request,500,'Internal server error')
|
|
response.headers['X-Request-Id']=request.state.request_id
|
|
return response
|
|
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_error(request,exc):
|
|
return error_response(request,exc.status_code,str(exc.detail),exc.headers)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_error(request,exc):
|
|
return error_response(request,400,'Invalid request')
|
|
|
|
app.include_router(users.router)
|
|
app.include_router(chats.router)
|
|
app.include_router(messages.router)
|
|
|
|
@app.get('/health/live')
|
|
def live():
|
|
return {'status':'ok'}
|
|
|
|
@app.get('/health/ready')
|
|
def ready():
|
|
with db() as conn:
|
|
conn.execute('SELECT 1')
|
|
return {'status':'ok'}
|