import sys import asyncio import uuid # 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 fastapi.middleware.gzip import GZipMiddleware from starlette.middleware.base import BaseHTTPMiddleware from starlette.types import ASGIApp, Receive, Scope, Send 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 import markdown from markdown.extensions.codehilite import CodeHiliteExtension from markdown.extensions.fenced_code import FencedCodeExtension 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:regular' ) logger.info("GLOBAL: Redis Pool (ARQ) initialized successfully.") # 3. Database migrations are now handled in the run_prod.sh bootstrap # to prevent race conditions in multi-worker environments. # await run_migrations() # 4. Pre-compile Master Agent Graph (Prevents first-query latency spikes) from agents.nexus_master import get_nexus_app logger.info("🏗️ [Lifespan] Pre-compiling Master Agent Graph...") await get_nexus_app(is_agent=True) await get_nexus_app(is_agent=False) # 5. Start WebSocket Redis pub/sub subscriber. # Uses the LOCAL Redis (localhost:6379) — NOT the cloud/Upstash instance. # Reason: pub/sub requires a persistent long-lived TCP connection. Cloud # providers like Upstash impose 30-second idle timeouts and bill per command, # making them unsuitable for always-on pub/sub. The local Redis (started by # run_prod.sh before this process) has no such limits and costs nothing. # All 4 Gunicorn workers share the same host, so localhost fan-out works # correctly. If you ever move to multiple physical servers, point # LOCAL_REDIS_URL at a shared Redis that all servers can reach. from core.websockets import manager as ws_manager _ws_redis_url = settings.LOCAL_REDIS_URL await ws_manager.start_pubsub(_ws_redis_url) logger.info("GLOBAL: WebSocket Redis pub/sub subscriber started.") yield # Shutdown logger.info("Shutting down Nexus Gateway") await ws_manager.stop_pubsub() 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="/api/docs", redoc_url="/api/redoc", openapi_url="/api/openapi.json", strict_slashes=False, ) 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.", "trace_id": str(uuid.uuid4())[:8], "path": str(request.url.path) } ) # --- PROXY HANDLING (SSL TERMINATION) --- # Ensure redirects use HTTPS when behind a proxy. # trusted_hosts restricts which upstream IPs can set X-Forwarded-For. # Private RFC-1918 ranges cover Docker/K8s ingress controllers and common PaaS proxies. # Add your specific load-balancer IPs via TRUSTED_PROXY_IPS env var if needed. import os as _os _trusted = _os.environ.get("TRUSTED_PROXY_IPS", "127.0.0.1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16") _trusted_list = [h.strip() for h in _trusted.split(",") if h.strip()] app.add_middleware(ProxyHeadersMiddleware, trusted_hosts=_trusted_list) # --- RATE LIMITING: Moved to route-level dependencies in auth.py --- # --- SECURITY HARDENING: SECURITY HEADERS (Raw ASGI) --- class SecurityHeadersMiddleware: def __init__(self, app: ASGIApp): self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send): if scope["type"] not in ("http", "websocket"): await self.app(scope, receive, send) return path = scope.get("path", "") # Unified check for all documentation and API reference paths (Swagger, Redoc, etc.) is_docs_path = any(p in path for p in ["/docs", "/redoc", "/openapi"]) async def send_with_headers(message): if message["type"] == "http.response.start": headers = dict() for k, v in message.get("headers", []): headers[k.lower()] = v headers[b"x-content-type-options"] = b"nosniff" headers[b"x-frame-options"] = b"SAMEORIGIN" headers[b"x-xss-protection"] = b"1; mode=block" headers[b"strict-transport-security"] = b"max-age=31536000; includeSubDomains" headers[b"referrer-policy"] = b"strict-origin-when-cross-origin" if is_docs_path: # Swagger UI requires unsafe-inline; scope to docs paths only headers[b"content-security-policy"] = ( b"default-src 'self'; " b"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net blob:; " b"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; " b"img-src 'self' data: https:; " b"font-src 'self' data: https://cdn.jsdelivr.net https://fonts.googleapis.com https://fonts.gstatic.com; " b"connect-src 'self' https: wss:; " b"worker-src 'self' blob:; " b"frame-ancestors 'self' https://*.huggingface.co https://huggingface.co;" ) else: headers[b"content-security-policy"] = ( b"default-src 'self'; " b"script-src 'self' https://cdn.jsdelivr.net; " b"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; " b"img-src 'self' data: https:; " b"font-src 'self' data: https://cdn.jsdelivr.net https://fonts.googleapis.com https://fonts.gstatic.com; " b"connect-src 'self' https: wss:; " b"frame-ancestors 'self' https://*.huggingface.co https://huggingface.co;" ) message["headers"] = [(k, v) for k, v in headers.items()] await send(message) await self.app(scope, receive, send_with_headers) app.add_middleware(SecurityHeadersMiddleware) # --- CORS CONFIGURATION --- # Auto-detect HF Space origin so deployments without ALLOWED_ORIGINS set still work _cors_origins = list(settings.ALLOWED_ORIGINS) _hf_space_id = _os.environ.get("SPACE_ID") if _hf_space_id: _user, _name = (_hf_space_id.split("/") + [""])[:2] _hf_origin = f"https://{_user}-{_name.replace('_', '-')}.hf.space" if _hf_origin not in _cors_origins: _cors_origins.append(_hf_origin) app.add_middleware( CORSMiddleware, allow_origins=_cors_origins, allow_credentials=True, allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"], allow_headers=["Content-Type", "Authorization", "X-Requested-With", "Accept", "X-Nexus-Portal"], ) # --- SECURITY HARDENING: RESPONSE COMPRESSION --- app.add_middleware(GZipMiddleware, minimum_size=1000) # 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 from fastapi.templating import Jinja2Templates # --- 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") # Ensure static directory exists to prevent mount errors STATIC_PATH = os.path.join(BASE_DIR, "static") if not os.path.exists(STATIC_PATH): os.makedirs(STATIC_PATH, exist_ok=True) # Initialize Templates for the Landing Page templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates")) # Note: Mounting Internal BEFORE Customer to avoid catch-all collisions app.mount("/static", StaticFiles(directory=STATIC_PATH), name="static") 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 Landing Page: Replacing redirect with Visionary Hub @app.get("/") async def root_landing(request: Request): return templates.TemplateResponse("landing.html", {"request": request}) # --- DOCUMENTATION HOSTING --- DOCS_DIR = os.path.join(BASE_DIR, "docs") def get_docs_list(): docs = [] if not os.path.exists(DOCS_DIR): return docs for root, dirs, files in os.walk(DOCS_DIR): # Skip archive directory if 'archive' in dirs: dirs.remove('archive') for f in files: if f.endswith(".md") and f.lower() != "readme.md": rel_path = os.path.relpath(os.path.join(root, f), DOCS_DIR) doc_id = rel_path.replace("\\", "/").replace(".md", "") # Title formatting: handle nested names name = os.path.basename(doc_id) title = name.replace("_", " ").title() # Add category prefix if in subdirectory category = os.path.dirname(doc_id) if category: title = f"{category.replace('_', ' ').title()}: {title}" docs.append({"id": doc_id, "title": title}) return sorted(docs, key=lambda x: x["title"]) @app.get("/docs") @app.get("/docs/") async def list_docs(request: Request): docs = get_docs_list() if not docs: return templates.TemplateResponse("docs.html", {"request": request, "title": "No Docs", "content": "

No documentation found.

", "docs": [], "current_doc": None}) # Redirect to first doc or show index first_doc = docs[0]["id"] return await show_doc(request, first_doc) @app.get("/docs/{doc_id:path}") async def show_doc(request: Request, doc_id: str): docs = get_docs_list() file_path = os.path.join(DOCS_DIR, f"{doc_id}.md") if not os.path.exists(file_path): return templates.TemplateResponse("docs.html", { "request": request, "title": "404 Not Found", "content": "

Document Not Found

The requested documentation page does not exist.

", "docs": docs, "current_doc": doc_id }) with open(file_path, "r", encoding="utf-8") as f: md_content = f.read() html_content = markdown.markdown( md_content, extensions=[ 'fenced_code', 'codehilite', 'tables', 'toc' ] ) title = doc_id.replace("_", " ").title() return templates.TemplateResponse("docs.html", { "request": request, "title": title, "content": html_content, "docs": docs, "current_doc": doc_id })