"""Connection quality detection and testing endpoints.""" import time from fastapi import APIRouter from pydantic import BaseModel router = APIRouter(tags=["quality"]) class ConnectionTestRequest(BaseModel): """Request schema for connection test.""" test_size_bytes: int = 100000 # 100KB default test size class ConnectionTestResponse(BaseModel): """Response schema for connection test results.""" speed_mbps: float latency_ms: float quality_tier: str # 'low', 'medium', 'high' recommended_thumbnail: str # 'low', 'medium', 'high' @router.post("/connection/test", response_model=ConnectionTestResponse) async def test_connection_speed(request: ConnectionTestRequest) -> ConnectionTestResponse: """ Test connection speed and return quality recommendation. This endpoint helps determine appropriate thumbnail quality. The client measures download time of test data to calculate speed. Args: request: Test configuration Returns: Connection quality information and recommendations """ # Record start time for latency measurement start_time = time.time() # Simulate latency measurement (in real implementation, client measures this) latency_ms = (time.time() - start_time) * 1000 # Client will measure actual download time # Here we just provide the test data size for calculation # The client calculates: speed_mbps = (test_size_bytes * 8) / (download_time_seconds * 1_000_000) # For now, we return a standard response # In practice, the client does the speed calculation return ConnectionTestResponse( speed_mbps=0.0, # Client calculates this latency_ms=latency_ms, quality_tier="medium", recommended_thumbnail="medium", ) @router.get("/connection/test-data") async def get_test_data(size: int = 100000) -> bytes: """ Serve test data for connection speed measurement. Client downloads this and measures time to calculate speed. Args: size: Size of test data in bytes (max 500KB) Returns: Random bytes for speed testing """ import secrets # Cap size at 500KB to prevent abuse size = min(size, 500000) # Generate random bytes return secrets.token_bytes(size)