feat: 绑定device和agent

This commit is contained in:
leo 2025-12-03 19:12:16 +08:00
parent 26c46c654d
commit e713e63dab
8 changed files with 769 additions and 1 deletions

View file

@ -1,5 +1,5 @@
from fastapi import APIRouter
from api.v1 import user, templates, agents, voices, internal, files, chat
from api.v1 import user, templates, agents, voices, internal, files, chat, devices
api_router = APIRouter()
@ -52,3 +52,10 @@ api_router.include_router(
tags=["Chat"]
)
# Device routes
api_router.include_router(
devices.router,
prefix="/devices",
tags=["Devices"]
)

View file

@ -0,0 +1,126 @@
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from infra import get_db
from services.device_service import device_service
from utils.response import success_response
from api.auth import get_current_user_id
from schemas.device import (
DeviceBindRequest,
DeviceAddAgentRequest,
DeviceSetDefaultAgentRequest
)
router = APIRouter()
@router.post("/bind", summary="Bind device")
async def bind_device(
request: DeviceBindRequest,
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
Bind a device to user with an agent.
- If device (SN) doesn't exist, creates it
- If device exists but unbound, binds to current user
- First agent bound becomes default
"""
device = await device_service.bind_device(
db=db,
owner_id=current_user_id,
sn=request.sn,
agent_id=request.agent_id
)
return success_response(data=device.model_dump())
@router.delete("/{device_id}", summary="Unbind device")
async def unbind_device(
device_id: str,
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
Unbind a device.
- Clears owner_id (device record preserved)
- Removes all agent bindings
"""
await device_service.unbind_device(
db=db,
owner_id=current_user_id,
device_id=device_id
)
return success_response(data={}, message="Device unbound successfully")
@router.get("", summary="Get user's devices")
async def get_devices(
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""Get all devices owned by current user with their agent bindings"""
devices = await device_service.get_user_devices(
db=db,
owner_id=current_user_id
)
return success_response(data=devices.model_dump())
@router.post("/{device_id}/agents", summary="Add agent to device")
async def add_agent_to_device(
device_id: str,
request: DeviceAddAgentRequest,
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""Add an agent binding to device"""
device = await device_service.add_agent_to_device(
db=db,
owner_id=current_user_id,
device_id=device_id,
agent_id=request.agent_id,
is_default=request.is_default
)
return success_response(data=device.model_dump())
@router.delete("/{device_id}/agents/{agent_id}", summary="Remove agent from device")
async def remove_agent_from_device(
device_id: str,
agent_id: str,
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
Remove an agent binding from device.
If removed agent was default, another binding will be set as default.
"""
device = await device_service.remove_agent_from_device(
db=db,
owner_id=current_user_id,
device_id=device_id,
agent_id=agent_id
)
return success_response(data=device.model_dump())
@router.put("/{device_id}/default-agent", summary="Set default agent")
async def set_default_agent(
device_id: str,
request: DeviceSetDefaultAgentRequest,
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""Set an agent as default for device"""
device = await device_service.set_default_agent(
db=db,
owner_id=current_user_id,
device_id=device_id,
agent_id=request.agent_id
)
return success_response(data=device.model_dump())

View file

@ -144,6 +144,53 @@ COMMENT ON COLUMN chat_messages.role IS 'Message role: 1=user, 2=agent';
COMMENT ON COLUMN chat_messages.content IS 'JSONB array: [{"message_type": "text|audio|image|file", "message_content": "text or S3 URL"}]';
COMMENT ON COLUMN chat_messages.created_at IS 'Message creation timestamp (UTC)';
-- ==================== Table: devices ====================
-- Device registry table
CREATE TABLE IF NOT EXISTS devices (
id SERIAL PRIMARY KEY,
device_id VARCHAR(50) UNIQUE NOT NULL,
sn VARCHAR(100) UNIQUE NOT NULL,
owner_id VARCHAR(50),
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
CONSTRAINT fk_devices_owner FOREIGN KEY (owner_id)
REFERENCES "user"(user_id) ON DELETE SET NULL
);
-- Indexes for devices table
CREATE UNIQUE INDEX IF NOT EXISTS idx_devices_device_id ON devices(device_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_devices_sn ON devices(sn);
CREATE INDEX IF NOT EXISTS idx_devices_owner_id ON devices(owner_id);
-- Comments for devices table
COMMENT ON TABLE devices IS 'Device registry for hardware devices';
COMMENT ON COLUMN devices.device_id IS 'External unique identifier (ULID)';
COMMENT ON COLUMN devices.sn IS 'Hardware serial number (globally unique)';
COMMENT ON COLUMN devices.owner_id IS 'User ID of device owner (null if unbound)';
-- ==================== Table: agent_device_bindings ====================
-- Agent-Device binding relationship table
CREATE TABLE IF NOT EXISTS agent_device_bindings (
id SERIAL PRIMARY KEY,
device_id VARCHAR(50) NOT NULL,
agent_id VARCHAR(50) NOT NULL,
is_default BOOLEAN DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
CONSTRAINT fk_bindings_device FOREIGN KEY (device_id)
REFERENCES devices(device_id) ON DELETE CASCADE,
CONSTRAINT fk_bindings_agent FOREIGN KEY (agent_id)
REFERENCES agents(agent_id) ON DELETE CASCADE,
CONSTRAINT uk_device_agent UNIQUE (device_id, agent_id)
);
-- Indexes for agent_device_bindings table
CREATE INDEX IF NOT EXISTS idx_bindings_device_id ON agent_device_bindings(device_id);
CREATE INDEX IF NOT EXISTS idx_bindings_agent_id ON agent_device_bindings(agent_id);
-- Comments for agent_device_bindings table
COMMENT ON TABLE agent_device_bindings IS 'Many-to-many relationship between devices and agents';
COMMENT ON COLUMN agent_device_bindings.is_default IS 'Whether this agent is the default for the device';
-- ==================== Functions ====================
-- Function to automatically update updated_at timestamp
CREATE OR REPLACE FUNCTION update_updated_at_column()
@ -178,6 +225,12 @@ CREATE TRIGGER update_agent_templates_updated_at
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
-- Create triggers for updated_at on devices table
CREATE TRIGGER update_devices_updated_at
BEFORE UPDATE ON devices
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
-- ==================== Grant Permissions ====================
-- Grant necessary permissions to postgres user
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO postgres;

View file

@ -8,6 +8,7 @@ from .agent import AgentModel
from .agent_template import AgentTemplateModel
from .voice import VoiceModel
from .chat import ChatMessageModel
from .device import DeviceModel, AgentDeviceBindingModel
# Import Repository classes
from .user import User
@ -16,6 +17,7 @@ from .agent_template import AgentTemplate
from .voice import Voice
from .chat import ChatMessage
from .file import FileRepository
from .device import Device, AgentDeviceBinding
__all__ = [
# ORM Models
@ -24,6 +26,8 @@ __all__ = [
"AgentTemplateModel",
"VoiceModel",
"ChatMessageModel",
"DeviceModel",
"AgentDeviceBindingModel",
# Repository classes
"User",
"Agent",
@ -31,5 +35,7 @@ __all__ = [
"Voice",
"ChatMessage",
"FileRepository",
"Device",
"AgentDeviceBinding",
]

View file

@ -0,0 +1,295 @@
from datetime import datetime
from typing import Optional, List
from sqlalchemy import String, Boolean, TIMESTAMP, ForeignKey, Index, select, delete, update
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.ext.asyncio import AsyncSession
from infra.database import Base, utc_now
# ==================== ORM Models ====================
class DeviceModel(Base):
__tablename__ = "devices"
# Primary key
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
# Device unique identifier (external)
device_id: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)
# Hardware serial number (globally unique)
sn: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
# Owner user ID (null if unbound)
owner_id: Mapped[str | None] = mapped_column(
String(50),
ForeignKey("user.user_id", ondelete="SET NULL"),
nullable=True
)
# Timestamps
created_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
onupdate=utc_now,
nullable=False
)
__table_args__ = (
Index('idx_devices_device_id', 'device_id', unique=True),
Index('idx_devices_sn', 'sn', unique=True),
Index('idx_devices_owner_id', 'owner_id'),
)
def __repr__(self):
return f"<DeviceModel(id={self.id}, device_id={self.device_id}, sn={self.sn})>"
class AgentDeviceBindingModel(Base):
__tablename__ = "agent_device_bindings"
# Primary key
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
# Foreign keys
device_id: Mapped[str] = mapped_column(
String(50),
ForeignKey("devices.device_id", ondelete="CASCADE"),
nullable=False
)
agent_id: Mapped[str] = mapped_column(
String(50),
ForeignKey("agents.agent_id", ondelete="CASCADE"),
nullable=False
)
# Whether this is the default agent for the device
is_default: Mapped[bool] = mapped_column(Boolean, default=False)
# Timestamp
created_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
nullable=False
)
__table_args__ = (
Index('idx_bindings_device_id', 'device_id'),
Index('idx_bindings_agent_id', 'agent_id'),
Index('uk_device_agent', 'device_id', 'agent_id', unique=True),
)
def __repr__(self):
return f"<AgentDeviceBindingModel(device_id={self.device_id}, agent_id={self.agent_id})>"
# ==================== Repository (CRUD Operations) ====================
class Device:
"""Device Repository - Handles all device database operations"""
@staticmethod
async def get_by_id(db: AsyncSession, device_id: str) -> Optional[DeviceModel]:
"""Get device by device_id"""
result = await db.execute(select(DeviceModel).where(DeviceModel.device_id == device_id))
return result.scalar_one_or_none()
@staticmethod
async def get_by_sn(db: AsyncSession, sn: str) -> Optional[DeviceModel]:
"""Get device by SN"""
result = await db.execute(select(DeviceModel).where(DeviceModel.sn == sn))
return result.scalar_one_or_none()
@staticmethod
async def get_by_owner(db: AsyncSession, owner_id: str) -> List[DeviceModel]:
"""Get all devices owned by a user"""
result = await db.execute(
select(DeviceModel)
.where(DeviceModel.owner_id == owner_id)
.order_by(DeviceModel.created_at.desc())
)
return list(result.scalars().all())
@staticmethod
async def create(
db: AsyncSession,
device_id: str,
sn: str,
owner_id: Optional[str] = None
) -> DeviceModel:
"""Create a new device"""
device = DeviceModel(
device_id=device_id,
sn=sn,
owner_id=owner_id
)
db.add(device)
await db.commit()
await db.refresh(device)
return device
@staticmethod
async def update_owner(
db: AsyncSession,
device_id: str,
owner_id: Optional[str]
) -> Optional[DeviceModel]:
"""Update device owner"""
device = await Device.get_by_id(db, device_id)
if not device:
return None
device.owner_id = owner_id
await db.commit()
await db.refresh(device)
return device
@staticmethod
async def unbind(db: AsyncSession, device_id: str) -> bool:
"""Unbind device: clear owner_id and delete all agent bindings"""
# Clear owner_id
result = await db.execute(
update(DeviceModel)
.where(DeviceModel.device_id == device_id)
.values(owner_id=None)
)
# Delete all agent bindings
await db.execute(
delete(AgentDeviceBindingModel)
.where(AgentDeviceBindingModel.device_id == device_id)
)
await db.commit()
return result.rowcount > 0
class AgentDeviceBinding:
"""Agent-Device Binding Repository"""
@staticmethod
async def get_bindings_by_device(
db: AsyncSession,
device_id: str
) -> List[AgentDeviceBindingModel]:
"""Get all agent bindings for a device"""
result = await db.execute(
select(AgentDeviceBindingModel)
.where(AgentDeviceBindingModel.device_id == device_id)
.order_by(AgentDeviceBindingModel.is_default.desc(), AgentDeviceBindingModel.created_at.desc())
)
return list(result.scalars().all())
@staticmethod
async def get_binding(
db: AsyncSession,
device_id: str,
agent_id: str
) -> Optional[AgentDeviceBindingModel]:
"""Get specific binding"""
result = await db.execute(
select(AgentDeviceBindingModel)
.where(
AgentDeviceBindingModel.device_id == device_id,
AgentDeviceBindingModel.agent_id == agent_id
)
)
return result.scalar_one_or_none()
@staticmethod
async def get_default_binding(
db: AsyncSession,
device_id: str
) -> Optional[AgentDeviceBindingModel]:
"""Get default agent binding for a device"""
result = await db.execute(
select(AgentDeviceBindingModel)
.where(
AgentDeviceBindingModel.device_id == device_id,
AgentDeviceBindingModel.is_default == True
)
)
return result.scalar_one_or_none()
@staticmethod
async def create(
db: AsyncSession,
device_id: str,
agent_id: str,
is_default: bool = False
) -> AgentDeviceBindingModel:
"""Create a new binding"""
# If setting as default, clear other defaults first
if is_default:
await db.execute(
update(AgentDeviceBindingModel)
.where(AgentDeviceBindingModel.device_id == device_id)
.values(is_default=False)
)
binding = AgentDeviceBindingModel(
device_id=device_id,
agent_id=agent_id,
is_default=is_default
)
db.add(binding)
await db.commit()
await db.refresh(binding)
return binding
@staticmethod
async def set_default(
db: AsyncSession,
device_id: str,
agent_id: str
) -> bool:
"""Set an agent as default for device"""
# Clear all defaults for this device
await db.execute(
update(AgentDeviceBindingModel)
.where(AgentDeviceBindingModel.device_id == device_id)
.values(is_default=False)
)
# Set the specified agent as default
result = await db.execute(
update(AgentDeviceBindingModel)
.where(
AgentDeviceBindingModel.device_id == device_id,
AgentDeviceBindingModel.agent_id == agent_id
)
.values(is_default=True)
)
await db.commit()
return result.rowcount > 0
@staticmethod
async def delete(db: AsyncSession, device_id: str, agent_id: str) -> bool:
"""Delete a binding"""
result = await db.execute(
delete(AgentDeviceBindingModel)
.where(
AgentDeviceBindingModel.device_id == device_id,
AgentDeviceBindingModel.agent_id == agent_id
)
)
await db.commit()
return result.rowcount > 0
@staticmethod
async def delete_all_by_device(db: AsyncSession, device_id: str) -> int:
"""Delete all bindings for a device"""
result = await db.execute(
delete(AgentDeviceBindingModel)
.where(AgentDeviceBindingModel.device_id == device_id)
)
await db.commit()
return result.rowcount

View file

@ -0,0 +1,62 @@
from datetime import datetime
from typing import Optional, List
from pydantic import BaseModel, Field
# ==================== Request Schemas ====================
class DeviceBindRequest(BaseModel):
"""Request to bind a device"""
sn: str = Field(..., description="Device serial number")
agent_id: str = Field(..., description="Agent ID to bind")
class DeviceAddAgentRequest(BaseModel):
"""Request to add an agent to device"""
agent_id: str = Field(..., description="Agent ID to add")
is_default: bool = Field(default=False, description="Set as default agent")
class DeviceSetDefaultAgentRequest(BaseModel):
"""Request to set default agent"""
agent_id: str = Field(..., description="Agent ID to set as default")
# ==================== Response Schemas ====================
class AgentBindingResponse(BaseModel):
"""Agent binding info"""
agent_id: str
is_default: bool
created_at: datetime
class Config:
from_attributes = True
class DeviceResponse(BaseModel):
"""Device response"""
device_id: str
sn: str
owner_id: Optional[str] = None
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
class DeviceWithBindingsResponse(BaseModel):
"""Device with agent bindings"""
device_id: str
sn: str
owner_id: Optional[str] = None
created_at: datetime
updated_at: datetime
bindings: List[AgentBindingResponse] = []
class DeviceListResponse(BaseModel):
"""Device list response"""
devices: List[DeviceWithBindingsResponse]

View file

@ -0,0 +1,208 @@
from typing import List
from sqlalchemy.ext.asyncio import AsyncSession
from repositories.device import Device, AgentDeviceBinding, DeviceModel
from repositories.agent import Agent
from utils.exceptions import NotFoundException, BadRequestException
from utils.ulid import generate_device_id
from schemas.device import (
DeviceResponse,
DeviceWithBindingsResponse,
DeviceListResponse,
AgentBindingResponse
)
class DeviceService:
"""Device service layer"""
async def bind_device(
self,
db: AsyncSession,
owner_id: str,
sn: str,
agent_id: str
) -> DeviceWithBindingsResponse:
"""
Bind a device to user with an agent.
If device exists but unbound, update owner and add binding.
If device doesn't exist, create it.
"""
# Verify agent exists and belongs to user
agent = await Agent.get_by_id(db, agent_id)
if not agent:
raise NotFoundException("Agent not found")
if agent.owner_id != owner_id:
raise BadRequestException("Agent does not belong to you")
# Check if device exists
device = await Device.get_by_sn(db, sn)
if device:
# Device exists
if device.owner_id and device.owner_id != owner_id:
raise BadRequestException("Device is bound to another user")
# Update owner if not set
if not device.owner_id:
device = await Device.update_owner(db, device.device_id, owner_id)
else:
# Create new device
device_id = generate_device_id()
device = await Device.create(db, device_id, sn, owner_id)
# Check if binding already exists
existing_binding = await AgentDeviceBinding.get_binding(db, device.device_id, agent_id)
if not existing_binding:
# Check if device has any bindings (for setting default)
bindings = await AgentDeviceBinding.get_bindings_by_device(db, device.device_id)
is_default = len(bindings) == 0 # First binding is default
await AgentDeviceBinding.create(db, device.device_id, agent_id, is_default)
return await self._build_device_with_bindings(db, device)
async def unbind_device(
self,
db: AsyncSession,
owner_id: str,
device_id: str
) -> None:
"""Unbind device: clear owner and all agent bindings"""
device = await Device.get_by_id(db, device_id)
if not device:
raise NotFoundException("Device not found")
if device.owner_id != owner_id:
raise BadRequestException("Device does not belong to you")
await Device.unbind(db, device_id)
async def get_user_devices(
self,
db: AsyncSession,
owner_id: str
) -> DeviceListResponse:
"""Get all devices owned by user"""
devices = await Device.get_by_owner(db, owner_id)
result = []
for device in devices:
device_with_bindings = await self._build_device_with_bindings(db, device)
result.append(device_with_bindings)
return DeviceListResponse(devices=result)
async def add_agent_to_device(
self,
db: AsyncSession,
owner_id: str,
device_id: str,
agent_id: str,
is_default: bool = False
) -> DeviceWithBindingsResponse:
"""Add an agent binding to device"""
device = await Device.get_by_id(db, device_id)
if not device:
raise NotFoundException("Device not found")
if device.owner_id != owner_id:
raise BadRequestException("Device does not belong to you")
# Verify agent exists and belongs to user
agent = await Agent.get_by_id(db, agent_id)
if not agent:
raise NotFoundException("Agent not found")
if agent.owner_id != owner_id:
raise BadRequestException("Agent does not belong to you")
# Check if binding already exists
existing = await AgentDeviceBinding.get_binding(db, device_id, agent_id)
if existing:
raise BadRequestException("Agent is already bound to this device")
await AgentDeviceBinding.create(db, device_id, agent_id, is_default)
return await self._build_device_with_bindings(db, device)
async def remove_agent_from_device(
self,
db: AsyncSession,
owner_id: str,
device_id: str,
agent_id: str
) -> DeviceWithBindingsResponse:
"""Remove an agent binding from device"""
device = await Device.get_by_id(db, device_id)
if not device:
raise NotFoundException("Device not found")
if device.owner_id != owner_id:
raise BadRequestException("Device does not belong to you")
# Check if binding exists
binding = await AgentDeviceBinding.get_binding(db, device_id, agent_id)
if not binding:
raise NotFoundException("Binding not found")
was_default = binding.is_default
await AgentDeviceBinding.delete(db, device_id, agent_id)
# If removed the default, set another as default
if was_default:
bindings = await AgentDeviceBinding.get_bindings_by_device(db, device_id)
if bindings:
await AgentDeviceBinding.set_default(db, device_id, bindings[0].agent_id)
return await self._build_device_with_bindings(db, device)
async def set_default_agent(
self,
db: AsyncSession,
owner_id: str,
device_id: str,
agent_id: str
) -> DeviceWithBindingsResponse:
"""Set an agent as default for device"""
device = await Device.get_by_id(db, device_id)
if not device:
raise NotFoundException("Device not found")
if device.owner_id != owner_id:
raise BadRequestException("Device does not belong to you")
# Check if binding exists
binding = await AgentDeviceBinding.get_binding(db, device_id, agent_id)
if not binding:
raise NotFoundException("Agent is not bound to this device")
await AgentDeviceBinding.set_default(db, device_id, agent_id)
return await self._build_device_with_bindings(db, device)
async def _build_device_with_bindings(
self,
db: AsyncSession,
device: DeviceModel
) -> DeviceWithBindingsResponse:
"""Build device response with bindings"""
bindings = await AgentDeviceBinding.get_bindings_by_device(db, device.device_id)
return DeviceWithBindingsResponse(
device_id=device.device_id,
sn=device.sn,
owner_id=device.owner_id,
created_at=device.created_at,
updated_at=device.updated_at,
bindings=[
AgentBindingResponse(
agent_id=b.agent_id,
is_default=b.is_default,
created_at=b.created_at
)
for b in bindings
]
)
device_service = DeviceService()

View file

@ -44,3 +44,14 @@ def generate_voice_id() -> str:
"""
return f"voice_{ULID()}"
def generate_device_id() -> str:
"""
Generate unique device ID with 'device_' prefix and ULID
Format: device_01JD8X0000ABC123DEF456GH (33 chars total)
- Prefix: device_
- ULID: 26 chars (128-bit unique, time-sortable)
"""
return f"device_{ULID()}"