Spaces:
Paused

File size: 7,619 Bytes
1282961
 
5eb4857
 
 
97655dc
5eb4857
b7980f7
5eb4857
 
 
 
accf280
94b1a89
17bb84f
5eb4857
 
 
b7980f7
 
 
5eb4857
 
17bb84f
b23c114
17bb84f
 
b7980f7
91ebb5b
b7980f7
91ebb5b
b7980f7
 
 
 
 
5eb4857
 
17bb84f
 
b7980f7
 
 
 
 
5eb4857
 
 
 
 
 
 
 
91ebb5b
5eb4857
 
f3a0c24
 
 
 
 
f3a5b2f
 
f3a0c24
 
 
 
 
 
 
 
f3a5b2f
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
accf280
 
 
 
b7980f7
 
 
1282961
91ebb5b
 
 
2dfe0ae
 
 
 
 
91ebb5b
 
 
 
 
 
 
 
 
 
4640159
91ebb5b
 
 
 
 
7645bba
 
91ebb5b
7645bba
 
 
 
 
2c17177
5eb4857
 
 
 
b7980f7
 
5eb4857
 
b7980f7
5eb4857
 
 
b7980f7
5eb4857
 
 
 
 
 
 
 
 
 
 
b7980f7
1266347
2dfe0ae
5df0bfe
 
 
 
4640159
5df0bfe
 
 
 
 
4640159
 
 
 
 
 
 
 
5eb4857
f3a5b2f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
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
from models import Workspace  # Triggers models/__init__.py for Base.metadata registration

# Initialize global logging
setup_logging()
import uvicorn
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
logger = get_logger(__name__)

settings = get_settings()

from arq import create_pool
from arq.connections import RedisSettings

@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
)

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.router, prefix=f"{settings.API_V1_STR}/kb", tags=["Knowledge Base"])
app.include_router(kb_insights.router, prefix=f"{settings.API_V1_STR}/kb/insights", tags=["Knowledge Base Insights"]) # New Router
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(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/")