File size: 3,889 Bytes
ef58e1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)