Improve auth models

This commit is contained in:
Urtzi Alfaro
2025-07-19 21:16:25 +02:00
parent abc8b68ab4
commit c7fd6135f0
9 changed files with 382 additions and 120 deletions

View File

@@ -1,4 +1,6 @@
# services/training/app/main.py
# ================================================================
# services/training/app/main.py - FIXED VERSION
# ================================================================
"""
Training Service Main Application
Enhanced with proper error handling, monitoring, and lifecycle management
@@ -19,7 +21,7 @@ from app.api import training, models
from app.services.messaging import setup_messaging, cleanup_messaging
from shared.monitoring.logging import setup_logging
from shared.monitoring.metrics import MetricsCollector
from shared.auth.decorators import require_auth
# REMOVED: from shared.auth.decorators import require_auth
# Setup structured logging
setup_logging("training-service", settings.LOG_LEVEL)
@@ -52,6 +54,9 @@ async def lifespan(app: FastAPI):
metrics_collector.start_metrics_server(8080)
logger.info("Metrics server started on port 8080")
# Store metrics collector in app state
app.state.metrics_collector = metrics_collector
# Mark service as ready
app.state.ready = True
logger.info("Training Service startup completed successfully")
@@ -67,74 +72,57 @@ async def lifespan(app: FastAPI):
logger.info("Shutting down Training Service")
try:
# Stop metrics server
if hasattr(app.state, 'metrics_collector'):
await app.state.metrics_collector.shutdown()
# Cleanup messaging
logger.info("Cleaning up messaging")
await cleanup_messaging()
logger.info("Messaging cleanup completed")
# Close database connections
logger.info("Closing database connections")
await database_manager.close_connections()
logger.info("Training Service shutdown completed")
logger.info("Database connections closed")
except Exception as e:
logger.error("Error during shutdown", error=str(e))
logger.info("Training Service shutdown completed")
# Create FastAPI app with lifespan
# Create FastAPI application with lifespan
app = FastAPI(
title="Training Service",
description="ML model training service for bakery demand forecasting",
title="Bakery Training Service",
description="ML training service for bakery demand forecasting",
version="1.0.0",
docs_url="/docs" if settings.DEBUG else None,
redoc_url="/redoc" if settings.DEBUG else None,
docs_url="/docs",
redoc_url="/redoc",
lifespan=lifespan
)
# Initialize app state
app.state.ready = False
# Security middleware
if not settings.DEBUG:
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=["localhost", "127.0.0.1", "training-service", "*.bakery-forecast.local"]
)
# CORS middleware
# Add middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"] if settings.DEBUG else [
"http://localhost:3000",
"http://localhost:8000",
"https://dashboard.bakery-forecast.es"
],
allow_origins=settings.CORS_ORIGINS_LIST,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_methods=["*"],
allow_headers=["*"],
)
# Request logging middleware
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=settings.ALLOWED_HOSTS
)
# Request middleware for logging and metrics
@app.middleware("http")
async def log_requests(request: Request, call_next):
"""Log all incoming requests with timing"""
async def process_request(request: Request, call_next):
"""Process requests with logging and metrics"""
start_time = asyncio.get_event_loop().time()
# Log request
logger.info(
"Request started",
method=request.method,
path=request.url.path,
client_ip=request.client.host if request.client else "unknown"
)
# Process request
try:
response = await call_next(request)
# Calculate duration
duration = asyncio.get_event_loop().time() - start_time
# Log response
logger.info(
"Request completed",
method=request.method,
@@ -189,19 +177,18 @@ async def global_exception_handler(request: Request, exc: Exception):
}
)
# Include API routers
# Include API routers - NO AUTH DEPENDENCIES HERE
# Authentication is handled by API Gateway
app.include_router(
training.router,
prefix="/training",
tags=["training"],
dependencies=[require_auth] if not settings.DEBUG else []
tags=["training"]
)
app.include_router(
models.router,
prefix="/models",
tags=["models"],
dependencies=[require_auth] if not settings.DEBUG else []
prefix="/models",
tags=["models"]
)
# Health check endpoints
@@ -217,66 +204,32 @@ async def health_check():
@app.get("/health/ready")
async def readiness_check():
"""Kubernetes readiness probe"""
if not app.state.ready:
"""Kubernetes readiness probe endpoint"""
checks = {
"database": await get_db_health(),
"application": getattr(app.state, 'ready', False)
}
if all(checks.values()):
return {"status": "ready", "checks": checks}
else:
return JSONResponse(
status_code=503,
content={"status": "not_ready", "message": "Service is starting up"}
content={"status": "not ready", "checks": checks}
)
return {"status": "ready", "service": "training-service"}
@app.get("/health/live")
async def liveness_check():
"""Kubernetes liveness probe"""
# Check database connectivity
try:
db_healthy = await get_db_health()
if not db_healthy:
return JSONResponse(
status_code=503,
content={"status": "unhealthy", "reason": "database_unavailable"}
)
except Exception as e:
logger.error("Database health check failed", error=str(e))
return JSONResponse(
status_code=503,
content={"status": "unhealthy", "reason": "database_error"}
)
return {"status": "alive", "service": "training-service"}
@app.get("/metrics")
async def get_metrics():
"""Expose service metrics"""
return {
"training_jobs_active": metrics_collector.get_gauge("training_jobs_active", 0),
"training_jobs_completed": metrics_collector.get_counter("training_jobs_completed", 0),
"training_jobs_failed": metrics_collector.get_counter("training_jobs_failed", 0),
"models_trained_total": metrics_collector.get_counter("models_trained_total", 0),
"uptime_seconds": metrics_collector.get_gauge("uptime_seconds", 0)
}
"""Prometheus metrics endpoint"""
if hasattr(app.state, 'metrics_collector'):
return app.state.metrics_collector.get_metrics()
return {"status": "metrics not available"}
@app.get("/")
async def root():
"""Root endpoint with service information"""
return {
"service": "training-service",
"version": "1.0.0",
"description": "ML model training service for bakery demand forecasting",
"docs": "/docs" if settings.DEBUG else "Documentation disabled in production",
"health": "/health"
}
# Development server configuration
if __name__ == "__main__":
uvicorn.run(
"app.main:app",
host="0.0.0.0",
port=8000,
port=settings.PORT,
reload=settings.DEBUG,
log_level=settings.LOG_LEVEL.lower(),
access_log=settings.DEBUG,
server_header=False,
date_header=False
log_level=settings.LOG_LEVEL.lower()
)