refactor: connect FastAPI to PostgreSQL services
This commit is contained in:
+52
-109
@@ -1,41 +1,56 @@
|
||||
import logging
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException, Request
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from .models import Chat, CreateChat, CreateMessage, CreateUser, User
|
||||
from .store import InMemoryStore
|
||||
from app.api.auth import router as auth_router
|
||||
from app.api.users import router as users_router
|
||||
from app.core.config import settings
|
||||
from app.db.session import engine
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
store = InMemoryStore()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
logger.info("Application startup")
|
||||
yield
|
||||
engine.dispose()
|
||||
logger.info("Application shutdown")
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
app = FastAPI(
|
||||
title="Messenger API",
|
||||
version="1.2.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.include_router(users_router)
|
||||
app.include_router(auth_router)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_request_id(request: Request, call_next):
|
||||
request_id = str(uuid.uuid4())
|
||||
request.state.request_id = request_id
|
||||
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
logger.exception("Unhandled request error; request_id=%s", request_id)
|
||||
logger.exception(
|
||||
"Unhandled request error; request_id=%s",
|
||||
request_id,
|
||||
)
|
||||
response = JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
@@ -46,6 +61,7 @@ async def add_request_id(request: Request, call_next):
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
|
||||
@@ -53,6 +69,7 @@ async def add_request_id(request: Request, call_next):
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
request_id = request.state.request_id
|
||||
|
||||
error_code_map = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
@@ -64,22 +81,37 @@ async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
500: "internal_error",
|
||||
503: "unavailable",
|
||||
}
|
||||
|
||||
headers = dict(exc.headers or {})
|
||||
headers["X-Request-Id"] = request_id
|
||||
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"error": {
|
||||
"code": error_code_map.get(exc.status_code, "internal_error"),
|
||||
"message": exc.detail if isinstance(exc.detail, str) else "Request failed",
|
||||
"code": error_code_map.get(
|
||||
exc.status_code,
|
||||
"internal_error",
|
||||
),
|
||||
"message": (
|
||||
exc.detail
|
||||
if isinstance(exc.detail, str)
|
||||
else "Request failed"
|
||||
),
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers={"X-Request-Id": request_id},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
async def validation_exception_handler(
|
||||
request: Request,
|
||||
exc: RequestValidationError,
|
||||
):
|
||||
request_id = request.state.request_id
|
||||
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={
|
||||
@@ -93,24 +125,6 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
||||
)
|
||||
|
||||
|
||||
def get_current_user(x_user_id: Optional[str] = Header(default=None)) -> User:
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||
user = store.get_user(x_user_id)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||
return user
|
||||
|
||||
|
||||
def validate_chat_uuid(chat_id: str) -> None:
|
||||
try:
|
||||
parsed = uuid.UUID(chat_id)
|
||||
if str(parsed) != chat_id.lower():
|
||||
raise ValueError("non-canonical UUID")
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
raise HTTPException(status_code=400, detail="Invalid chat UUID") from None
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
def liveness():
|
||||
return {"status": "ok"}
|
||||
@@ -118,85 +132,14 @@ def liveness():
|
||||
|
||||
@app.get("/health/ready")
|
||||
def readiness():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
def register_user(body: CreateUser):
|
||||
try:
|
||||
return store.create_user(body.username, body.display_name)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "conflict":
|
||||
raise HTTPException(status_code=409, detail="Username already exists") from None
|
||||
raise HTTPException(status_code=400, detail="Invalid request") from None
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT 1"))
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
def current_user(user: User = Depends(get_current_user)):
|
||||
return user
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
def create_chat(body: CreateChat, user: User = Depends(get_current_user)):
|
||||
try:
|
||||
return store.create_chat(body.title, body.member_ids, user.id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid members or missing creator") from None
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
def list_chats(
|
||||
limit: int = 50,
|
||||
cursor: Optional[str] = None,
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="Limit out of range")
|
||||
try:
|
||||
items, next_cursor = store.list_chats(user.id, limit, cursor)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid cursor") from None
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
def get_chat(chat_id: str, user: User = Depends(get_current_user)):
|
||||
validate_chat_uuid(chat_id)
|
||||
chat = store.get_chat(chat_id, user.id)
|
||||
if chat is None:
|
||||
raise HTTPException(status_code=404, detail="Chat not found or access denied")
|
||||
return chat
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
def create_message(
|
||||
chat_id: str,
|
||||
body: CreateMessage,
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
validate_chat_uuid(chat_id)
|
||||
try:
|
||||
return store.create_message(chat_id, user.id, body.text)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "not_found":
|
||||
raise HTTPException(status_code=404, detail="Chat not found or access denied") from None
|
||||
raise HTTPException(status_code=400, detail="Invalid request") from None
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = 50,
|
||||
cursor: Optional[str] = None,
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
validate_chat_uuid(chat_id)
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="Limit out of range")
|
||||
try:
|
||||
items, next_cursor = store.list_messages(chat_id, user.id, limit, cursor)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
except ValueError as exc:
|
||||
if str(exc) == "not_found":
|
||||
raise HTTPException(status_code=404, detail="Chat not found or access denied") from None
|
||||
raise HTTPException(status_code=400, detail="Invalid cursor") from None
|
||||
except SQLAlchemyError:
|
||||
logger.exception("PostgreSQL readiness check failed")
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Database unavailable",
|
||||
) from None
|
||||
|
||||
Reference in New Issue
Block a user