import sys import asyncio # WINDOWS STABILITY LOCK: Psycopg3 requires SelectorEventLoop on Windows if sys.platform == 'win32': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from fastapi.middleware.cors import CORSMiddleware from core.config import get_settings from core.database import engine, run_migrations from core.logging import setup_logging, get_logger from contextlib import asynccontextmanager from core.observability import setup_telemetry # Initialize global logging setup_logging() from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware logger = get_logger(__name__) settings = get_settings() from arq import create_pool @asynccontextmanager async def lifespan(app: FastAPI): # Startup diagnostics logger.info("Starting Nexus Gateway (Beta 1.0) - Deployment: 2026-04-01-Sync") logger.info(f"Target Database Host: {settings.database_host}") # Initialize ARQ Pool Singleton (Optimized for Cloud) from core.config import get_redis_settings app.state.arq_pool = await create_pool( get_redis_settings(), default_queue_name='arq:queue' ) logger.info("GLOBAL: Redis Pool (ARQ) initialized successfully.") # Startup: ensure migrations are run await run_migrations() yield # Shutdown logger.info("Shutting down Nexus Gateway") if hasattr(app.state, "arq_pool"): await app.state.arq_pool.close() # Cleanup token blocklist Redis connection from core.token_blocklist import close_blocklist_redis await close_blocklist_redis() await engine.dispose() app = FastAPI( title=settings.APP_NAME, version=settings.APP_VERSION, lifespan=lifespan, docs_url="/docs", redoc_url="/redoc", strict_slashes=False, # Disable strict slashes to prevent redirect-based CORS failures ) from fastapi import Depends from core.deps import get_db, get_arq_pool from core.observability import check_infra_health from sqlalchemy.ext.asyncio import AsyncSession @app.get("/health", tags=["System"]) @app.get("/health/", tags=["System"]) async def health_check( db: AsyncSession = Depends(get_db), arq_pool = Depends(get_arq_pool) ): health = await check_infra_health(db, arq_pool) if health["status"] != "healthy": return JSONResponse(status_code=503, content=health) return health # --- OPENTELEMETRY TRACING --- setup_telemetry(app) # --- GLOBAL ROBUSTNESS: UNHANDLED EXCEPTION HANDLER --- @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): import traceback # Log the full traceback internally error_trace = traceback.format_exc() logger.error(f"UNHANDLED EXCEPTION: {request.method} {request.url.path}\n{error_trace}") # Return structured but obfuscated JSON for security return JSONResponse( status_code=500, content={ "detail": "An internal server error occurred. Our engineers have been notified.", "type": type(exc).__name__, "path": str(request.url.path) } ) # --- PROXY HANDLING (SSL TERMINATION) --- # Ensure redirects use HTTPS when behind a proxy app.add_middleware(ProxyHeadersMiddleware, trusted_hosts=["*"]) # --- RATE LIMITING ON AUTH ENDPOINTS --- from core.rate_limiter import RateLimiterMiddleware app.add_middleware(RateLimiterMiddleware) # --- SLEDGEHAMMER CORS: FORCE HEADERS ON ALL RESPONSES --- @app.middleware("http") async def force_cors_middleware(request: Request, call_next): # Skip CORS logic for WebSockets (they have their own handshake mechanisms) if "upgrade" in request.headers.get("connection", "").lower() and \ request.headers.get("upgrade", "").lower() == "websocket": return await call_next(request) origin = request.headers.get("origin") if request.method == "OPTIONS": response = JSONResponse(content="OK") else: response = await call_next(request) if origin: response.headers["Access-Control-Allow-Origin"] = origin response.headers["Access-Control-Allow-Credentials"] = "true" response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS, PATCH" response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, X-Requested-With, Accept, X-Nexus-Portal" response.headers["Access-Control-Expose-Headers"] = "*" return response # Standard CORS as fallback app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Router Registration from api.v1 import ( auth, users, tickets, messages, websockets, dashboard, projects, ai, kb, kb_insights, attachments, feedback, notifications, workspace, escalations, reports, nexus, system, nexus_stream, worker ) app.include_router(projects.projects_router, prefix=f"{settings.API_V1_STR}/projects", tags=["projects"]) app.include_router(auth.router, prefix=f"{settings.API_V1_STR}/auth", tags=["auth"]) app.include_router(users.router, prefix=f"{settings.API_V1_STR}/users", tags=["users"]) app.include_router(kb_insights.router, prefix=f"{settings.API_V1_STR}/kb/insights", tags=["Knowledge Base Insights"]) # New Router app.include_router(kb.router, prefix=f"{settings.API_V1_STR}/kb", tags=["Knowledge Base"]) app.include_router(tickets.router, prefix=f"{settings.API_V1_STR}/tickets", tags=["tickets"]) app.include_router(messages.router, prefix=f"{settings.API_V1_STR}/tickets", tags=["messages"]) app.include_router(dashboard.router, prefix=f"{settings.API_V1_STR}/dashboard", tags=["dashboard"]) app.include_router(ai.router, prefix=f"{settings.API_V1_STR}/ai", tags=["AI Intelligence"]) app.include_router(attachments.router, prefix=f"{settings.API_V1_STR}/tickets", tags=["attachments"]) app.include_router(feedback.router, prefix=f"{settings.API_V1_STR}/tickets", tags=["feedback"]) app.include_router(notifications.router, prefix=f"{settings.API_V1_STR}/notifications", tags=["notifications"]) app.include_router(workspace.router, prefix=f"{settings.API_V1_STR}/workspace", tags=["workspace"]) app.include_router(escalations.router, prefix=f"{settings.API_V1_STR}/escalations", tags=["escalation"]) app.include_router(reports.router, prefix=f"{settings.API_V1_STR}/reports", tags=["reports"]) app.include_router(nexus.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"]) app.include_router(nexus_stream.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"]) app.include_router(system.router, prefix=f"{settings.API_V1_STR}/system", tags=["System Infrastructure"]) app.include_router(worker.router, prefix=f"{settings.API_V1_STR}/worker", tags=["Worker Monitoring"]) app.include_router(websockets.router, tags=["websockets"]) # Included at root to match frontend /ws/ logic import os from fastapi.staticfiles import StaticFiles # --- UNIFIED PORTAL HOSTING --- # Serve Customer Portal at /customer and Internal Portal at /internal BASE_DIR = os.path.dirname(os.path.abspath(__file__)) FRONTEND_CUSTOMER_PATH = os.path.join(BASE_DIR, "frontend/apps/customer/dist") FRONTEND_INTERNAL_PATH = os.path.join(BASE_DIR, "frontend/apps/internal/dist") # Note: Mounting Internal BEFORE Customer to avoid catch-all collisions app.mount("/internal", StaticFiles(directory=FRONTEND_INTERNAL_PATH, html=True), name="internal") app.mount("/customer", StaticFiles(directory=FRONTEND_CUSTOMER_PATH, html=True), name="customer") # Root redirect for convenience from fastapi.responses import RedirectResponse @app.get("/") async def root_redirect(): return RedirectResponse(url="/customer/")