feat: cursor pagination

This commit is contained in:
Harold 2025-11-21 15:45:26 +08:00
parent f835bb0774
commit 9620b9f1df
8 changed files with 178 additions and 54 deletions

View file

@ -12,16 +12,25 @@ router = APIRouter()
@router.get("", summary="Get user's agent list")
async def get_agent_list(
page: int = Query(1, ge=1),
page_size: int = Query(10, ge=1, le=20),
cursor: Optional[str] = Query(None, description="Pagination cursor"),
page_size: int = Query(10, ge=1, le=20, description="Number of items per page"),
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""Get user's agent list"""
"""
Get user's agent list with cursor-based pagination
Cursor-based pagination prevents data drift when creating/deleting agents:
- **First request**: No cursor parameter needed
- **Subsequent requests**: Use `next_cursor` from previous response
- **Returns**: List of agents with `next_cursor` and `has_more` flag
Agents are ordered by creation time (newest first).
"""
agent_list = await agent_service.get_agent_list(
db=db,
owner_id=current_user_id,
page=page,
cursor=cursor,
page_size=page_size
)
return success_response(data=agent_list.model_dump())

View file

@ -91,20 +91,27 @@ async def get_default_voices(
@router.get("/", summary="Get My Voices")
async def get_my_voices(
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
cursor: Optional[str] = Query(None, description="Pagination cursor (ISO datetime from previous response)"),
page_size: int = Query(10, ge=1, le=50, description="Number of items per page"),
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
Get user's custom voices (my_voices tab)
Returns voices created/cloned by the current user
Get user's custom voices with cursor-based pagination
Cursor-based pagination prevents data drift when adding/removing voices:
- **First request**: No cursor parameter needed
- **Subsequent requests**: Use `next_cursor` from previous response
- **Returns**: List of voices with `next_cursor` and `has_more` flag
Voices are ordered by creation time (newest first).
Returns voices created/cloned/added by the current user.
"""
# Get raw data from service layer
voices, count = await voice_service.get_my_voices(
voices, next_cursor, has_more = await voice_service.get_my_voices(
db=db,
owner_id=current_user_id,
page=page,
cursor=cursor,
page_size=page_size
)
@ -114,13 +121,15 @@ async def get_my_voices(
voice_responses.append(LiveAgentVoice(
voice_id=voice.voice_id,
name=voice.name,
tags=voice.tags or [],
desc=voice.desc,
created_at=voice.created_at,
))
# Build response
voice_list = MyVoiceResponse(
voices=voice_responses,
has_more=count > page * page_size
next_cursor=next_cursor,
has_more=has_more
)
return success_response(data=voice_list.model_dump())
@ -140,16 +149,26 @@ async def clone_voice(
"""
# Clone voice
voice_id = await voice_service.clone_voice(
voice_id, samples = await voice_service.clone_voice(
fish_client=fish_client,
audio_file=audio_file,
text=text
)
# Build response
if samples:
sample = AudioSample(
title=samples[0].title,
text=samples[0].text,
audio=samples[0].audio
)
else:
sample = None
return success_response(
data={
"voice_id": voice_id,
"sample": sample,
},
message="Voice cloned successfully"
)

View file

@ -1,5 +1,5 @@
from datetime import datetime
from typing import Optional, List
from typing import Optional, List, Tuple
from sqlalchemy import String, Text, TIMESTAMP, ForeignKey, Index, select, delete
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.ext.asyncio import AsyncSession
@ -75,18 +75,54 @@ class Agent:
async def get_agents_by_owner(
db: AsyncSession,
owner_id: str,
skip: int = 0,
cursor: Optional[str] = None,
limit: int = 20
) -> List[AgentModel]:
"""Get all agents owned by a user"""
result = await db.execute(
select(AgentModel)
.where(AgentModel.owner_id == owner_id)
.offset(skip)
.limit(limit)
.order_by(AgentModel.created_at.desc())
)
return result.scalars().all()
) -> Tuple[List[AgentModel], Optional[str], bool]:
"""
Get agents owned by a user with cursor-based pagination
Args:
db: Database session
owner_id: User ID
cursor: ISO datetime string of last item's created_at
limit: Number of items to return
Returns:
(agents, next_cursor, has_more)
"""
query = select(AgentModel).where(AgentModel.owner_id == owner_id)
# Apply cursor filter if provided
if cursor:
try:
cursor_time = datetime.fromisoformat(cursor)
# Get records created before cursor time
query = query.where(AgentModel.created_at < cursor_time)
except (ValueError, TypeError):
# Invalid cursor, ignore and start from beginning
pass
# Order by created_at DESC, agent_id DESC for stable sorting
# Fetch limit + 1 to check if there are more records
query = query.order_by(
AgentModel.created_at.desc(),
AgentModel.agent_id.desc()
).limit(limit + 1)
result = await db.execute(query)
agents: List[AgentModel] = result.scalars().all()
# Check if there are more records
has_more = len(agents) > limit
if has_more:
agents = agents[:limit]
# Generate next cursor from last item
next_cursor = None
if has_more and agents:
next_cursor = agents[-1].created_at.isoformat()
return agents, next_cursor, has_more
@staticmethod
async def create(

View file

@ -1,5 +1,5 @@
from datetime import datetime
from typing import Optional, List
from typing import Optional, List, Tuple
from sqlalchemy import String, Text, TIMESTAMP, ForeignKey, Index, select, func, update
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.ext.asyncio import AsyncSession
@ -71,10 +71,21 @@ class Voice:
async def get_list(
db: AsyncSession,
owner_id: Optional[str] = None,
skip: int = 0,
cursor: Optional[str] = None,
limit: int = 100
) -> List[VoiceModel]:
"""Get voices with filters"""
) -> Tuple[List[VoiceModel], Optional[str], bool]:
"""
Get voices with cursor-based pagination
Args:
db: Database session
owner_id: Filter by owner ID
cursor: ISO datetime string of last item's created_at
limit: Number of items to return
Returns:
(voices, next_cursor, has_more)
"""
query = select(VoiceModel)
if owner_id:
@ -83,10 +94,37 @@ class Voice:
VoiceModel.owner_id == owner_id
)
query = query.offset(skip).limit(limit).order_by(VoiceModel.created_at.desc())
# Apply cursor filter if provided
if cursor:
try:
cursor_time = datetime.fromisoformat(cursor)
# Get records created before cursor time
query = query.where(VoiceModel.created_at < cursor_time)
except (ValueError, TypeError):
# Invalid cursor, ignore and start from beginning
pass
# Order by created_at DESC, voice_id DESC for stable sorting
# Fetch limit + 1 to check if there are more records
query = query.order_by(
VoiceModel.created_at.desc(),
VoiceModel.voice_id.desc()
).limit(limit + 1)
result = await db.execute(query)
return result.scalars().all()
voices = list(result.scalars().all())
# Check if there are more records
has_more = len(voices) > limit
if has_more:
voices = voices[:limit]
# Generate next cursor from last item
next_cursor = None
if has_more and voices:
next_cursor = voices[-1].created_at.isoformat()
return voices, next_cursor, has_more
async def count(
db: AsyncSession,

View file

@ -42,8 +42,10 @@ class AgentResponse(BaseModel):
class AgentListResponse(BaseModel):
"""Agent list response"""
"""Agent list response with cursor-based pagination"""
agents: list[AgentResponse]
next_cursor: Optional[str] = None
has_more: bool = False
class AgentConfigResponse(BaseModel):

View file

@ -45,6 +45,8 @@ class LiveAgentVoice(BaseModel):
samples: Optional[List[AudioSample]] = None
created_at: datetime
class FishAudioVoiceResponse(BaseModel):
@ -65,9 +67,10 @@ class DiscoverVoiceResponse(BaseModel):
has_more: bool
class MyVoiceResponse(BaseModel):
"""My voice response"""
"""My voice response with cursor-based pagination"""
voices: List[LiveAgentVoice]
has_more: bool
next_cursor: Optional[str] = None
has_more: bool = False
class VoiceCloneStatusResponse(BaseModel):

View file

@ -23,20 +23,34 @@ class AgentService:
self,
db: AsyncSession,
owner_id: str,
page: int = 1,
cursor: Optional[str] = None,
page_size: int = 10
) -> AgentListResponse:
"""Get user's agent list"""
skip = (page - 1) * page_size
agents = await Agent.get_agents_by_owner(
"""
Get user's agent list with cursor-based pagination
Args:
db: Database session
owner_id: User ID
cursor: Pagination cursor (ISO datetime string)
page_size: Number of items per page
Returns:
AgentListResponse with agents, next_cursor, and has_more
"""
agents, next_cursor, has_more = await Agent.get_agents_by_owner(
db,
owner_id=owner_id,
skip=skip,
owner_id=owner_id,
cursor=cursor,
limit=page_size
)
agent_responses = [AgentResponse.model_validate(a) for a in agents]
return AgentListResponse(agents=agent_responses)
return AgentListResponse(
agents=agent_responses,
next_cursor=next_cursor,
has_more=has_more
)
async def get_agent_detail(
self,

View file

@ -2,7 +2,7 @@ from typing import Optional, List, Tuple
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import UploadFile
from fishaudio import AsyncFishAudio
from fishaudio.types import PaginatedResponse, Voice as FishVoice
from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as FishSample
from repositories import VoiceModel, Voice
from utils.ulid import generate_voice_id
@ -64,32 +64,36 @@ class VoiceService:
self,
db: AsyncSession,
owner_id: str,
page: int = 1,
cursor: Optional[str] = None,
page_size: int = 20
) -> Tuple[List[VoiceModel], int]:
) -> Tuple[List[VoiceModel], Optional[str], bool]:
"""
Get user's custom voices (my_voices tab)
Get user's custom voices with cursor-based pagination
Args:
db: Database session
owner_id: User ID
cursor: Pagination cursor (ISO datetime string)
page_size: Number of items per page
Returns:
List of VoiceModel objects
Tuple of (voices, next_cursor, has_more)
"""
skip = (page - 1) * page_size
voices = await Voice.get_list(
voices, next_cursor, has_more = await Voice.get_list(
db,
owner_id=owner_id,
skip=skip,
cursor=cursor,
limit=page_size
)
count = await Voice.count(db, owner_id=owner_id)
return voices, count
return voices, next_cursor, has_more
async def clone_voice(
self,
fish_client: AsyncFishAudio,
audio_file: UploadFile,
text: Optional[str] = None
) -> VoiceModel:
) -> Tuple[str, List[FishSample]]:
"""
Clone a voice using Fish Audio API
@ -117,8 +121,7 @@ class VoiceService:
visibility="private",
enhance_audio_quality=True
)
return fish_voice.id
return fish_voice.id, fish_voice.samples
async def add_voice(
self,