Phase 10: Per-User Rate Limits — messages + tokens, quota UI, admin usage
Backend:
- max_ai_messages_per_day + max_ai_tokens_per_day on User model (nullable, override)
- Migration 008: add columns + seed default settings (100 msgs, 500K tokens)
- usage_service: count today's messages + tokens, check quota, get limits
- GET /chats/quota returns usage vs limits + reset time
- POST /chats/{id}/messages checks quota before streaming (429 if exceeded)
- Admin user schemas expose both limit fields
- GET /admin/usage returns per-user daily message + token counts
- admin_user_service allows updating both limit fields
Frontend:
- Chat header shows "X/Y messages · XK/YK tokens" with red highlight at limit
- Quota refreshes every 30s via TanStack Query
- Admin usage page with table: user, messages today, tokens today
- Route + sidebar entry for admin usage
- English + Russian translations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -19,10 +19,19 @@ from app.schemas.chat import (
|
||||
)
|
||||
from app.services import chat_service, skill_service
|
||||
from app.services.ai_service import stream_ai_response
|
||||
from app.services.usage_service import check_user_quota
|
||||
|
||||
router = APIRouter(prefix="/chats", tags=["chats"])
|
||||
|
||||
|
||||
@router.get("/quota")
|
||||
async def get_quota(
|
||||
user: Annotated[User, Depends(get_current_user)],
|
||||
db: Annotated[AsyncSession, Depends(get_db)],
|
||||
):
|
||||
return await check_user_quota(db, user)
|
||||
|
||||
|
||||
@router.post("/", response_model=ChatResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_chat(
|
||||
data: CreateChatRequest,
|
||||
@@ -96,6 +105,13 @@ async def send_message(
|
||||
user: Annotated[User, Depends(get_current_user)],
|
||||
db: Annotated[AsyncSession, Depends(get_db)],
|
||||
):
|
||||
from fastapi import HTTPException
|
||||
quota = await check_user_quota(db, user)
|
||||
if quota["messages_exceeded"]:
|
||||
raise HTTPException(status_code=429, detail=f"Daily message limit reached ({quota['message_limit']}). Resets at {quota['resets_at']}.")
|
||||
if quota["tokens_exceeded"]:
|
||||
raise HTTPException(status_code=429, detail=f"Daily token limit reached ({quota['token_limit']}). Resets at {quota['resets_at']}.")
|
||||
|
||||
return StreamingResponse(
|
||||
stream_ai_response(db, chat_id, user.id, data.content),
|
||||
media_type="text/event-stream",
|
||||
|
||||
Reference in New Issue
Block a user