Files
bakery-ia/services/external/app/api/traffic.py

184 lines
7.5 KiB
Python
Raw Normal View History

2025-08-12 18:17:30 +02:00
# services/external/app/api/traffic.py
2025-07-19 12:09:10 +02:00
"""Traffic data API endpoints with improved error handling"""
2025-07-18 11:51:43 +02:00
2025-07-26 18:46:52 +02:00
from fastapi import APIRouter, Depends, HTTPException, Query, Path
2025-07-21 14:41:33 +02:00
from typing import List, Dict, Any
2025-07-18 11:51:43 +02:00
from datetime import datetime, timedelta
2025-07-19 12:09:10 +02:00
import structlog
2025-07-26 18:46:52 +02:00
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
2025-07-18 11:51:43 +02:00
from app.core.database import get_db
from app.services.traffic_service import TrafficService
2025-08-12 18:17:30 +02:00
from app.services.messaging import publish_traffic_updated
from app.schemas.traffic import (
2025-07-18 11:51:43 +02:00
TrafficDataResponse,
2025-08-12 18:17:30 +02:00
HistoricalTrafficRequest,
TrafficForecastRequest
2025-07-18 11:51:43 +02:00
)
2025-07-21 14:41:33 +02:00
from shared.auth.decorators import (
2025-07-27 20:20:09 +02:00
get_current_user_dep
2025-07-21 14:41:33 +02:00
)
2025-07-26 18:46:52 +02:00
router = APIRouter(tags=["traffic"])
2025-07-18 11:51:43 +02:00
traffic_service = TrafficService()
2025-07-19 12:09:10 +02:00
logger = structlog.get_logger()
2025-07-18 11:51:43 +02:00
2025-07-27 19:30:42 +02:00
@router.get("/tenants/{tenant_id}/traffic/current", response_model=TrafficDataResponse)
2025-07-18 11:51:43 +02:00
async def get_current_traffic(
latitude: float = Query(..., description="Latitude"),
longitude: float = Query(..., description="Longitude"),
2025-07-26 18:46:52 +02:00
tenant_id: UUID = Path(..., description="Tenant ID"),
2025-07-21 14:41:33 +02:00
current_user: Dict[str, Any] = Depends(get_current_user_dep),
2025-07-18 11:51:43 +02:00
):
"""Get current traffic data for location"""
try:
2025-07-19 12:09:10 +02:00
logger.debug("API: Getting current traffic", lat=latitude, lon=longitude)
2025-07-18 11:51:43 +02:00
traffic = await traffic_service.get_current_traffic(latitude, longitude)
2025-07-19 12:09:10 +02:00
2025-07-18 11:51:43 +02:00
if not traffic:
2025-07-19 12:09:10 +02:00
logger.warning("No traffic data available", lat=latitude, lon=longitude)
2025-07-18 11:51:43 +02:00
raise HTTPException(status_code=404, detail="Traffic data not available")
2025-07-19 12:09:10 +02:00
# Publish event (with error handling)
try:
2025-08-08 23:06:54 +02:00
await publish_traffic_updated({
2025-07-19 12:09:10 +02:00
"type": "current_requested",
"latitude": latitude,
"longitude": longitude,
"timestamp": datetime.utcnow().isoformat()
})
except Exception as pub_error:
logger.warning("Failed to publish traffic event", error=str(pub_error))
# Continue processing - event publishing failure shouldn't break the API
2025-07-18 11:51:43 +02:00
2025-07-19 12:09:10 +02:00
logger.debug("Successfully returning traffic data",
volume=traffic.get('traffic_volume') if isinstance(traffic, dict) else getattr(traffic, 'traffic_volume', None),
congestion=traffic.get('congestion_level') if isinstance(traffic, dict) else getattr(traffic, 'congestion_level', None))
2025-07-18 11:51:43 +02:00
return traffic
2025-07-19 12:09:10 +02:00
except HTTPException:
# Re-raise HTTP exceptions
raise
2025-07-18 11:51:43 +02:00
except Exception as e:
2025-07-19 12:09:10 +02:00
logger.error("Unexpected error in traffic API", error=str(e))
import traceback
logger.error("Traffic API traceback", traceback=traceback.format_exc())
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
2025-07-18 11:51:43 +02:00
2025-07-27 20:20:09 +02:00
@router.post("/tenants/{tenant_id}/traffic/historical")
2025-07-18 11:51:43 +02:00
async def get_historical_traffic(
2025-07-27 20:20:09 +02:00
request: HistoricalTrafficRequest,
2025-07-18 11:51:43 +02:00
db: AsyncSession = Depends(get_db),
2025-07-26 18:46:52 +02:00
tenant_id: UUID = Path(..., description="Tenant ID"),
2025-07-21 14:41:33 +02:00
current_user: Dict[str, Any] = Depends(get_current_user_dep),
2025-07-18 11:51:43 +02:00
):
2025-07-27 20:20:09 +02:00
"""Get historical traffic data with date range in payload"""
2025-07-18 11:51:43 +02:00
try:
# Validate date range
2025-07-27 20:20:09 +02:00
if request.end_date <= request.start_date:
2025-07-18 11:51:43 +02:00
raise HTTPException(status_code=400, detail="End date must be after start date")
2025-07-27 21:44:18 +02:00
if (request.end_date - request.start_date).days > 1000:
2025-07-18 11:51:43 +02:00
raise HTTPException(status_code=400, detail="Date range cannot exceed 90 days")
historical_data = await traffic_service.get_historical_traffic(
2025-08-12 18:17:30 +02:00
request.latitude, request.longitude, request.start_date, request.end_date, str(tenant_id)
2025-07-18 11:51:43 +02:00
)
2025-07-19 12:09:10 +02:00
# Publish event (with error handling)
try:
2025-08-08 23:06:54 +02:00
await publish_traffic_updated({
2025-07-19 12:09:10 +02:00
"type": "historical_requested",
2025-07-27 20:20:09 +02:00
"latitude": request.latitude,
"longitude": request.longitude,
"start_date": request.start_date.isoformat(),
"end_date": request.end_date.isoformat(),
2025-07-19 12:09:10 +02:00
"records_count": len(historical_data),
"timestamp": datetime.utcnow().isoformat()
})
except Exception as pub_error:
logger.warning("Failed to publish historical traffic event", error=str(pub_error))
# Continue processing
2025-07-18 11:51:43 +02:00
return historical_data
2025-07-19 12:09:10 +02:00
except HTTPException:
raise
except Exception as e:
logger.error("Unexpected error in historical traffic API", error=str(e))
2025-08-08 23:29:48 +02:00
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
2025-08-12 18:17:30 +02:00
@router.post("/tenants/{tenant_id}/traffic/forecast")
async def get_traffic_forecast(
request: TrafficForecastRequest,
2025-08-08 23:29:48 +02:00
tenant_id: UUID = Path(..., description="Tenant ID"),
current_user: Dict[str, Any] = Depends(get_current_user_dep),
):
2025-08-12 18:17:30 +02:00
"""Get traffic forecast for location"""
2025-08-08 23:29:48 +02:00
try:
2025-08-12 18:17:30 +02:00
logger.debug("API: Getting traffic forecast",
lat=request.latitude, lon=request.longitude, hours=request.hours)
# For now, return mock forecast data since we don't have a real traffic forecast service
# In a real implementation, this would call a traffic forecasting service
# Generate mock forecast data for the requested hours
forecast_data = []
from datetime import datetime, timedelta
base_time = datetime.utcnow()
for hour in range(request.hours):
forecast_time = base_time + timedelta(hours=hour)
# Mock traffic pattern (higher during rush hours)
hour_of_day = forecast_time.hour
if 7 <= hour_of_day <= 9 or 17 <= hour_of_day <= 19: # Rush hours
traffic_volume = 120
pedestrian_count = 80
congestion_level = "high"
average_speed = 15
elif 22 <= hour_of_day or hour_of_day <= 6: # Night hours
traffic_volume = 20
pedestrian_count = 10
congestion_level = "low"
average_speed = 50
else: # Regular hours
traffic_volume = 60
pedestrian_count = 40
congestion_level = "medium"
average_speed = 35
# Use consistent TrafficDataResponse format
forecast_data.append({
"date": forecast_time.isoformat(),
"traffic_volume": traffic_volume,
"pedestrian_count": pedestrian_count,
"congestion_level": congestion_level,
"average_speed": average_speed,
"source": "madrid_opendata_forecast"
})
2025-08-08 23:29:48 +02:00
2025-08-12 18:17:30 +02:00
# Publish event (with error handling)
2025-08-08 23:29:48 +02:00
try:
await publish_traffic_updated({
2025-08-12 18:17:30 +02:00
"type": "forecast_requested",
2025-08-08 23:29:48 +02:00
"latitude": request.latitude,
"longitude": request.longitude,
2025-08-12 18:17:30 +02:00
"hours": request.hours,
2025-08-08 23:29:48 +02:00
"timestamp": datetime.utcnow().isoformat()
})
except Exception as pub_error:
2025-08-12 18:17:30 +02:00
logger.warning("Failed to publish traffic forecast event", error=str(pub_error))
# Continue processing
2025-08-08 23:29:48 +02:00
2025-08-12 18:17:30 +02:00
logger.debug("Successfully returning traffic forecast", records=len(forecast_data))
return forecast_data
2025-08-08 23:29:48 +02:00
except HTTPException:
raise
except Exception as e:
2025-08-12 18:17:30 +02:00
logger.error("Unexpected error in traffic forecast API", error=str(e))
2025-07-19 12:09:10 +02:00
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")