diff --git a/main/live-agent-api/api/v1/chat.py b/main/live-agent-api/api/v1/chat.py index 93e30d14e..3a6db8c2a 100644 --- a/main/live-agent-api/api/v1/chat.py +++ b/main/live-agent-api/api/v1/chat.py @@ -7,11 +7,15 @@ from typing import Optional from infra import get_db, get_s3 from services.chat_service import chat_service +from services.agent_service import agent_service from schemas.chat import ( ReportChatMessageRequest, - ChatMessagesListResponse + ChatMessagesListResponse, ) -from utils.response import success_response +from api.auth import get_current_user_id +from utils.response import success_response, error_response +from utils.exceptions import ForbiddenException, NotFoundException, InternalServerException + router = APIRouter() @@ -104,3 +108,46 @@ async def get_agent_messages( has_more=has_more )) + +@router.delete("/{agent_id}", summary="Delete all chat data for an agent") +async def clear_agent_chat( + agent_id: str, + db: AsyncSession = Depends(get_db), + s3 = Depends(get_s3), + user_id: str = Depends(get_current_user_id) +): + """ + Clear all chat data for an agent + + Deletes: + - All chat messages in database + - All audio files in S3 (chat-audio/{agent_id}/) + - All chat files in S3 (chat-files/{agent_id}/) + + Requirements: + - User must be authenticated + - User must own the agent + + Returns: + ClearChatResponse with deletion counts + """ + # Verify agent exists and user owns it + try: + await agent_service.verify_ownership(db=db, agent_id=agent_id, owner_id=user_id) + except ForbiddenException as e: + return error_response(code=403, message=e.message) + except NotFoundException as e: + return error_response(code=404, message=e.message) + + # Clear chat data + try: + result = await chat_service.clear_agent_chat( + db=db, + s3=s3, + agent_id=agent_id + ) + except InternalServerException as e: + return error_response(code=500, message=e.message) + + return success_response(data=result) + diff --git a/main/live-agent-api/repositories/chat.py b/main/live-agent-api/repositories/chat.py index d4714a6a6..1e0c41c01 100644 --- a/main/live-agent-api/repositories/chat.py +++ b/main/live-agent-api/repositories/chat.py @@ -3,7 +3,7 @@ Chat messages repository - Database operations for chat messages """ from datetime import datetime, timezone from typing import List, Optional, Tuple -from sqlalchemy import String, SmallInteger, TIMESTAMP, ForeignKey, Index, select, insert +from sqlalchemy import String, SmallInteger, TIMESTAMP, ForeignKey, Index, select, delete from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.dialects.postgresql import JSONB @@ -185,3 +185,24 @@ class ChatMessage: result = await db.execute(query) return result.scalar_one_or_none() + @staticmethod + async def delete_by_agent( + db: AsyncSession, + agent_id: str + ) -> int: + """ + Delete all messages for a specific agent + + Args: + db: Database session + agent_id: Agent ID + + Returns: + Number of deleted messages + """ + result = await db.execute( + delete(ChatMessageModel).where(ChatMessageModel.agent_id == agent_id) + ) + await db.commit() + return result.rowcount + diff --git a/main/live-agent-api/repositories/file.py b/main/live-agent-api/repositories/file.py index ff6312ee3..540af600e 100644 --- a/main/live-agent-api/repositories/file.py +++ b/main/live-agent-api/repositories/file.py @@ -7,6 +7,10 @@ from fastapi import UploadFile from config import settings from utils.ulid import ULID +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() class FileRepository: @@ -184,3 +188,71 @@ class FileRepository: url = f"{settings.S3_PUBLIC_BASE_URL}/{settings.S3_BUCKET_NAME}/{s3_key}" return url + @staticmethod + async def delete_folder(s3, folder_prefix: str) -> int: + """ + Delete all files under a folder prefix in S3 + + Args: + s3: S3 client + folder_prefix: S3 folder prefix (e.g., "chat-audio/agent_123/") + + Returns: + Number of deleted objects + """ + deleted_count = 0 + try: + # List all objects with the prefix + paginator = s3.get_paginator('list_objects_v2') + async for page in paginator.paginate( + Bucket=settings.S3_BUCKET_NAME, + Prefix=folder_prefix + ): + if 'Contents' not in page: + continue + + # Delete objects in batch + objects_to_delete = [{'Key': obj['Key']} for obj in page['Contents']] + if objects_to_delete: + chunk_size = 1000 + for i in range(0, len(objects_to_delete), chunk_size): + batch = objects_to_delete[i:i + chunk_size] + + response = await s3.delete_objects( + Bucket=settings.S3_BUCKET_NAME, + Delete={'Objects': batch, 'Quiet': True} + ) + + if 'Errors' in response: + for err in response['Errors']: + logger.bind(tag=TAG).error(f"Failed to delete {err.get('Key')}: {err.get('Message')}") + + deleted_count += len(response.get('Deleted', [])) + except Exception as e: + logger.bind(tag=TAG).error(f"Error deleting folder {folder_prefix}: {e}") + pass + + return deleted_count + + @staticmethod + async def delete_agent_chat_files(s3, agent_id: str) -> int: + """ + Delete all chat-related files for an agent (audio and files) + + Args: + s3: S3 client + agent_id: Agent ID + + Returns: + Total number of deleted files + """ + total_deleted = 0 + + # Delete chat audio files + total_deleted += await FileRepository.delete_folder(s3, f"chat-audio/{agent_id}/") + + # Delete chat files (if any other files stored under agent) + total_deleted += await FileRepository.delete_folder(s3, f"chat-files/{agent_id}/") + + return total_deleted + diff --git a/main/live-agent-api/schemas/chat.py b/main/live-agent-api/schemas/chat.py index 8d64702f2..d3644d0c8 100644 --- a/main/live-agent-api/schemas/chat.py +++ b/main/live-agent-api/schemas/chat.py @@ -44,3 +44,10 @@ class ChatMessagesListResponse(BaseModel): next_cursor: Optional[str] = Field(None, description="ISO timestamp to load older messages (pass as cursor for next request)") has_more: bool = Field(False, description="Whether there are more older messages available") + +class ClearChatResponse(BaseModel): + """Response schema for clearing agent chat data""" + agent_id: str = Field(..., description="Agent ID whose chat was cleared") + deleted_messages: int = Field(..., description="Number of deleted messages") + deleted_files: int = Field(..., description="Number of deleted files from storage") + diff --git a/main/live-agent-api/services/agent_service.py b/main/live-agent-api/services/agent_service.py index 48515519d..65298db3d 100644 --- a/main/live-agent-api/services/agent_service.py +++ b/main/live-agent-api/services/agent_service.py @@ -3,7 +3,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from fastapi import UploadFile from repositories import AgentModel, Agent, AgentTemplate, FileRepository -from utils.exceptions import NotFoundException, BadRequestException +from utils.exceptions import NotFoundException, ForbiddenException from utils.ulid import generate_agent_id from schemas.agent import ( AgentResponse, @@ -13,6 +13,8 @@ from schemas.agent import ( AgentWithLatestMessage ) from utils.ulid import generate_template_id + + class AgentService: """Agent service layer""" @@ -117,6 +119,36 @@ class AgentService: raise NotFoundException("Agent not found") return agent + + async def verify_ownership( + self, + db: AsyncSession, + agent_id: str, + owner_id: str + ) -> AgentModel: + """ + Verify agent exists and belongs to user + + Args: + db: Database session + agent_id: Agent ID + owner_id: Expected owner user ID + + Returns: + AgentModel if verification passes + + Raises: + NotFoundException: If agent not found + ForbiddenException: If user doesn't own the agent + """ + agent = await Agent.get_by_id(db, agent_id) + if not agent: + raise NotFoundException("Agent not found") + + if agent.owner_id != owner_id: + raise ForbiddenException("You don't have permission to access this agent") + + return agent async def get_bindable_agents( self, @@ -198,7 +230,7 @@ class AgentService: # Check ownership if agent.owner_id != owner_id: - raise BadRequestException("You don't have permission to update this agent") + raise ForbiddenException("You don't have permission to update this agent") # Prepare update data update_data = {} @@ -246,7 +278,7 @@ class AgentService: # Check ownership if agent.owner_id != owner_id: - raise BadRequestException("You don't have permission to delete this agent") + raise ForbiddenException("You don't have permission to delete this agent") # Delete avatar from S3 if exists if agent.avatar_url: diff --git a/main/live-agent-api/services/chat_service.py b/main/live-agent-api/services/chat_service.py index 4af474135..f81a5af40 100644 --- a/main/live-agent-api/services/chat_service.py +++ b/main/live-agent-api/services/chat_service.py @@ -7,10 +7,15 @@ from typing import List, Optional, Tuple from sqlalchemy.ext.asyncio import AsyncSession from copy import deepcopy +from config.logger import setup_logging from repositories.chat import ChatMessage as ChatMessageRepo from repositories.file import FileRepository -from schemas.chat import ReportChatMessageRequest, ChatMessage as ChatMessageSchema +from schemas.chat import ReportChatMessageRequest, ChatMessage as ChatMessageSchema, ClearChatResponse from utils.ulid import ULID +from utils.exceptions import InternalServerException + +TAG = __name__ +logger = setup_logging(__name__) class ChatService: @@ -137,6 +142,52 @@ class ChatService: return response_messages, next_cursor, has_more + async def clear_agent_chat( + self, + db: AsyncSession, + s3, + agent_id: str + ) -> ClearChatResponse: + """ + Clear all chat data for an agent (messages and files) + + Note: Caller must verify agent ownership before calling this method + + Process: + 1. Delete all chat messages from database + 2. Delete all chat files from S3 + + Args: + db: Database session + s3: S3 client + agent_id: Agent ID + + Returns: + ClearChatResponse with deletion counts + + Raises: + InternalServerException: If database or S3 deletion fails + """ + # Delete all messages from database + try: + deleted_messages = await ChatMessageRepo.delete_by_agent(db, agent_id) + except Exception as e: + logger.bind(tag=TAG).exception(f"Failed to delete chat messages for agent {agent_id}") + raise InternalServerException(f"Failed to delete chat messages: {e}") + + # Delete all chat files from S3 + try: + deleted_files = await FileRepository.delete_agent_chat_files(s3, agent_id) + except Exception as e: + logger.bind(tag=TAG).exception(f"Failed to delete chat files for agent {agent_id}") + raise InternalServerException(f"Failed to delete chat files: {e}") + + return ClearChatResponse( + agent_id=agent_id, + deleted_messages=deleted_messages, + deleted_files=deleted_files + ) + # Global singleton instance chat_service = ChatService() diff --git a/main/live-agent-api/utils/exceptions.py b/main/live-agent-api/utils/exceptions.py index 859f78494..70a3a56c4 100644 --- a/main/live-agent-api/utils/exceptions.py +++ b/main/live-agent-api/utils/exceptions.py @@ -35,3 +35,9 @@ class ConflictException(APIException): def __init__(self, message: str = "Resource already exists"): super().__init__(409, message) + +class InternalServerException(APIException): + """Internal server exception (500)""" + def __init__(self, message: str = "Internal server error"): + super().__init__(500, message) +