File size: 9,097 Bytes
3acb982
 
 
 
dc6eb4c
 
 
3acb982
dc6eb4c
3acb982
 
b32fbe0
dc6eb4c
b32fbe0
3acb982
 
 
0699b16
dc6eb4c
3acb982
 
 
 
 
0699b16
3acb982
 
 
 
dc6eb4c
 
 
 
3acb982
dc6eb4c
 
3acb982
dc6eb4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9795dbe
dc6eb4c
 
 
 
 
 
9795dbe
dc6eb4c
 
 
 
 
 
 
 
 
 
 
 
 
 
9795dbe
 
 
 
 
 
 
 
 
dc6eb4c
 
 
 
 
 
 
 
 
3acb982
 
dc6eb4c
 
 
 
 
 
 
 
 
3acb982
 
 
dc6eb4c
d33881a
 
 
3acb982
 
dc6eb4c
3acb982
 
 
b04deac
 
 
 
 
 
 
 
 
 
 
3acb982
 
b04deac
dc6eb4c
3acb982
dc6eb4c
3acb982
 
dc6eb4c
3acb982
 
dc6eb4c
 
 
3acb982
 
 
 
 
9795dbe
 
3acb982
 
dc6eb4c
 
aa5ac5f
3acb982
 
 
 
 
 
 
 
 
 
dc6eb4c
3acb982
0699b16
dc6eb4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3acb982
 
 
 
 
 
 
 
dc6eb4c
 
3acb982
 
 
dc6eb4c
 
 
3acb982
 
 
 
 
 
 
dc6eb4c
3acb982
 
 
 
 
 
dc6eb4c
3acb982
 
dc6eb4c
3acb982
 
 
 
9795dbe
 
 
 
 
3acb982
 
9795dbe
 
b32fbe0
 
3acb982
 
 
 
dc6eb4c
b32fbe0
9795dbe
 
 
a734ef7
9795dbe
 
 
 
 
 
 
 
 
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""
Knowledge Universe API - Main FastAPI Application
"""
import asyncio
import json
import logging
import os
from contextlib import asynccontextmanager

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, FileResponse
from fastapi.exceptions import RequestValidationError
from fastapi.staticfiles import StaticFiles
from prometheus_client import make_asgi_app

from config.settings import get_settings
from src.api.routes import router as block2_router
from src.api.models import SourceFormat
from src.api.middleware import RateLimitMiddleware, MetricsMiddleware
from src.cache.redis_manager import RedisManager
from src.cache.eviction_manager import EvictionManager
from src.orchestration.background_tasks import BackgroundTaskManager


settings = get_settings()
logger = logging.getLogger(__name__)


# ------------------------------------------------------------------
# πŸ”’ REQUEST SANITIZATION MIDDLEWARE (CRITICAL FIX)
# ------------------------------------------------------------------
class RequestSanitizerMiddleware:
    """
    Sanitizes incoming JSON before Pydantic validation.
    Fixes enum pollution (formats causing 422).
    """

    def __init__(self, app: FastAPI):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        request = Request(scope, receive=receive)

        if request.method == "POST" and request.url.path.endswith("/discover"):
            try:
                body = await request.json()

                # Sanitize formats β€” strip invalid enum values with a warning
                if "formats" in body and isinstance(body["formats"], list):
                    cleaned = []
                    for f in body["formats"]:
                        try:
                            cleaned.append(SourceFormat(f))
                        except Exception:
                            logger.warning(f"Dropped invalid format value: '{f}'")
                    body["formats"] = cleaned

                # Re-inject sanitized body
                async def receive_override():
                    return {
                        "type": "http.request",
                        "body": json.dumps(body).encode(),
                        "more_body": False,
                    }

                await self.app(scope, receive_override, send)
                return

            except Exception as e:
                # ── BUG 6 FIX ──────────────────────────────────────────────
                # GET requests have no body. Trying request.json() on them
                # always raises "Expecting value: line 1 column 1 (char 0)".
                # This is normal β€” not an error. Log at DEBUG not ERROR.
                # Only log as WARNING if this is genuinely a POST with bad JSON.
                if request.method == "POST":
                    logger.warning(f"Malformed JSON on POST {request.url.path}: {e}")
                else:
                    logger.debug(f"Sanitizer skipped non-POST: {e}")

        await self.app(scope, receive, send)


# ------------------------------------------------------------------
# LIFESPAN
# ------------------------------------------------------------------
@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info("Starting Knowledge Universe API...")
    
    # βœ… ADD THIS DIAGNOSTIC
    logger.info("=" * 60)
    logger.info("ENVIRONMENT DIAGNOSTIC")
    logger.info(f"GITHUB_TOKEN: {'SET βœ“' if os.getenv('GITHUB_TOKEN') else 'MISSING βœ—'}")
    logger.info(f"KAGGLE_USERNAME: {'SET βœ“' if os.getenv('KAGGLE_USERNAME') else 'MISSING βœ—'}")
    logger.info(f"KAGGLE_KEY: {'SET βœ“' if os.getenv('KAGGLE_KEY') else 'MISSING βœ—'}")
    logger.info("=" * 60)

    # ... rest of code
    redis_manager = RedisManager()
    await redis_manager.connect()
    app.state.redis = redis_manager

    from src.utils.key_rotator import init_key_rotators
    init_key_rotators(redis_manager)

    eviction_manager = EvictionManager(redis_manager)
    app.state.eviction_manager = eviction_manager

    background_tasks = BackgroundTaskManager(redis_manager)
    cleanup_task = asyncio.create_task(background_tasks.start_cleanup_daemon())
    app.state.cleanup_task = cleanup_task
    # Pre-warm the embedding model so the first real request doesn't pay
    # the initialization cost (~500-800ms on HuggingFace Spaces).
    # This runs synchronously in the lifespan β€” model is guaranteed ready
    # before any request reaches the /v1/discover handler.
    try:
        from src.integrations.shared_model import prewarm_model
        logger.info("Pre-warming embedding model...")
        prewarm_model()
    except Exception as e:
        logger.warning(f"Model pre-warm failed (non-fatal): {e}")
 
    if settings.WARMUP_ENABLED:
        asyncio.create_task(background_tasks.warmup_cache())
 
    logger.info("API ready")
    yield

    cleanup_task.cancel()
    await redis_manager.close()
    logger.info("Shutdown complete")


# ------------------------------------------------------------------
# APP
# ------------------------------------------------------------------
app = FastAPI(
    title=settings.API_TITLE,
    version=settings.API_VERSION,
    description="Intelligent content aggregation and ranking for educational materials",
    lifespan=lifespan,
    docs_url="/api-docs",    # moved β€” /docs serves our human-readable docs page
    redoc_url="/api-redoc",
)

# πŸ”’ ORDER MATTERS
app.add_middleware(RequestSanitizerMiddleware)
app.add_middleware(RateLimitMiddleware)
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

if settings.ENABLE_METRICS:
    app.add_middleware(MetricsMiddleware)
    app.mount("/metrics", make_asgi_app())

app.include_router(block2_router)
# ------------------------------------------------------------------
# 🧯 VALIDATION ERROR HANDLER (422)
# ------------------------------------------------------------------
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    logger.warning(f"422 Validation error on {request.url}: {exc.errors()}")
    return JSONResponse(
        status_code=422,
        content={
            "error": "Validation error",
            "details": exc.errors(),
            "body": exc.body,
        },
    )


# ------------------------------------------------------------------
# GLOBAL ERROR HANDLER
# ------------------------------------------------------------------
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(f"Unhandled exception: {exc}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={
            "error": "Internal server error",
            "message": str(exc) if settings.DEBUG else "An error occurred",
            "path": str(request.url),
        },
    )


# ------------------------------------------------------------------
# HEALTH
# ------------------------------------------------------------------
@app.get("/health")
async def health_check(request: Request):
    redis_manager = request.app.state.redis
    redis_healthy = await redis_manager.ping()
    return {
        "status": "healthy" if redis_healthy else "degraded",
        "version": settings.API_VERSION,
        "redis": "connected" if redis_healthy else "disconnected",
    }


@app.get("/ready")
async def readiness_check(request: Request):
    redis_manager = request.app.state.redis
    if not await redis_manager.ping():
        return JSONResponse(
            status_code=503,
            content={"status": "not ready", "reason": "redis unavailable"},
        )
    return {"status": "ready"}


# Project root = two levels up from src/api/main.py
_PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
_LANDING_DIR  = os.path.join(_PROJECT_ROOT, "landing")


@app.get("/")
async def root():
    """Serve landing page."""
    landing = os.path.join(_LANDING_DIR, "index.html")
    if os.path.exists(landing):
        return FileResponse(landing, media_type="text/html")
    return {
        "name": settings.API_TITLE,
        "version": settings.API_VERSION,
        "status": "operational",
        "docs": "/docs",
        "signup": "/v1/signup",
    }


@app.get("/docs.html", include_in_schema=False)
async def serve_docs():
    """Serve the human-readable API documentation page."""
    docs_path = os.path.join(_LANDING_DIR, "docs.html")
    if os.path.exists(docs_path):
        return FileResponse(docs_path, media_type="text/html")
    return JSONResponse(
        status_code=404,
        content={"error": "docs.html not found in landing/. Check the file exists."},
    )