202 lines
6.2 KiB
Python
202 lines
6.2 KiB
Python
import logging
|
|
import uuid
|
|
from contextlib import asynccontextmanager
|
|
from typing import Optional
|
|
|
|
from fastapi import Depends, FastAPI, Header, HTTPException, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from .models import Chat, CreateChat, CreateMessage, CreateUser, User
|
|
from .store import InMemoryStore
|
|
|
|
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
|
|
logger.info("Application shutdown")
|
|
|
|
|
|
app = FastAPI(lifespan=lifespan)
|
|
|
|
|
|
@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)
|
|
response = JSONResponse(
|
|
status_code=500,
|
|
content={
|
|
"error": {
|
|
"code": "internal_error",
|
|
"message": "Unexpected error",
|
|
"request_id": request_id,
|
|
}
|
|
},
|
|
)
|
|
response.headers["X-Request-Id"] = request_id
|
|
return response
|
|
|
|
|
|
@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",
|
|
404: "not_found",
|
|
409: "conflict",
|
|
413: "payload_too_large",
|
|
415: "unsupported_media_type",
|
|
429: "rate_limited",
|
|
500: "internal_error",
|
|
503: "unavailable",
|
|
}
|
|
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",
|
|
"request_id": request_id,
|
|
}
|
|
},
|
|
headers={"X-Request-Id": request_id},
|
|
)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
|
request_id = request.state.request_id
|
|
return JSONResponse(
|
|
status_code=400,
|
|
content={
|
|
"error": {
|
|
"code": "invalid_request",
|
|
"message": "Validation error",
|
|
"request_id": request_id,
|
|
}
|
|
},
|
|
headers={"X-Request-Id": request_id},
|
|
)
|
|
|
|
|
|
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"}
|
|
|
|
|
|
@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
|
|
|
|
|
|
@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 |