Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /InferiaAI_InferiaLLM /src /api_gateway /app.py
| """ | |
| API Gateway Service Application Entry Point. | |
| This is the main entry point for the API Gateway that includes: | |
| - API Gateway functionality (routing, proxying) | |
| - RBAC & Authentication | |
| - Rate Limiting | |
| - Request routing to downstream services (Orchestration, etc.) | |
| """ | |
| from fastapi import FastAPI | |
| from contextlib import asynccontextmanager | |
| from common.exception_handlers import register_exception_handlers | |
| from common.logger import setup_logging | |
| from common.app_setup import setup_cors, add_standard_health_routes | |
| from api_gateway.config import httpx_verify, settings | |
| from api_gateway.gateway.middleware import ( | |
| RequestIDMiddleware, | |
| StandardHeadersMiddleware, | |
| ProcessingTimeMiddleware, | |
| ) | |
| from api_gateway.gateway.internal_middleware import ( | |
| internal_api_key_middleware, | |
| ) | |
| from api_gateway.rbac.middleware import auth_middleware | |
| from api_gateway.rbac.router import router as auth_router | |
| from api_gateway.rbac.oauth_router import router as oauth_router | |
| from api_gateway.gateway.router import router as gateway_router | |
| from api_gateway.management.router import router as management_router | |
| from api_gateway.rbac.roles_router import router as roles_router | |
| from api_gateway.rbac.users_router import router as users_router | |
| from api_gateway.audit.router import router as audit_router | |
| from api_gateway.gateway.proxy_routes import ( | |
| router as proxy_router, | |
| worker_passthrough_router, | |
| ) | |
| from api_gateway.gateway.health_routes import router as health_router | |
| # Configure logging | |
| logger = setup_logging( | |
| level=settings.log_level, | |
| service_name="api-gateway", | |
| use_json=not settings.is_development, | |
| log_file="debug.log", | |
| logger_name="services.api_gateway", | |
| ) | |
| async def _maybe_declare_catalog() -> None: | |
| """Best-effort catalog declaration to InferiaAuth on startup. | |
| Runs only when auth_provider=="inferiaauth", external_auth_url, and | |
| catalog_admin_token are all set. Any failure is logged and swallowed — | |
| a catalog declare failure must never crash boot. | |
| """ | |
| if ( | |
| settings.auth_provider == "inferiaauth" | |
| and settings.external_auth_url | |
| and settings.catalog_admin_token | |
| ): | |
| from api_gateway.rbac.catalog_declare import declare_catalog | |
| ok = await declare_catalog( | |
| settings.external_auth_url, | |
| settings.catalog_admin_token, | |
| service_id=settings.external_service_id, | |
| verify=httpx_verify(settings), | |
| ) | |
| if ok: | |
| logger.info("Declared InferiaLLM catalog to InferiaAuth") | |
| else: | |
| logger.warning( | |
| "Catalog declare to InferiaAuth failed (non-fatal; will retry next boot)" | |
| ) | |
| async def lifespan(app: FastAPI): | |
| """Lifespan context manager for startup and shutdown events.""" | |
| # Startup | |
| logger.info(f"Starting {settings.app_name} v{settings.app_version}") | |
| logger.info(f"Environment: {settings.environment}") | |
| logger.info( | |
| f"Rate limiting: {'enabled' if settings.rate_limit_enabled else 'disabled'}" | |
| ) | |
| # Initialize Default Org & Superadmin | |
| from api_gateway.db.database import AsyncSessionLocal | |
| from api_gateway.rbac.initialization import initialize_default_org | |
| async with AsyncSessionLocal() as session: | |
| await initialize_default_org(session) | |
| # Start Config Polling | |
| from api_gateway.management.config_manager import config_manager | |
| await config_manager.initialize() | |
| config_manager.start_polling() | |
| if settings.is_external_mode and settings.external_auth_url: | |
| logger.info(f"External auth enabled via: {settings.external_auth_url}") | |
| # Declare catalog to InferiaAuth (best-effort, never raises) | |
| await _maybe_declare_catalog() | |
| yield | |
| # Shutdown | |
| logger.info(f"Shutting down {settings.app_name}") | |
| config_manager.stop_polling() | |
| from api_gateway.gateway.http_client import gateway_http_client | |
| from api_gateway.gateway.rate_limiter import rate_limiter | |
| await gateway_http_client.close_all() | |
| await rate_limiter.close() | |
| if settings.is_external_mode: | |
| from api_gateway.rbac.external_auth import close_client | |
| await close_client() | |
| # Create FastAPI app | |
| app = FastAPI( | |
| title=settings.app_name, | |
| version=settings.app_version, | |
| description="API Gateway Service", | |
| lifespan=lifespan, | |
| docs_url="/docs", | |
| redoc_url="/redoc", | |
| ) | |
| # Register standard exception handlers | |
| register_exception_handlers(app) | |
| # ==================== CORS Configuration ==================== | |
| setup_cors(app, settings.allowed_origins, settings.is_development) | |
| # ==================== Custom Middleware ==================== | |
| # Add custom middleware in order (last added = first executed) | |
| app.add_middleware(ProcessingTimeMiddleware) | |
| app.add_middleware(StandardHeadersMiddleware) | |
| app.add_middleware(RequestIDMiddleware) | |
| # Add internal API key validation for /internal/* endpoints | |
| app.middleware("http")(internal_api_key_middleware) | |
| # Add RBAC auth middleware | |
| app.middleware("http")(auth_middleware) | |
| # ==================== Exception Handlers ==================== | |
| # Using standardized handlers from common.exception_handlers | |
| # ==================== Routes ==================== | |
| # Add standard / and /health routes | |
| add_standard_health_routes( | |
| app=app, | |
| app_name=settings.app_name, | |
| app_version=settings.app_version, | |
| environment=settings.environment, | |
| extra_components={ | |
| "rbac": "healthy", | |
| "rate_limiter": "healthy", | |
| } | |
| ) | |
| # Include routers | |
| app.include_router(auth_router) | |
| app.include_router(oauth_router) | |
| app.include_router(audit_router) | |
| app.include_router(management_router) | |
| app.include_router(gateway_router) | |
| app.include_router(roles_router) | |
| app.include_router(users_router) | |
| app.include_router(proxy_router) | |
| app.include_router(worker_passthrough_router) | |
| app.include_router(health_router) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn_kwargs = dict( | |
| host=settings.host, | |
| port=settings.port, | |
| reload=settings.reload, | |
| workers=settings.workers, | |
| log_level=settings.log_level.lower(), | |
| proxy_headers=settings.proxy_headers, | |
| ) | |
| if settings.forwarded_allow_ips is not None: | |
| uvicorn_kwargs["forwarded_allow_ips"] = settings.forwarded_allow_ips | |
| uvicorn.run("app:app", **uvicorn_kwargs) | |
Xet Storage Details
- Size:
- 6.34 kB
- Xet hash:
- d8a58e9b774777df9ece989c42d5f7617f8a6e174f15a4416b00aa20c510cbb2
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.