/ api-gateway / main.py
main.py
1 from fastapi import FastAPI 2 from fastapi.middleware.cors import CORSMiddleware 3 import logging 4 from app.migrations import run_migrations 5 from app.routes import docs, gcs 6 7 # Configure logging 8 logging.basicConfig(level=logging.INFO) 9 logger = logging.getLogger(__name__) 10 11 app = FastAPI(title="SME Ops-Center API Gateway", version="0.1.0") 12 13 # CORS middleware for frontend access 14 app.add_middleware( 15 CORSMiddleware, 16 allow_origins=["http://localhost:8501"], # Streamlit frontend 17 allow_credentials=True, 18 allow_methods=["*"], 19 allow_headers=["*"], 20 ) 21 22 # Include routers 23 app.include_router(docs.router) 24 app.include_router(gcs.router) 25 26 27 @app.on_event("startup") 28 async def startup_event(): 29 """Run database migrations and ensure directories exist on startup.""" 30 logger.info("API Gateway starting up...") 31 32 # Ensure uploads and sessions directories exist and are writable 33 from pathlib import Path 34 uploads_dir = Path("/app/uploads") 35 sessions_dir = Path("/app/sessions") 36 uploads_dir.mkdir(parents=True, exist_ok=True) 37 sessions_dir.mkdir(parents=True, exist_ok=True) 38 logger.info(f"Ensured uploads directory exists: {uploads_dir}") 39 40 try: 41 run_migrations() 42 except Exception as e: 43 logger.error(f"Startup migration failed: {e}") 44 # Don't fail startup if migrations fail - let it be handled separately 45 # In production, you might want to fail fast here 46 47 48 @app.get("/health") 49 async def health(): 50 """Health check endpoint with database connectivity check.""" 51 from app.health import check_database_health 52 53 db_healthy = await check_database_health() 54 status = "ok" if db_healthy else "degraded" 55 56 return { 57 "status": status, 58 "service": "api-gateway", 59 "database": "connected" if db_healthy else "disconnected" 60 } 61 62 63 @app.get("/") 64 async def root(): 65 """Root endpoint.""" 66 return {"message": "SME Ops-Center API Gateway", "version": "0.1.0"}