refactor: connect FastAPI to PostgreSQL services
This commit is contained in:
+52
-109
@@ -1,41 +1,56 @@
|
|||||||
import logging
|
import logging
|
||||||
import uuid
|
import uuid
|
||||||
from contextlib import asynccontextmanager
|
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.exceptions import RequestValidationError
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
|
from sqlalchemy import text
|
||||||
|
from sqlalchemy.exc import SQLAlchemyError
|
||||||
|
|
||||||
from .models import Chat, CreateChat, CreateMessage, CreateUser, User
|
from app.api.auth import router as auth_router
|
||||||
from .store import InMemoryStore
|
from app.api.users import router as users_router
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.db.session import engine
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
level=logging.INFO,
|
level=logging.INFO,
|
||||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
store = InMemoryStore()
|
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
logger.info("Application startup")
|
logger.info("Application startup")
|
||||||
yield
|
yield
|
||||||
|
engine.dispose()
|
||||||
logger.info("Application shutdown")
|
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")
|
@app.middleware("http")
|
||||||
async def add_request_id(request: Request, call_next):
|
async def add_request_id(request: Request, call_next):
|
||||||
request_id = str(uuid.uuid4())
|
request_id = str(uuid.uuid4())
|
||||||
request.state.request_id = request_id
|
request.state.request_id = request_id
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = await call_next(request)
|
response = await call_next(request)
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception("Unhandled request error; request_id=%s", request_id)
|
logger.exception(
|
||||||
|
"Unhandled request error; request_id=%s",
|
||||||
|
request_id,
|
||||||
|
)
|
||||||
response = JSONResponse(
|
response = JSONResponse(
|
||||||
status_code=500,
|
status_code=500,
|
||||||
content={
|
content={
|
||||||
@@ -46,6 +61,7 @@ async def add_request_id(request: Request, call_next):
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
response.headers["X-Request-Id"] = request_id
|
response.headers["X-Request-Id"] = request_id
|
||||||
return response
|
return response
|
||||||
|
|
||||||
@@ -53,6 +69,7 @@ async def add_request_id(request: Request, call_next):
|
|||||||
@app.exception_handler(HTTPException)
|
@app.exception_handler(HTTPException)
|
||||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||||
request_id = request.state.request_id
|
request_id = request.state.request_id
|
||||||
|
|
||||||
error_code_map = {
|
error_code_map = {
|
||||||
400: "invalid_request",
|
400: "invalid_request",
|
||||||
401: "unauthorized",
|
401: "unauthorized",
|
||||||
@@ -64,22 +81,37 @@ async def http_exception_handler(request: Request, exc: HTTPException):
|
|||||||
500: "internal_error",
|
500: "internal_error",
|
||||||
503: "unavailable",
|
503: "unavailable",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
headers = dict(exc.headers or {})
|
||||||
|
headers["X-Request-Id"] = request_id
|
||||||
|
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
status_code=exc.status_code,
|
status_code=exc.status_code,
|
||||||
content={
|
content={
|
||||||
"error": {
|
"error": {
|
||||||
"code": error_code_map.get(exc.status_code, "internal_error"),
|
"code": error_code_map.get(
|
||||||
"message": exc.detail if isinstance(exc.detail, str) else "Request failed",
|
exc.status_code,
|
||||||
|
"internal_error",
|
||||||
|
),
|
||||||
|
"message": (
|
||||||
|
exc.detail
|
||||||
|
if isinstance(exc.detail, str)
|
||||||
|
else "Request failed"
|
||||||
|
),
|
||||||
"request_id": request_id,
|
"request_id": request_id,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
headers={"X-Request-Id": request_id},
|
headers=headers,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(RequestValidationError)
|
@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
|
request_id = request.state.request_id
|
||||||
|
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
status_code=400,
|
status_code=400,
|
||||||
content={
|
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")
|
@app.get("/health/live")
|
||||||
def liveness():
|
def liveness():
|
||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
@@ -118,85 +132,14 @@ def liveness():
|
|||||||
|
|
||||||
@app.get("/health/ready")
|
@app.get("/health/ready")
|
||||||
def readiness():
|
def readiness():
|
||||||
return {"status": "ok"}
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/v1/users", status_code=201)
|
|
||||||
def register_user(body: CreateUser):
|
|
||||||
try:
|
try:
|
||||||
return store.create_user(body.username, body.display_name)
|
with engine.connect() as connection:
|
||||||
except ValueError as exc:
|
connection.execute(text("SELECT 1"))
|
||||||
if str(exc) == "conflict":
|
return {"status": "ok"}
|
||||||
raise HTTPException(status_code=409, detail="Username already exists") from None
|
|
||||||
raise HTTPException(status_code=400, detail="Invalid request") from None
|
|
||||||
|
|
||||||
|
except SQLAlchemyError:
|
||||||
@app.get("/api/v1/users/me")
|
logger.exception("PostgreSQL readiness check failed")
|
||||||
def current_user(user: User = Depends(get_current_user)):
|
raise HTTPException(
|
||||||
return user
|
status_code=503,
|
||||||
|
detail="Database unavailable",
|
||||||
|
) from None
|
||||||
@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
|
|
||||||
|
|||||||
Reference in New Issue
Block a user