# gateway/app/routes/inventory.py """ Inventory routes for API Gateway - Handles inventory management endpoints """ from fastapi import APIRouter, Request, Response, HTTPException, Path from fastapi.responses import JSONResponse import httpx import logging from typing import Optional from app.core.config import settings logger = logging.getLogger(__name__) router = APIRouter() # Inventory service URL - add to settings INVENTORY_SERVICE_URL = "http://inventory-service:8000" # ================================================================ # TENANT-SCOPED INVENTORY ENDPOINTS # ================================================================ @router.api_route("/{tenant_id}/inventory/ingredients{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"]) async def proxy_tenant_ingredients(request: Request, tenant_id: str = Path(...), path: str = ""): """Proxy tenant ingredient requests to inventory service""" base_path = f"/api/v1/ingredients" # 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 return await _proxy_to_inventory_service(request, target_path) @router.api_route("/{tenant_id}/inventory/stock{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"]) async def proxy_tenant_stock(request: Request, tenant_id: str = Path(...), path: str = ""): """Proxy tenant stock requests to inventory service""" base_path = f"/api/v1/stock" # 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 return await _proxy_to_inventory_service(request, target_path) @router.api_route("/{tenant_id}/inventory/alerts{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"]) async def proxy_tenant_alerts(request: Request, tenant_id: str = Path(...), path: str = ""): """Proxy tenant inventory alert requests to inventory service""" base_path = f"/api/v1/alerts" # 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 return await _proxy_to_inventory_service(request, target_path) @router.api_route("/{tenant_id}/inventory/dashboard{path:path}", methods=["GET", "OPTIONS"]) async def proxy_tenant_inventory_dashboard(request: Request, tenant_id: str = Path(...), path: str = ""): """Proxy tenant inventory dashboard requests to inventory service""" base_path = f"/api/v1/dashboard" # 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 return await _proxy_to_inventory_service(request, target_path) # ================================================================ # DIRECT INVENTORY ENDPOINTS (for backward compatibility) # ================================================================ @router.api_route("/ingredients{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"]) async def proxy_ingredients(request: Request, path: str = ""): """Proxy ingredient requests to inventory service""" base_path = f"/api/v1/ingredients" if not path or path == "/" or path == "": target_path = base_path else: if not path.startswith("/"): path = "/" + path target_path = base_path + path return await _proxy_to_inventory_service(request, target_path) @router.api_route("/stock{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"]) async def proxy_stock(request: Request, path: str = ""): """Proxy stock requests to inventory service""" base_path = f"/api/v1/stock" if not path or path == "/" or path == "": target_path = base_path else: if not path.startswith("/"): path = "/" + path target_path = base_path + path return await _proxy_to_inventory_service(request, target_path) @router.api_route("/alerts{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"]) async def proxy_alerts(request: Request, path: str = ""): """Proxy inventory alert requests to inventory service""" base_path = f"/api/v1/alerts" if not path or path == "/" or path == "": target_path = base_path else: if not path.startswith("/"): path = "/" + path target_path = base_path + path return await _proxy_to_inventory_service(request, target_path) # ================================================================ # PROXY HELPER FUNCTION # ================================================================ async def _proxy_to_inventory_service(request: Request, target_path: str): """Proxy request to inventory service with enhanced error handling""" # Handle OPTIONS requests directly for CORS if request.method == "OPTIONS": return Response( status_code=200, headers={ "Access-Control-Allow-Origin": "*", "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" } ) try: url = f"{INVENTORY_SERVICE_URL}{target_path}" # Forward headers and add user/tenant context headers = dict(request.headers) headers.pop("host", None) # Get request body if present body = None if request.method in ["POST", "PUT", "PATCH"]: body = await request.body() # Add query parameters params = dict(request.query_params) timeout_config = httpx.Timeout( connect=30.0, # Connection timeout read=600.0, # Read timeout: 10 minutes write=30.0, # Write timeout pool=30.0 # Pool timeout ) async with httpx.AsyncClient(timeout=timeout_config) as client: response = await client.request( method=request.method, url=url, headers=headers, content=body, params=params ) # Handle different response types if response.headers.get("content-type", "").startswith("application/json"): try: content = response.json() except: content = {"message": "Invalid JSON response from inventory service"} else: content = response.text return JSONResponse( status_code=response.status_code, content=content ) except httpx.ConnectTimeout: logger.error(f"Connection timeout to inventory service: {INVENTORY_SERVICE_URL}{target_path}") raise HTTPException( status_code=503, detail="Inventory service temporarily unavailable" ) except httpx.ReadTimeout: logger.error(f"Read timeout from inventory service: {INVENTORY_SERVICE_URL}{target_path}") raise HTTPException( status_code=504, detail="Inventory service response timeout" ) except Exception as e: logger.error(f"Unexpected error proxying to inventory service {INVENTORY_SERVICE_URL}{target_path}: {e}") raise HTTPException( status_code=500, detail="Internal gateway error" )