Fix issues

This commit is contained in:
Urtzi Alfaro
2025-07-18 11:51:43 +02:00
parent 9391368b83
commit 592a810762
35 changed files with 3806 additions and 122 deletions

View File

@@ -1,66 +1,71 @@
"""
Data routes for gateway
"""
# ================================================================
# gateway/app/routes/data.py
# ================================================================
"""Data service routes for API Gateway"""
from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import JSONResponse
from fastapi import APIRouter, Request, Depends, HTTPException
from fastapi.responses import StreamingResponse
import httpx
import logging
import structlog
from app.core.config import settings
from app.core.auth import verify_token
logger = logging.getLogger(__name__)
logger = structlog.get_logger()
router = APIRouter()
@router.post("/upload")
async def upload_sales_data(request: Request):
"""Proxy data upload to data service"""
@router.api_route("/sales/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def proxy_sales(request: Request, path: str, current_user: dict = Depends(verify_token)):
"""Proxy sales data requests to data service"""
return await _proxy_request(request, f"/api/v1/sales/{path}")
@router.api_route("/weather/{path:path}", methods=["GET", "POST"])
async def proxy_weather(request: Request, path: str, current_user: dict = Depends(verify_token)):
"""Proxy weather requests to data service"""
return await _proxy_request(request, f"/api/v1/weather/{path}")
@router.api_route("/traffic/{path:path}", methods=["GET", "POST"])
async def proxy_traffic(request: Request, path: str, current_user: dict = Depends(verify_token)):
"""Proxy traffic requests to data service"""
return await _proxy_request(request, f"/api/v1/traffic/{path}")
async def _proxy_request(request: Request, target_path: str):
"""Proxy request to data service"""
try:
body = await request.body()
auth_header = request.headers.get("Authorization")
url = f"{settings.DATA_SERVICE_URL}{target_path}"
# Forward headers (including auth)
headers = dict(request.headers)
headers.pop("host", None) # Remove host header
# Get request body if present
body = None
if request.method in ["POST", "PUT", "PATCH"]:
body = await request.body()
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.post(
f"{settings.DATA_SERVICE_URL}/upload",
content=body,
headers={
"Content-Type": "application/json",
"Authorization": auth_header
}
)
return JSONResponse(
status_code=response.status_code,
content=response.json()
response = await client.request(
method=request.method,
url=url,
params=request.query_params,
headers=headers,
content=body
)
# Return streaming response for large payloads
if int(response.headers.get("content-length", 0)) > 1024:
return StreamingResponse(
iter([response.content]),
status_code=response.status_code,
headers=dict(response.headers),
media_type=response.headers.get("content-type")
)
else:
return response.json() if response.headers.get("content-type", "").startswith("application/json") else response.content
except httpx.RequestError as e:
logger.error(f"Data service unavailable: {e}")
raise HTTPException(
status_code=503,
detail="Data service unavailable"
)
@router.get("/sales")
async def get_sales_data(request: Request):
"""Get sales data"""
try:
auth_header = request.headers.get("Authorization")
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.get(
f"{settings.DATA_SERVICE_URL}/sales",
headers={"Authorization": auth_header}
)
return JSONResponse(
status_code=response.status_code,
content=response.json()
)
except httpx.RequestError as e:
logger.error(f"Data service unavailable: {e}")
raise HTTPException(
status_code=503,
detail="Data service unavailable"
)
logger.error("Data service request failed", error=str(e))
raise HTTPException(status_code=503, detail="Data service unavailable")
except Exception as e:
logger.error("Unexpected error in data proxy", error=str(e))
raise HTTPException(status_code=500, detail="Internal server error")