from datetime import datetime, timedelta, timezone from uuid import UUID, uuid4 import socket from fastapi import Depends, FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from fastapi.security import ( HTTPAuthorizationCredentials, HTTPBasic, HTTPBasicCredentials, HTTPBearer, ) from sqlalchemy.exc import IntegrityError, SQLAlchemyError from sqlalchemy.ext.asyncio import AsyncSession from starlette.exceptions import HTTPException as StarletteHTTPException from src.database import get_db_session, ping_database from src.errors import APIError from src.models import CreateUser, SessionResponse, User, CreateChat, Chat, ChatPage, CreateMessage, Message, MessagePage from src.repositories import ( create_chat, list_chats, create_user as create_user_in_db, get_user_by_id, get_chat_by_id, get_user_credentials_by_username, create_message, get_messages, ) from src.security import verify_password from src.sessions import ( create_session, delete_session, get_session_user_id, ping_session_store, ) app = FastAPI() basic_security = HTTPBasic(auto_error=False) bearer_security = HTTPBearer(auto_error=False) async def get_current_user( credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security), session: AsyncSession = Depends(get_db_session), ) -> User: if credentials is None or credentials.scheme.lower() != "bearer": raise APIError( status_code=401, code="unauthorized", message="Unauthorized", headers={ "WWW-Authenticate": "Bearer", }, ) user_id = await get_session_user_id(credentials.credentials) if user_id is None: raise APIError( status_code=401, code="unauthorized", message="Unauthorized", headers={ "WWW-Authenticate": "Bearer", }, ) user = await get_user_by_id(session, user_id) if user is None: raise APIError( status_code=401, code="unauthorized", message="Unauthorized", headers={ "WWW-Authenticate": "Bearer", }, ) return user @app.middleware("http") async def request_middleware(request: Request, call_next): request_id = str(uuid4()) request.state.request_id = request_id if request.method in {"POST", "PUT", "PATCH"}: content_type = request.headers.get("content-type") if content_type is not None: media_type = content_type.split(";", 1)[0].strip().lower() if media_type != "application/json": return JSONResponse( status_code=415, content={ "error": { "code": "unsupported_media_type", "message": "Unsupported media type", "request_id": request_id, } }, headers={ "X-Request-Id": request_id, }, ) response = await call_next(request) response.headers["X-Request-Id"] = request_id return response @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": "Invalid request", "request_id": request_id, } }, ) @app.exception_handler(APIError) async def api_error_handler(request: Request, exc: APIError): request_id = request.state.request_id return JSONResponse( status_code=exc.status_code, content={ "error": { "code": exc.code, "message": exc.message, "request_id": request_id, } }, headers=exc.headers, ) @app.exception_handler(SQLAlchemyError) async def database_exception_handler( request: Request, exc: SQLAlchemyError, ): request_id = request.state.request_id return JSONResponse( status_code=503, content={ "error": { "code": "service_unavailable", "message": "Database unavailable", "request_id": request_id, } }, ) @app.exception_handler(OSError) async def database_connection_exception_handler( request: Request, exc: OSError, ): request_id = request.state.request_id return JSONResponse( status_code=503, content={ "error": { "code": "service_unavailable", "message": "Database unavailable", "request_id": request_id, } }, ) @app.exception_handler(StarletteHTTPException) async def http_exception_handler( request: Request, exc: StarletteHTTPException, ): request_id = request.state.request_id if exc.status_code == 404: code = "not_found" message = "Not found" else: code = "invalid_request" message = "Invalid request" return JSONResponse( status_code=exc.status_code, content={ "error": { "code": code, "message": message, "request_id": request_id, } }, headers=exc.headers, ) @app.exception_handler(Exception) async def unexpected_exception_handler( request: Request, exc: Exception, ): request_id = request.state.request_id return JSONResponse( status_code=500, content={ "error": { "code": "internal_error", "message": "Internal server error", "request_id": request_id, } }, ) @app.get("/health/live") async def health_live(): return {"status": "ok"} @app.get("/health/ready") async def health_ready(): database_ready = await ping_database() session_store_ready = await ping_session_store() if not database_ready or not session_store_ready: raise APIError( status_code=503, code="service_unavailable", message="Service dependencies unavailable", ) return {"status": "ok"} @app.post("/api/v1/users", response_model=User, status_code=201) async def create_user( data: CreateUser, session: AsyncSession = Depends(get_db_session), ): try: async with session.begin(): return await create_user_in_db(session, data) except IntegrityError as exc: raise APIError( status_code=409, code="conflict", message="Username already exists", ) from exc @app.get("/api/v1/users/me", response_model=User) async def get_me( current_user: User = Depends(get_current_user), ): return current_user @app.post( "/api/v1/auth/sessions", response_model=SessionResponse, status_code=201, ) async def create_auth_session( credentials: HTTPBasicCredentials | None = Depends(basic_security), session: AsyncSession = Depends(get_db_session), ): if credentials is None: raise APIError( status_code=401, code="unauthorized", message="Unauthorized", headers={ "WWW-Authenticate": 'Basic realm="messenger"', }, ) user_credentials = await get_user_credentials_by_username( session, credentials.username, ) if user_credentials is None: raise APIError( status_code=401, code="unauthorized", message="Unauthorized", headers={ "WWW-Authenticate": 'Basic realm="messenger"', }, ) if not verify_password( user_credentials.password_hash, credentials.password, ): raise APIError( status_code=401, code="unauthorized", message="Unauthorized", headers={ "WWW-Authenticate": 'Basic realm="messenger"', }, ) user = User( id=user_credentials.id, username=user_credentials.username, display_name=user_credentials.display_name, created_at=user_credentials.created_at, ) token, ttl = await create_session(user.id) expires_at = datetime.now(timezone.utc) + timedelta(seconds=ttl) return SessionResponse( token=token, token_type="Bearer", expires_at=expires_at, user=user, ) @app.delete( "/api/v1/auth/sessions/current", status_code=204, ) async def delete_current_session( credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security), current_user: User = Depends(get_current_user), ): await delete_session(credentials.credentials) @app.post( "/api/v1/chats", response_model=Chat, status_code=201, ) async def create_chat_endpoint( data: CreateChat, current_user: User = Depends(get_current_user), session: AsyncSession = Depends(get_db_session), ) -> Chat: try: chat = await create_chat( session=session, data=data, current_user_id=current_user.id, ) await session.commit() except Exception: await session.rollback() raise return chat @app.get( "/api/v1/chats", response_model=ChatPage, ) async def get_chats( limit: int = 50, current_user: User = Depends(get_current_user), session: AsyncSession = Depends(get_db_session), ) -> ChatPage: if limit < 1 or limit > 100: raise APIError( status_code=400, code="invalid_request", message="Limit must be between 1 and 100", ) return await list_chats( session=session, current_user_id=current_user.id, limit=limit, ) @app.get( "/api/v1/chats/{chat_id}", response_model=Chat, ) async def get_chat_endpoint( chat_id: UUID, current_user: User = Depends(get_current_user), session: AsyncSession = Depends(get_db_session), ) -> Chat: chat = await get_chat_by_id( session=session, chat_id=chat_id, current_user_id=current_user.id, ) if chat is None: raise APIError( status_code=404, code="not_found", message="Chat not found", ) return chat @app.post( "/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201, ) async def create_message_endpoint( chat_id: UUID, data: CreateMessage, current_user: User = Depends(get_current_user), session: AsyncSession = Depends(get_db_session), ) -> Message: try: message = await create_message( session=session, chat_id=chat_id, current_user_id=current_user.id, data=data, ) await session.commit() except Exception: await session.rollback() raise return message @app.get( "/api/v1/chats/{chat_id}/messages", response_model=MessagePage, ) async def get_messages_endpoint( chat_id: UUID, limit: int = 50, cursor: str | None = None, current_user: User = Depends(get_current_user), session: AsyncSession = Depends(get_db_session), ) -> MessagePage: if limit < 1 or limit > 100: raise APIError( status_code=400, code="invalid_request", message="Limit must be between 1 and 100", ) return await get_messages( session=session, chat_id=chat_id, current_user_id=current_user.id, limit=limit, cursor=cursor, )