import logging from contextlib import asynccontextmanager from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote_address from slowapi.errors import RateLimitExceeded from app.config import settings from app.db.database import engine, Base from app.api.v1.router import api_router from app.scheduler.cron import start_scheduler, stop_scheduler # Configure Logging logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) # Initialize Rate Limiter (Protection against API token depletion and DDoS) limiter = Limiter(key_func=get_remote_address, default_limits=["60 per minute"]) @asynccontextmanager async def lifespan(app: FastAPI): # Startup: Initialize Database Tables logger.info("Initializing database schema...") Base.metadata.create_all(bind=engine) # Startup: Start APScheduler Cron Job (Twice Daily) start_scheduler() yield # Shutdown: Stop Scheduler stop_scheduler() app = FastAPI( title=settings.APP_NAME, version=settings.VERSION, description="Enterprise API for BytePulse AI Daily Tech Digest powered by 8 Scrapers, Gemini 2.5 Flash, ChromaDB, and FCM.", lifespan=lifespan ) # Attach Rate Limiter to app state app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) # App Secret Authentication Middleware (Only accept requests from Mobile App, block all external bots) @app.middleware("http") async def app_secret_security_middleware(request: Request, call_next): path = request.url.path # Allow docs, open API spec, root and health checks without secret header if path in ["/", "/health", "/docs", "/openapi.json", "/redoc"]: return await call_next(request) # Inspect X-App-Secret header for all /api/v1 endpoints app_secret = request.headers.get("X-App-Secret") if app_secret != settings.API_SECRET_KEY: logger.warning(f"Blocked unauthorized API request to {path} from IP {request.client.host}") return JSONResponse( status_code=403, content={ "status": "forbidden", "message": "Access Denied: Invalid or missing X-App-Secret key. Only authorized BytePulse AI clients are allowed." } ) return await call_next(request) # Global Error Handler for unhandled server exceptions @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): logger.error(f"Global Error caught on {request.url.path}: {exc}", exc_info=True) return JSONResponse( status_code=500, content={ "status": "error", "message": "An internal server error occurred. Our engineers have been notified.", "path": request.url.path } ) # Enable CORS Security Middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["GET", "POST", "OPTIONS"], allow_headers=["*"], ) # Root & Health Endpoints @app.get("/") @limiter.limit("30/minute") def root(request: Request): return { "message": f"Welcome to {settings.APP_NAME}", "version": settings.VERSION, "docs": "/docs", "api_v1": "/api/v1" } @app.get("/health") @limiter.limit("60/minute") def health_check(request: Request): return {"status": "healthy", "service": settings.APP_NAME, "security": "rate_limited_enabled"} # Include API v1 Router app.include_router(api_router, prefix="/api/v1") if __name__ == "__main__": import uvicorn uvicorn.run("main:app", host=settings.HOST, port=settings.PORT, reload=settings.DEBUG)