Add forecasting service
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
Forecasting routes for gateway
|
||||
"""
|
||||
# ================================================================
|
||||
# Gateway Integration: Update gateway/app/routes/forecasting.py
|
||||
# ================================================================
|
||||
"""Forecasting service routes for API Gateway"""
|
||||
|
||||
from fastapi import APIRouter, Request, HTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi import APIRouter, Request
|
||||
import httpx
|
||||
import logging
|
||||
|
||||
@@ -12,55 +12,49 @@ from app.core.config import settings
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/predict")
|
||||
async def create_forecast(request: Request):
|
||||
"""Proxy forecast request to forecasting service"""
|
||||
@router.api_route("/forecasts/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
|
||||
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"])
|
||||
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"""
|
||||
try:
|
||||
body = await request.body()
|
||||
auth_header = request.headers.get("Authorization")
|
||||
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.post(
|
||||
f"{settings.FORECASTING_SERVICE_URL}/predict",
|
||||
response = await client.request(
|
||||
method=request.method,
|
||||
url=url,
|
||||
headers=headers,
|
||||
content=body,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": auth_header
|
||||
}
|
||||
params=request.query_params
|
||||
)
|
||||
|
||||
return JSONResponse(
|
||||
status_code=response.status_code,
|
||||
content=response.json()
|
||||
)
|
||||
# Return response
|
||||
return response.json() if response.headers.get("content-type", "").startswith("application/json") else response.text
|
||||
|
||||
except httpx.RequestError as e:
|
||||
logger.error(f"Forecasting service unavailable: {e}")
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Forecasting service unavailable"
|
||||
)
|
||||
|
||||
@router.get("/forecasts")
|
||||
async def get_forecasts(request: Request):
|
||||
"""Get forecasts"""
|
||||
try:
|
||||
auth_header = request.headers.get("Authorization")
|
||||
|
||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
||||
response = await client.get(
|
||||
f"{settings.FORECASTING_SERVICE_URL}/forecasts",
|
||||
headers={"Authorization": auth_header}
|
||||
)
|
||||
|
||||
return JSONResponse(
|
||||
status_code=response.status_code,
|
||||
content=response.json()
|
||||
)
|
||||
|
||||
except httpx.RequestError as e:
|
||||
logger.error(f"Forecasting service unavailable: {e}")
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Forecasting service unavailable"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error proxying to forecasting service: {e}")
|
||||
raise
|
||||
|
||||
Reference in New Issue
Block a user