2025-07-26 18:46:52 +02:00
|
|
|
# gateway/app/routes/tenant.py - COMPLETELY UPDATED
|
2025-07-17 19:46:41 +02:00
|
|
|
"""
|
2025-07-26 18:46:52 +02:00
|
|
|
Tenant routes for API Gateway - Handles all tenant-scoped endpoints
|
2025-07-17 19:46:41 +02:00
|
|
|
"""
|
|
|
|
|
|
2025-07-26 18:46:52 +02:00
|
|
|
from fastapi import APIRouter, Request, Response, HTTPException, Path
|
2025-07-17 19:46:41 +02:00
|
|
|
from fastapi.responses import JSONResponse
|
|
|
|
|
import httpx
|
|
|
|
|
import logging
|
2025-07-26 18:46:52 +02:00
|
|
|
from typing import Optional
|
2025-07-17 19:46:41 +02:00
|
|
|
|
|
|
|
|
from app.core.config import settings
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
2025-07-26 18:46:52 +02:00
|
|
|
# ================================================================
|
|
|
|
|
# TENANT MANAGEMENT ENDPOINTS
|
|
|
|
|
# ================================================================
|
|
|
|
|
|
2025-07-20 23:15:57 +02:00
|
|
|
@router.post("/register")
|
2025-07-17 19:46:41 +02:00
|
|
|
async def create_tenant(request: Request):
|
|
|
|
|
"""Proxy tenant creation to tenant service"""
|
2025-07-26 18:46:52 +02:00
|
|
|
return await _proxy_to_tenant_service(request, "/api/v1/tenants/register")
|
2025-07-17 19:46:41 +02:00
|
|
|
|
2025-07-26 18:46:52 +02:00
|
|
|
@router.get("/{tenant_id}")
|
|
|
|
|
async def get_tenant(request: Request, tenant_id: str = Path(...)):
|
|
|
|
|
"""Get specific tenant details"""
|
|
|
|
|
return await _proxy_to_tenant_service(request, f"/api/v1/tenants/{tenant_id}")
|
|
|
|
|
|
|
|
|
|
@router.put("/{tenant_id}")
|
|
|
|
|
async def update_tenant(request: Request, tenant_id: str = Path(...)):
|
|
|
|
|
"""Update tenant details"""
|
|
|
|
|
return await _proxy_to_tenant_service(request, f"/api/v1/tenants/{tenant_id}")
|
|
|
|
|
|
|
|
|
|
@router.get("/{tenant_id}/members")
|
|
|
|
|
async def get_tenant_members(request: Request, tenant_id: str = Path(...)):
|
|
|
|
|
"""Get tenant members"""
|
|
|
|
|
return await _proxy_to_tenant_service(request, f"/api/v1/tenants/{tenant_id}/members")
|
|
|
|
|
|
|
|
|
|
# ================================================================
|
|
|
|
|
# TENANT-SCOPED DATA SERVICE ENDPOINTS
|
|
|
|
|
# ================================================================
|
|
|
|
|
|
2025-07-26 21:10:54 +02:00
|
|
|
@router.api_route("/{tenant_id}/sales{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
|
|
|
|
|
async def proxy_all_tenant_sales_alternative(request: Request, tenant_id: str = Path(...), path: str = ""):
|
|
|
|
|
"""Proxy all tenant sales requests - handles both base and sub-paths"""
|
|
|
|
|
base_path = f"/api/v1/tenants/{tenant_id}/sales"
|
|
|
|
|
|
|
|
|
|
# If path is empty or just "/", use base path
|
|
|
|
|
if not path or path == "/" or path == "":
|
|
|
|
|
target_path = base_path
|
|
|
|
|
else:
|
|
|
|
|
# Ensure path starts with "/"
|
|
|
|
|
if not path.startswith("/"):
|
|
|
|
|
path = "/" + path
|
|
|
|
|
target_path = base_path + path
|
|
|
|
|
|
2025-07-26 18:46:52 +02:00
|
|
|
return await _proxy_to_data_service(request, target_path)
|
|
|
|
|
|
|
|
|
|
@router.api_route("/{tenant_id}/weather/{path:path}", methods=["GET", "POST", "OPTIONS"])
|
|
|
|
|
async def proxy_tenant_weather(request: Request, tenant_id: str = Path(...), path: str = ""):
|
|
|
|
|
"""Proxy tenant weather requests to data service"""
|
|
|
|
|
target_path = f"/api/v1/tenants/{tenant_id}/weather/{path}".rstrip("/")
|
|
|
|
|
return await _proxy_to_data_service(request, target_path)
|
|
|
|
|
|
2025-07-27 22:58:18 +02:00
|
|
|
@router.api_route("/{tenant_id}/traffic/{path:path}", methods=["GET", "POST", "OPTIONS"])
|
|
|
|
|
async def proxy_tenant_traffic(request: Request, tenant_id: str = Path(...), path: str = ""):
|
|
|
|
|
"""Proxy tenant traffic requests to data service"""
|
|
|
|
|
target_path = f"/api/v1/tenants/{tenant_id}/traffic/{path}".rstrip("/")
|
|
|
|
|
return await _proxy_to_data_service(request, target_path)
|
|
|
|
|
|
2025-07-26 18:46:52 +02:00
|
|
|
@router.api_route("/{tenant_id}/analytics/{path:path}", methods=["GET", "POST", "OPTIONS"])
|
|
|
|
|
async def proxy_tenant_analytics(request: Request, tenant_id: str = Path(...), path: str = ""):
|
|
|
|
|
"""Proxy tenant analytics requests to data service"""
|
|
|
|
|
target_path = f"/api/v1/tenants/{tenant_id}/analytics/{path}".rstrip("/")
|
|
|
|
|
return await _proxy_to_data_service(request, target_path)
|
|
|
|
|
|
|
|
|
|
# ================================================================
|
|
|
|
|
# TENANT-SCOPED TRAINING SERVICE ENDPOINTS
|
|
|
|
|
# ================================================================
|
|
|
|
|
|
|
|
|
|
@router.api_route("/{tenant_id}/training/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
|
|
|
|
|
async def proxy_tenant_training(request: Request, tenant_id: str = Path(...), path: str = ""):
|
|
|
|
|
"""Proxy tenant training requests to training service"""
|
|
|
|
|
target_path = f"/api/v1/tenants/{tenant_id}/training/{path}".rstrip("/")
|
|
|
|
|
return await _proxy_to_training_service(request, target_path)
|
|
|
|
|
|
|
|
|
|
@router.api_route("/{tenant_id}/models/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
|
|
|
|
|
async def proxy_tenant_models(request: Request, tenant_id: str = Path(...), path: str = ""):
|
|
|
|
|
"""Proxy tenant model requests to training service"""
|
|
|
|
|
target_path = f"/api/v1/tenants/{tenant_id}/models/{path}".rstrip("/")
|
|
|
|
|
return await _proxy_to_training_service(request, target_path)
|
|
|
|
|
|
|
|
|
|
# ================================================================
|
|
|
|
|
# TENANT-SCOPED FORECASTING SERVICE ENDPOINTS
|
|
|
|
|
# ================================================================
|
|
|
|
|
|
|
|
|
|
@router.api_route("/{tenant_id}/forecasts/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
|
|
|
|
|
async def proxy_tenant_forecasts(request: Request, tenant_id: str = Path(...), path: str = ""):
|
|
|
|
|
"""Proxy tenant forecast requests to forecasting service"""
|
|
|
|
|
target_path = f"/api/v1/tenants/{tenant_id}/forecasts/{path}".rstrip("/")
|
|
|
|
|
return await _proxy_to_forecasting_service(request, target_path)
|
|
|
|
|
|
|
|
|
|
@router.api_route("/{tenant_id}/predictions/{path:path}", methods=["GET", "POST", "OPTIONS"])
|
|
|
|
|
async def proxy_tenant_predictions(request: Request, tenant_id: str = Path(...), path: str = ""):
|
|
|
|
|
"""Proxy tenant prediction requests to forecasting service"""
|
|
|
|
|
target_path = f"/api/v1/tenants/{tenant_id}/predictions/{path}".rstrip("/")
|
|
|
|
|
return await _proxy_to_forecasting_service(request, target_path)
|
|
|
|
|
|
|
|
|
|
# ================================================================
|
|
|
|
|
# TENANT-SCOPED NOTIFICATION SERVICE ENDPOINTS
|
|
|
|
|
# ================================================================
|
|
|
|
|
|
|
|
|
|
@router.api_route("/{tenant_id}/notifications/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
|
|
|
|
|
async def proxy_tenant_notifications(request: Request, tenant_id: str = Path(...), path: str = ""):
|
|
|
|
|
"""Proxy tenant notification requests to notification service"""
|
|
|
|
|
target_path = f"/api/v1/tenants/{tenant_id}/notifications/{path}".rstrip("/")
|
|
|
|
|
return await _proxy_to_notification_service(request, target_path)
|
2025-07-20 23:43:42 +02:00
|
|
|
|
2025-07-26 18:46:52 +02:00
|
|
|
# ================================================================
|
|
|
|
|
# PROXY HELPER FUNCTIONS
|
|
|
|
|
# ================================================================
|
|
|
|
|
|
|
|
|
|
async def _proxy_to_tenant_service(request: Request, target_path: str):
|
|
|
|
|
"""Proxy request to tenant service"""
|
|
|
|
|
return await _proxy_request(request, target_path, settings.TENANT_SERVICE_URL)
|
|
|
|
|
|
|
|
|
|
async def _proxy_to_data_service(request: Request, target_path: str):
|
|
|
|
|
"""Proxy request to data service"""
|
|
|
|
|
return await _proxy_request(request, target_path, settings.DATA_SERVICE_URL)
|
|
|
|
|
|
|
|
|
|
async def _proxy_to_training_service(request: Request, target_path: str):
|
|
|
|
|
"""Proxy request to training service"""
|
|
|
|
|
return await _proxy_request(request, target_path, settings.TRAINING_SERVICE_URL)
|
|
|
|
|
|
|
|
|
|
async def _proxy_to_forecasting_service(request: Request, target_path: str):
|
|
|
|
|
"""Proxy request to forecasting service"""
|
|
|
|
|
return await _proxy_request(request, target_path, settings.FORECASTING_SERVICE_URL)
|
|
|
|
|
|
|
|
|
|
async def _proxy_to_notification_service(request: Request, target_path: str):
|
|
|
|
|
"""Proxy request to notification service"""
|
|
|
|
|
return await _proxy_request(request, target_path, settings.NOTIFICATION_SERVICE_URL)
|
|
|
|
|
|
|
|
|
|
async def _proxy_request(request: Request, target_path: str, service_url: str):
|
|
|
|
|
"""Generic proxy function with enhanced error handling"""
|
|
|
|
|
|
|
|
|
|
# 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"
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
2025-07-20 23:43:42 +02:00
|
|
|
try:
|
2025-07-26 18:46:52 +02:00
|
|
|
url = f"{service_url}{target_path}"
|
2025-07-20 23:43:42 +02:00
|
|
|
|
2025-07-26 18:46:52 +02:00
|
|
|
# Forward headers and add user/tenant context
|
2025-07-20 23:43:42 +02:00
|
|
|
headers = dict(request.headers)
|
|
|
|
|
headers.pop("host", None)
|
|
|
|
|
|
|
|
|
|
# Get request body if present
|
|
|
|
|
body = None
|
2025-07-26 18:46:52 +02:00
|
|
|
if request.method in ["POST", "PUT", "PATCH"]:
|
2025-07-20 23:43:42 +02:00
|
|
|
body = await request.body()
|
|
|
|
|
|
2025-07-26 18:46:52 +02:00
|
|
|
# Add query parameters
|
|
|
|
|
params = dict(request.query_params)
|
|
|
|
|
|
2025-07-20 23:43:42 +02:00
|
|
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
|
|
|
|
response = await client.request(
|
2025-07-26 18:46:52 +02:00
|
|
|
method=request.method,
|
2025-07-20 23:43:42 +02:00
|
|
|
url=url,
|
|
|
|
|
headers=headers,
|
|
|
|
|
content=body,
|
2025-07-26 18:46:52 +02:00
|
|
|
params=params
|
2025-07-17 19:46:41 +02:00
|
|
|
)
|
|
|
|
|
|
2025-07-26 18:46:52 +02:00
|
|
|
# Handle different response types
|
|
|
|
|
if response.headers.get("content-type", "").startswith("application/json"):
|
|
|
|
|
try:
|
|
|
|
|
content = response.json()
|
|
|
|
|
except:
|
|
|
|
|
content = {"message": "Invalid JSON response from service"}
|
|
|
|
|
else:
|
|
|
|
|
content = response.text
|
|
|
|
|
|
2025-07-17 19:46:41 +02:00
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=response.status_code,
|
2025-07-26 18:46:52 +02:00
|
|
|
content=content
|
2025-07-17 19:46:41 +02:00
|
|
|
)
|
|
|
|
|
|
2025-07-26 18:46:52 +02:00
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Unexpected error proxying to {service_url}{target_path}: {e}")
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=500,
|
|
|
|
|
detail="Internal gateway error"
|
2025-07-17 19:46:41 +02:00
|
|
|
)
|