75 lines
3.0 KiB
Python
75 lines
3.0 KiB
Python
# ================================================================
|
|
# Gateway Integration: Update gateway/app/routes/forecasting.py
|
|
# ================================================================
|
|
"""Forecasting service routes for API Gateway"""
|
|
|
|
from fastapi import APIRouter, Request
|
|
import httpx
|
|
import logging
|
|
|
|
from app.core.config import settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
router = APIRouter()
|
|
|
|
@router.api_route("/forecasts/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
|
|
async def proxy_forecasts(request: Request, path: str):
|
|
"""Proxy forecast requests to forecasting service"""
|
|
return await _proxy_request(request, f"/api/v1/forecasts/{path}")
|
|
|
|
@router.api_route("/predictions/{path:path}", methods=["GET", "POST", "OPTIONS"])
|
|
async def proxy_predictions(request: Request, path: str):
|
|
"""Proxy prediction requests to forecasting service"""
|
|
return await _proxy_request(request, f"/api/v1/predictions/{path}")
|
|
|
|
async def _proxy_request(request: Request, target_path: str):
|
|
"""Proxy request to forecasting service with user context"""
|
|
|
|
# Handle OPTIONS requests directly for CORS
|
|
if request.method == "OPTIONS":
|
|
return Response(
|
|
status_code=200,
|
|
headers={
|
|
"Access-Control-Allow-Origin": settings.CORS_ORIGINS_LIST,
|
|
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
|
|
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Tenant-ID",
|
|
"Access-Control-Allow-Credentials": "true",
|
|
"Access-Control-Max-Age": "86400" # Cache preflight for 24 hours
|
|
}
|
|
)
|
|
|
|
try:
|
|
url = f"{settings.FORECASTING_SERVICE_URL}{target_path}"
|
|
|
|
# Forward headers and add user context
|
|
headers = dict(request.headers)
|
|
headers.pop("host", None)
|
|
|
|
# Add user context from gateway authentication
|
|
if hasattr(request.state, 'user'):
|
|
headers["X-User-ID"] = str(request.state.user.get("user_id"))
|
|
headers["X-User-Email"] = request.state.user.get("email", "")
|
|
headers["X-Tenant-ID"] = str(request.state.user.get("tenant_id"))
|
|
headers["X-User-Roles"] = ",".join(request.state.user.get("roles", []))
|
|
|
|
# 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.request(
|
|
method=request.method,
|
|
url=url,
|
|
headers=headers,
|
|
content=body,
|
|
params=request.query_params
|
|
)
|
|
|
|
# Return response
|
|
return response.json() if response.headers.get("content-type", "").startswith("application/json") else response.text
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error proxying to forecasting service: {e}")
|
|
raise
|