diff --git a/main/live-agent-api/orm/binding/model.py b/main/live-agent-api/orm/binding/model.py index 40d4d9a4e..c6bd0e922 100644 --- a/main/live-agent-api/orm/binding/model.py +++ b/main/live-agent-api/orm/binding/model.py @@ -52,8 +52,8 @@ class DeviceAgentBinding(Base): status: Mapped[str] = mapped_column( String(20), nullable=False, - default="active", - comment="Binding status (active, inactive)" + default="bound", + comment="Binding status (bound, unbound)" ) # Timestamps @@ -72,8 +72,6 @@ class DeviceAgentBinding(Base): comment="Last update timestamp" ) - def __repr__(self) -> str: - return f"" def to_dict(self) -> dict: """ diff --git a/main/live-agent-api/orm/binding/repository.py b/main/live-agent-api/orm/binding/repository.py index d52fb0dad..d6955de52 100644 --- a/main/live-agent-api/orm/binding/repository.py +++ b/main/live-agent-api/orm/binding/repository.py @@ -66,6 +66,28 @@ class DeviceAgentBindingRepository: result = await self.db.execute(stmt) return list(result.scalars().all()) + async def find_by_device_and_agent( + self, + device_id: str, + agent_id: str + ) -> Optional[DeviceAgentBinding]: + """ + Find binding by device ID and agent ID + + Args: + device_id: Device unique ID + agent_id: Agent unique ID + + Returns: + DeviceAgentBinding instance or None if not found + """ + stmt = select(DeviceAgentBinding).where( + DeviceAgentBinding.device_id == device_id, + DeviceAgentBinding.agent_id == agent_id + ) + result = await self.db.execute(stmt) + return result.scalar_one_or_none() + async def find_all( self, device_id: Optional[str] = None, diff --git a/main/live-agent-api/router/binding.py b/main/live-agent-api/router/binding.py index 5e46a689f..6bdd4d534 100644 --- a/main/live-agent-api/router/binding.py +++ b/main/live-agent-api/router/binding.py @@ -5,175 +5,99 @@ API endpoints for Device-Agent binding management. """ import logging -from typing import Annotated -from fastapi import APIRouter, Depends, Query +from fastapi import APIRouter, Depends from sqlalchemy.ext.asyncio import AsyncSession from orm import get_db -from services.binding_service import BindingService, get_binding_service -from schemas.binding import ( - BindingCreate, - BindingUpdate, - BindingResponse, - BindingListQuery, -) -from utils.response import ( - ApiResponse, - success_response, - error_response, - paginated_response, -) +from services.binding_service import get_binding_service +from schemas.binding import BindingOperation, BindingResponse +from utils.response import ApiResponse, success_response, error_response logger = logging.getLogger(__name__) -router = APIRouter(prefix="/binding", tags=["binding"]) - - -@router.get("/") -async def get_binding_list( - deviceId: Annotated[str | None, Query(alias="deviceId", description="Filter by device ID")] = None, - agentId: Annotated[str | None, Query(alias="agentId", description="Filter by agent ID")] = None, - status: Annotated[str | None, Query(description="Filter by status")] = None, - page: Annotated[int, Query(ge=1, description="Page number")] = 1, - pageSize: Annotated[int, Query(ge=1, le=100, alias="pageSize", description="Items per page")] = 10, - sortBy: Annotated[str, Query(alias="sortBy", description="Sort field")] = "createdAt", - sortOrder: Annotated[str, Query(alias="sortOrder", pattern="^(asc|desc)$", description="Sort order")] = "desc", - db: AsyncSession = Depends(get_db), -) -> ApiResponse: - """ - Get DeviceAgentBinding list with filtering, pagination and sorting - - - **deviceId**: Filter by device ID - - **agentId**: Filter by agent ID - - **status**: Filter by status (active, inactive) - - **page**: Page number (starting from 1) - - **pageSize**: Number of items per page (1-100) - - **sortBy**: Field to sort by (default: createdAt) - - **sortOrder**: Sort order - asc or desc (default: desc) - - Returns paginated list of bindings with total count. - """ - try: - # Create query object - query = BindingListQuery( - device_id=deviceId, - agent_id=agentId, - status=status, - page=page, - page_size=pageSize, - sort_by=sortBy, - sort_order=sortOrder, - ) - - # Get service - service = get_binding_service(db) - - # Get bindings - bindings, total = await service.get_binding_list(query) - - # Convert to response format - binding_responses = [ - BindingResponse.model_validate(binding) for binding in bindings - ] - - # Create paginated response - pagination_data = paginated_response( - items=binding_responses, - total=total, - page=page, - page_size=pageSize, - ) - - return success_response(data=pagination_data) - - except Exception as e: - logger.error(f"Error getting binding list: {str(e)}") - return error_response( - message=f"Failed to get binding list: {str(e)}", - code=500 - ) - - -@router.get("/{binding_id}") -async def get_binding_detail( - binding_id: str, - db: AsyncSession = Depends(get_db), -) -> ApiResponse: - """ - Get DeviceAgentBinding details by ID - - - **binding_id**: Binding unique ID - - Returns detailed binding information. - """ - try: - service = get_binding_service(db) - binding = await service.get_binding_by_id(binding_id) - - if not binding: - return error_response( - message=f"Binding not found: {binding_id}", - code=404 - ) - - binding_response = BindingResponse.model_validate(binding) - return success_response(data=binding_response) - - except Exception as e: - logger.error(f"Error getting binding detail: {str(e)}") - return error_response( - message=f"Failed to get binding detail: {str(e)}", - code=500 - ) +router = APIRouter(prefix="/bindings", tags=["bindings"]) @router.get("/device/{device_id}") -async def get_binding_by_device( +async def get_bindings_by_device( device_id: str, db: AsyncSession = Depends(get_db), ) -> ApiResponse: """ - Get DeviceAgentBinding by device ID + Get device-agent binding information by device ID - **device_id**: Device unique ID - Returns binding information for the device. + Returns the binding relationship for the specified device, or null if not bound. """ try: service = get_binding_service(db) binding = await service.get_binding_by_device_id(device_id) if not binding: - return error_response( - message=f"No binding found for device: {device_id}", - code=404 + # No binding is not an error - return success with null data + return success_response( + data=None ) binding_response = BindingResponse.model_validate(binding) return success_response(data=binding_response) except Exception as e: - logger.error(f"Error getting binding by device: {str(e)}") + logger.error(f"Error getting device binding: {str(e)}") return error_response( - message=f"Failed to get binding by device: {str(e)}", + message=f"Failed to get device binding: {str(e)}", code=500 ) -@router.post("/") -async def create_binding( - binding_data: BindingCreate, +@router.get("/agent/{agent_id}") +async def get_bindings_by_agent( + agent_id: str, db: AsyncSession = Depends(get_db), ) -> ApiResponse: """ - Create a new DeviceAgentBinding + Get all device bindings for an agent + + - **agent_id**: Agent unique ID + + Returns all devices bound to the specified agent (empty list if none). + """ + try: + service = get_binding_service(db) + bindings = await service.get_bindings_by_agent_id(agent_id) + + binding_responses = [ + BindingResponse.model_validate(binding) for binding in bindings + ] + + return success_response( + data=binding_responses, + message=f"Found {len(bindings)} device(s) bound to agent" + ) + + except Exception as e: + logger.error(f"Error getting agent device bindings: {str(e)}") + return error_response( + message=f"Failed to get agent device bindings: {str(e)}", + code=500 + ) + + +@router.post("/bind") +async def create_device_agent_binding( + binding_data: BindingOperation, + db: AsyncSession = Depends(get_db), +) -> ApiResponse: + """ + Create a device-agent binding (bind device to agent) Request body: - **deviceId**: Device unique ID (required) - **agentId**: Agent unique ID (required) - Returns the created binding with generated ID. + Creates a binding relationship between the specified device and agent. Note: Each device can only be bound to one agent at a time. """ @@ -184,12 +108,10 @@ async def create_binding( binding_response = BindingResponse.model_validate(binding) return success_response( data=binding_response, - message="Binding created successfully", - code=201 + message="Device bound to agent successfully", ) except ValueError as e: - # Business logic errors (e.g., device not found, already bound) logger.warning(f"Validation error creating binding: {str(e)}") return error_response( message=str(e), @@ -203,116 +125,39 @@ async def create_binding( ) -@router.put("/{binding_id}") -async def update_binding( - binding_id: str, - binding_data: BindingUpdate, - db: AsyncSession = Depends(get_db), -) -> ApiResponse: - """ - Update DeviceAgentBinding configuration - - - **binding_id**: Binding unique ID - - Request body (all fields optional): - - **agentId**: Agent unique ID (to change the bound agent) - - **status**: Binding status (active, inactive) - - Returns the updated binding information. - """ - try: - service = get_binding_service(db) - binding = await service.update_binding(binding_id, binding_data) - - if not binding: - return error_response( - message=f"Binding not found: {binding_id}", - code=404 - ) - - binding_response = BindingResponse.model_validate(binding) - return success_response( - data=binding_response, - message="Binding updated successfully" - ) - - except ValueError as e: - # Business logic errors (e.g., agent not found) - logger.warning(f"Validation error updating binding: {str(e)}") - return error_response( - message=str(e), - code=400 - ) - except Exception as e: - logger.error(f"Error updating binding: {str(e)}") - return error_response( - message=f"Failed to update binding: {str(e)}", - code=500 - ) - - -@router.delete("/{binding_id}") -async def delete_binding( - binding_id: str, - db: AsyncSession = Depends(get_db), -) -> ApiResponse: - """ - Delete a DeviceAgentBinding - - - **binding_id**: Binding unique ID - - Deletes the binding relationship between device and agent. - Returns success message if deleted. - """ - try: - service = get_binding_service(db) - deleted = await service.delete_binding(binding_id) - - if not deleted: - return error_response( - message=f"Binding not found: {binding_id}", - code=404 - ) - - return success_response( - data={"id": binding_id}, - message="Binding deleted successfully" - ) - - except Exception as e: - logger.error(f"Error deleting binding: {str(e)}") - return error_response( - message=f"Failed to delete binding: {str(e)}", - code=500 - ) - - -@router.delete("/device/{device_id}") +@router.post("/unbind") async def unbind_device( - device_id: str, + binding_data: BindingOperation, db: AsyncSession = Depends(get_db), ) -> ApiResponse: """ - Remove binding for a device + Unbind device from agent - - **device_id**: Device unique ID + Request body: + - **deviceId**: Device unique ID (required) + - **agentId**: Agent unique ID (required) - Unbinds the device from its agent. - Returns success message if unbound. + Updates the binding status to unbound for the specified device-agent pair. """ try: service = get_binding_service(db) - unbound = await service.unbind_device(device_id) + unbound = await service.unbind_device( + binding_data.device_id, + binding_data.agent_id + ) if not unbound: return error_response( - message=f"No binding found for device: {device_id}", + message=f"No active binding found for device {binding_data.device_id} and agent {binding_data.agent_id}", code=404 ) return success_response( - data={"deviceId": device_id}, - message="Device unbound successfully" + data={ + "deviceId": binding_data.device_id, + "agentId": binding_data.agent_id + }, + message="Device unbound from agent successfully" ) except Exception as e: diff --git a/main/live-agent-api/schemas/__init__.py b/main/live-agent-api/schemas/__init__.py index 67112443d..0574773d6 100644 --- a/main/live-agent-api/schemas/__init__.py +++ b/main/live-agent-api/schemas/__init__.py @@ -27,7 +27,7 @@ from schemas.device import ( # Binding schemas from schemas.binding import ( - BindingCreate, + BindingOperation, BindingUpdate, BindingResponse, BindingWithDetails, @@ -53,7 +53,7 @@ __all__ = [ "DeviceListQuery", # Binding schemas - "BindingCreate", + "BindingOperation", "BindingUpdate", "BindingResponse", "BindingWithDetails", diff --git a/main/live-agent-api/schemas/binding.py b/main/live-agent-api/schemas/binding.py index 8a577eba7..b1987ca3e 100644 --- a/main/live-agent-api/schemas/binding.py +++ b/main/live-agent-api/schemas/binding.py @@ -9,8 +9,12 @@ from typing import Optional from pydantic import BaseModel, Field -class BindingCreate(BaseModel): - """Schema for creating a new DeviceAgentBinding""" +class BindingOperation(BaseModel): + """ + Schema for device-agent binding operations (bind/unbind) + + This schema represents the device-agent pair for all binding operations. + """ device_id: str = Field( ..., @@ -51,7 +55,7 @@ class BindingUpdate(BaseModel): status: Optional[str] = Field( None, max_length=20, - description="Binding status (active, inactive)" + description="Binding status (bound, unbound)" ) model_config = { @@ -59,7 +63,7 @@ class BindingUpdate(BaseModel): "json_schema_extra": { "example": { "agentId": "0987654321", - "status": "active" + "status": "bound" } } } @@ -91,7 +95,7 @@ class BindingResponse(BaseModel): "id": "1122334455", "deviceId": "1234567890", "agentId": "0987654321", - "status": "active", + "status": "bound", "createdAt": "2024-01-01T00:00:00", "updatedAt": "2024-01-01T00:00:00" } @@ -113,7 +117,7 @@ class BindingWithDetails(BindingResponse): "id": "1122334455", "deviceId": "1234567890", "agentId": "0987654321", - "status": "active", + "status": "bound", "deviceName": "My PLAUD Device", "agentName": "My Assistant", "createdAt": "2024-01-01T00:00:00", diff --git a/main/live-agent-api/services/binding_service.py b/main/live-agent-api/services/binding_service.py index 0ff59eb41..1adc4246e 100644 --- a/main/live-agent-api/services/binding_service.py +++ b/main/live-agent-api/services/binding_service.py @@ -13,7 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from orm.binding import DeviceAgentBinding, DeviceAgentBindingRepository from orm.device import DeviceRepository from orm.agent import AgentRepository -from schemas.binding import BindingCreate, BindingUpdate, BindingListQuery +from schemas.binding import BindingOperation, BindingUpdate, BindingListQuery from utils import id_generator @@ -117,49 +117,67 @@ class BindingService: return bindings - async def create_binding(self, binding_data: BindingCreate) -> DeviceAgentBinding: + async def create_binding(self, binding_data: BindingOperation) -> DeviceAgentBinding: """ - Create a new device-agent binding + Create or reactivate a device-agent binding Args: binding_data: Binding creation data Returns: - Created binding instance + Created or updated binding instance Raises: - ValueError: If device or agent not found, or device already has binding + ValueError: If device or agent not found, or device already bound to this agent """ - # Business logic: Validate device exists + # 1. Validate device exists device = await self.device_repo.find_by_id(binding_data.device_id) if not device: raise ValueError(f"Device not found: {binding_data.device_id}") - # Business logic: Validate agent exists + # 2. Validate agent exists agent = await self.agent_repo.find_by_id(binding_data.agent_id) if not agent: raise ValueError(f"Agent not found: {binding_data.agent_id}") - # Business logic: Check if device already has a binding - if await self.repo.device_has_binding(binding_data.device_id): - raise ValueError(f"Device already has a binding: {binding_data.device_id}") - - # Business logic: Generate unique ID - binding_id = id_generator.generate() - - # Business logic: Create binding instance - binding = DeviceAgentBinding( - id=binding_id, - device_id=binding_data.device_id, - agent_id=binding_data.agent_id, + # 3. Check if binding already exists for this device-agent pair + existing_binding = await self.repo.find_by_device_and_agent( + binding_data.device_id, + binding_data.agent_id ) - # Persist to database - binding = await self.repo.save(binding) - - logger.info(f"Created binding: {binding_id} (device={binding_data.device_id}, agent={binding_data.agent_id})") - - return binding + if existing_binding: + # Binding record exists + if existing_binding.status == "bound": + # Already bound - return error + raise ValueError( + f"Device {binding_data.device_id} is already bound to agent {binding_data.agent_id}" + ) + else: + # Status is "unbound" - reactivate the binding + existing_binding.status = "bound" + existing_binding.updated_at = datetime.now(timezone.utc) + binding = await self.repo.save(existing_binding) + logger.info( + f"Reactivated binding: {existing_binding.id} " + f"(device={binding_data.device_id}, agent={binding_data.agent_id})" + ) + return binding + else: + # No existing binding - create new one + binding_id = id_generator.generate() + binding = DeviceAgentBinding( + id=binding_id, + device_id=binding_data.device_id, + agent_id=binding_data.agent_id, + status="bound", + ) + binding = await self.repo.save(binding) + logger.info( + f"Created new binding: {binding_id} " + f"(device={binding_data.device_id}, agent={binding_data.agent_id})" + ) + return binding async def update_binding( self, @@ -225,23 +243,34 @@ class BindingService: return True - async def unbind_device(self, device_id: str) -> bool: + async def unbind_device(self, device_id: str, agent_id: str) -> bool: """ - Remove binding for a device + Unbind a device from an agent (update status to unbound) Args: device_id: Device unique ID + agent_id: Agent unique ID Returns: - True if unbound, False if no binding found + True if unbound successfully, False if no active binding found """ - binding = await self.repo.find_by_device_id(device_id) + # Find the specific device-agent binding + binding = await self.repo.find_by_device_and_agent(device_id, agent_id) if not binding: + logger.warning(f"No binding found for device {device_id} and agent {agent_id}") return False - await self.repo.delete(binding) + # Check if already unbound + if binding.status == "unbound": + logger.info(f"Device {device_id} is already unbound from agent {agent_id}") + return False - logger.info(f"Unbound device: {device_id}") + # Update status to unbound instead of deleting + binding.status = "unbound" + binding.updated_at = datetime.now(timezone.utc) + await self.repo.save(binding) + + logger.info(f"Unbound device {device_id} from agent {agent_id}") return True