Files
bakery-ia/services/demo_session/app/main.py

122 lines
2.8 KiB
Python
Raw Normal View History

2025-10-03 14:09:34 +02:00
"""
Demo Session Service - Main Application
Manages isolated demo sessions with ephemeral data
"""
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import structlog
from contextlib import asynccontextmanager
from app.core import settings, DatabaseManager
2025-11-30 09:12:40 +01:00
from app.api import demo_sessions, demo_accounts, demo_operations, internal
from shared.redis_utils import initialize_redis, close_redis
2025-10-03 14:09:34 +02:00
logger = structlog.get_logger()
# Initialize database
2025-10-03 14:09:34 +02:00
db_manager = DatabaseManager()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan handler"""
logger.info("Starting Demo Session Service", version=settings.VERSION)
# Initialize database
db_manager.initialize()
# Initialize Redis using shared implementation
await initialize_redis(
redis_url=settings.REDIS_URL,
db=0,
max_connections=50
)
2025-10-03 14:09:34 +02:00
logger.info("Demo Session Service started successfully")
yield
# Cleanup on shutdown
await db_manager.close()
await close_redis()
2025-10-03 14:09:34 +02:00
logger.info("Demo Session Service stopped")
app = FastAPI(
title="Demo Session Service",
description="Manages isolated demo sessions for prospect users",
version=settings.VERSION,
lifespan=lifespan
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
"""Global exception handler"""
logger.error(
"Unhandled exception",
path=request.url.path,
method=request.method,
error=str(exc)
)
return JSONResponse(
status_code=500,
content={"detail": "Internal server error"}
)
# Include routers
2025-10-06 15:27:01 +02:00
app.include_router(demo_sessions.router)
app.include_router(demo_accounts.router)
app.include_router(demo_operations.router)
2025-11-30 09:12:40 +01:00
app.include_router(internal.router)
2025-10-03 14:09:34 +02:00
@app.get("/")
async def root():
"""Root endpoint"""
return {
"service": "demo-session",
"version": settings.VERSION,
"status": "running"
}
@app.get("/health")
async def health():
"""Health check endpoint"""
from shared.redis_utils import get_redis_manager
redis_manager = await get_redis_manager()
redis_ok = await redis_manager.health_check()
2025-10-03 14:09:34 +02:00
return {
"status": "healthy" if redis_ok else "degraded",
"service": "demo-session",
"version": settings.VERSION,
"redis": "connected" if redis_ok else "disconnected"
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"app.main:app",
host="0.0.0.0",
port=8000,
reload=settings.DEBUG,
log_level=settings.LOG_LEVEL.lower()
)