|
| 1 | +"""Handler for REST API call to provide info.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from typing import Any |
| 5 | +from pathlib import Path |
| 6 | +import json |
| 7 | +from datetime import datetime, UTC |
| 8 | + |
| 9 | +from fastapi import APIRouter, Request, HTTPException, Depends, status |
| 10 | + |
| 11 | +from configuration import configuration |
| 12 | +from models.responses import FeedbackResponse, StatusResponse |
| 13 | +from models.requests import FeedbackRequest |
| 14 | +from utils.suid import get_suid |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | +router = APIRouter(prefix="/feedback", tags=["feedback"]) |
| 18 | + |
| 19 | +# Response for the feedback endpoint |
| 20 | +feedback_response: dict[int | str, dict[str, Any]] = { |
| 21 | + 200: {"response": "Feedback received and stored"}, |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +def is_feedback_enabled() -> bool: |
| 26 | + """Check if feedback is enabled. |
| 27 | +
|
| 28 | + Returns: |
| 29 | + bool: True if feedback is enabled, False otherwise. |
| 30 | + """ |
| 31 | + return not configuration.user_data_collection_configuration.feedback_disabled |
| 32 | + |
| 33 | + |
| 34 | +# TODO(lucasagomes): implement this function to retrieve user ID from auth |
| 35 | +def retrieve_user_id(auth: Any) -> str: # pylint: disable=unused-argument |
| 36 | + """Retrieve the user ID from the authentication handler. |
| 37 | +
|
| 38 | + Args: |
| 39 | + auth: The Authentication handler (FastAPI Depends) that will |
| 40 | + handle authentication Logic. |
| 41 | +
|
| 42 | + Returns: |
| 43 | + str: The user ID. |
| 44 | + """ |
| 45 | + return "user_id_placeholder" |
| 46 | + |
| 47 | + |
| 48 | +# TODO(lucasagomes): implement this function to handle authentication |
| 49 | +async def auth_dependency(_request: Request) -> bool: |
| 50 | + """Authenticate dependency to ensure the user is authenticated. |
| 51 | +
|
| 52 | + Args: |
| 53 | + request (Request): The FastAPI request object. |
| 54 | +
|
| 55 | + Raises: |
| 56 | + HTTPException: If the user is not authenticated. |
| 57 | + """ |
| 58 | + return True |
| 59 | + |
| 60 | + |
| 61 | +async def assert_feedback_enabled(_request: Request) -> None: |
| 62 | + """Check if feedback is enabled. |
| 63 | +
|
| 64 | + Args: |
| 65 | + request (Request): The FastAPI request object. |
| 66 | +
|
| 67 | + Raises: |
| 68 | + HTTPException: If feedback is disabled. |
| 69 | + """ |
| 70 | + feedback_enabled = is_feedback_enabled() |
| 71 | + if not feedback_enabled: |
| 72 | + raise HTTPException( |
| 73 | + status_code=status.HTTP_403_FORBIDDEN, |
| 74 | + detail="Forbidden: Feedback is disabled", |
| 75 | + ) |
| 76 | + |
| 77 | + |
| 78 | +@router.post("", responses=feedback_response) |
| 79 | +def feedback_endpoint_handler( |
| 80 | + _request: Request, |
| 81 | + feedback_request: FeedbackRequest, |
| 82 | + _ensure_feedback_enabled: Any = Depends(assert_feedback_enabled), |
| 83 | + auth: Any = Depends(auth_dependency), |
| 84 | +) -> FeedbackResponse: |
| 85 | + """Handle feedback requests. |
| 86 | +
|
| 87 | + Args: |
| 88 | + feedback_request: The request containing feedback information. |
| 89 | + ensure_feedback_enabled: The feedback handler (FastAPI Depends) that |
| 90 | + will handle feedback status checks. |
| 91 | + auth: The Authentication handler (FastAPI Depends) that will |
| 92 | + handle authentication Logic. |
| 93 | +
|
| 94 | + Returns: |
| 95 | + Response indicating the status of the feedback storage request. |
| 96 | + """ |
| 97 | + logger.debug("Feedback received %s", str(feedback_request)) |
| 98 | + |
| 99 | + user_id = retrieve_user_id(auth) |
| 100 | + try: |
| 101 | + store_feedback(user_id, feedback_request.model_dump(exclude={"model_config"})) |
| 102 | + except Exception as e: |
| 103 | + logger.error("Error storing user feedback: %s", e) |
| 104 | + raise HTTPException( |
| 105 | + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, |
| 106 | + detail={ |
| 107 | + "response": "Error storing user feedback", |
| 108 | + "cause": str(e), |
| 109 | + }, |
| 110 | + ) from e |
| 111 | + |
| 112 | + return FeedbackResponse(response="feedback received") |
| 113 | + |
| 114 | + |
| 115 | +def store_feedback(user_id: str, feedback: dict) -> None: |
| 116 | + """Store feedback in the local filesystem. |
| 117 | +
|
| 118 | + Args: |
| 119 | + user_id: The user ID (UUID). |
| 120 | + feedback: The feedback to store. |
| 121 | + """ |
| 122 | + logger.debug("Storing feedback for user %s", user_id) |
| 123 | + # Creates storage path only if it doesn't exist. The `exist_ok=True` prevents |
| 124 | + # race conditions in case of multiple server instances trying to set up storage |
| 125 | + # at the same location. |
| 126 | + storage_path = Path( |
| 127 | + configuration.user_data_collection_configuration.feedback_storage or "" |
| 128 | + ) |
| 129 | + storage_path.mkdir(parents=True, exist_ok=True) |
| 130 | + |
| 131 | + current_time = str(datetime.now(UTC)) |
| 132 | + data_to_store = {"user_id": user_id, "timestamp": current_time, **feedback} |
| 133 | + |
| 134 | + # stores feedback in a file under unique uuid |
| 135 | + feedback_file_path = storage_path / f"{get_suid()}.json" |
| 136 | + with open(feedback_file_path, "w", encoding="utf-8") as feedback_file: |
| 137 | + json.dump(data_to_store, feedback_file) |
| 138 | + |
| 139 | + logger.info("Feedback stored sucessfully at %s", feedback_file_path) |
| 140 | + |
| 141 | + |
| 142 | +@router.get("/status") |
| 143 | +def feedback_status() -> StatusResponse: |
| 144 | + """Handle feedback status requests. |
| 145 | +
|
| 146 | + Returns: |
| 147 | + Response indicating the status of the feedback. |
| 148 | + """ |
| 149 | + logger.debug("Feedback status requested") |
| 150 | + feedback_status_enabled = is_feedback_enabled() |
| 151 | + return StatusResponse( |
| 152 | + functionality="feedback", status={"enabled": feedback_status_enabled} |
| 153 | + ) |
0 commit comments