Fix shared issues
This commit is contained in:
@@ -1,9 +1,5 @@
|
||||
# ================================================================
|
||||
# services/auth/app/main.py (ENHANCED VERSION)
|
||||
# ================================================================
|
||||
"""
|
||||
Authentication Service Main Application
|
||||
Enhanced version with proper lifecycle management and microservices integration
|
||||
Authentication Service Main Application - Fixed middleware issue
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -16,58 +12,108 @@ from app.core.config import settings
|
||||
from app.core.database import engine, create_tables
|
||||
from app.api import auth, users
|
||||
from app.services.messaging import setup_messaging, cleanup_messaging
|
||||
from shared.monitoring.logging import setup_logging
|
||||
from shared.monitoring.metrics import MetricsCollector
|
||||
from shared.monitoring import setup_logging, HealthChecker
|
||||
from shared.monitoring.metrics import setup_metrics_early
|
||||
|
||||
# Setup logging
|
||||
# Setup logging first
|
||||
setup_logging("auth-service", settings.LOG_LEVEL)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Initialize metrics
|
||||
metrics = MetricsCollector("auth_service")
|
||||
# Global variables for lifespan access
|
||||
metrics_collector = None
|
||||
health_checker = None
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Application lifespan events"""
|
||||
# Startup
|
||||
logger.info("Starting Authentication Service...")
|
||||
|
||||
# Create database tables
|
||||
await create_tables()
|
||||
logger.info("Database tables created")
|
||||
|
||||
# Setup messaging
|
||||
await setup_messaging()
|
||||
logger.info("Messaging setup complete")
|
||||
|
||||
# Register metrics
|
||||
metrics.register_counter("auth_requests_total", "Total authentication requests")
|
||||
metrics.register_counter("auth_login_success_total", "Successful logins")
|
||||
metrics.register_counter("auth_login_failure_total", "Failed logins")
|
||||
metrics.register_counter("auth_registration_total", "User registrations")
|
||||
metrics.register_histogram("auth_request_duration_seconds", "Request duration")
|
||||
|
||||
logger.info("Authentication Service started successfully")
|
||||
|
||||
yield
|
||||
|
||||
# Shutdown
|
||||
logger.info("Shutting down Authentication Service...")
|
||||
await cleanup_messaging()
|
||||
await engine.dispose()
|
||||
logger.info("Authentication Service shutdown complete")
|
||||
|
||||
# Create FastAPI app
|
||||
# Create FastAPI app FIRST
|
||||
app = FastAPI(
|
||||
title="Authentication Service",
|
||||
description="Handles user authentication and authorization for bakery forecasting platform",
|
||||
version="1.0.0",
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
lifespan=lifespan
|
||||
redoc_url="/redoc"
|
||||
)
|
||||
|
||||
# CORS middleware
|
||||
# Setup metrics BEFORE any middleware and BEFORE lifespan
|
||||
# This must happen before the app starts
|
||||
metrics_collector = setup_metrics_early(app, "auth-service")
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Application lifespan events - NO MIDDLEWARE ADDED HERE"""
|
||||
global health_checker
|
||||
|
||||
# Startup
|
||||
logger.info("Starting Authentication Service...")
|
||||
|
||||
try:
|
||||
# Create database tables
|
||||
await create_tables()
|
||||
logger.info("Database tables created")
|
||||
|
||||
# Setup messaging
|
||||
await setup_messaging()
|
||||
logger.info("Messaging setup complete")
|
||||
|
||||
# Register custom metrics (metrics_collector already exists)
|
||||
metrics_collector.register_counter("registration_total", "Total user registrations")
|
||||
metrics_collector.register_counter("login_success_total", "Successful logins")
|
||||
metrics_collector.register_counter("login_failure_total", "Failed logins")
|
||||
metrics_collector.register_counter("token_refresh_total", "Token refresh requests")
|
||||
metrics_collector.register_counter("token_verify_total", "Token verification requests")
|
||||
metrics_collector.register_counter("logout_total", "User logout requests")
|
||||
metrics_collector.register_counter("errors_total", "Total errors")
|
||||
metrics_collector.register_histogram("registration_duration_seconds", "Registration request duration")
|
||||
metrics_collector.register_histogram("login_duration_seconds", "Login request duration")
|
||||
metrics_collector.register_histogram("token_refresh_duration_seconds", "Token refresh duration")
|
||||
|
||||
# Setup health checker
|
||||
health_checker = HealthChecker("auth-service")
|
||||
|
||||
# Add database health check
|
||||
async def check_database():
|
||||
try:
|
||||
from app.core.database import get_db
|
||||
async for db in get_db():
|
||||
await db.execute("SELECT 1")
|
||||
return True
|
||||
except Exception as e:
|
||||
return f"Database error: {e}"
|
||||
|
||||
health_checker.add_check("database", check_database, timeout=5.0, critical=True)
|
||||
|
||||
# Add messaging health check
|
||||
def check_messaging():
|
||||
try:
|
||||
# Add your messaging health check logic here
|
||||
return True
|
||||
except Exception as e:
|
||||
return f"Messaging error: {e}"
|
||||
|
||||
health_checker.add_check("messaging", check_messaging, timeout=3.0, critical=False)
|
||||
|
||||
# Store health checker in app state
|
||||
app.state.health_checker = health_checker
|
||||
|
||||
logger.info("Authentication Service started successfully")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to start Authentication Service: {e}")
|
||||
raise
|
||||
|
||||
yield
|
||||
|
||||
# Shutdown
|
||||
logger.info("Shutting down Authentication Service...")
|
||||
try:
|
||||
await cleanup_messaging()
|
||||
await engine.dispose()
|
||||
logger.info("Authentication Service shutdown complete")
|
||||
except Exception as e:
|
||||
logger.error(f"Error during shutdown: {e}")
|
||||
|
||||
# Set lifespan AFTER metrics setup
|
||||
app.router.lifespan_context = lifespan
|
||||
|
||||
# CORS middleware (added after metrics setup)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"], # Configure properly for production
|
||||
@@ -80,44 +126,30 @@ app.add_middleware(
|
||||
app.include_router(auth.router, prefix="/api/v1/auth", tags=["authentication"])
|
||||
app.include_router(users.router, prefix="/api/v1/users", tags=["users"])
|
||||
|
||||
# Health check endpoint
|
||||
# Health check endpoint with comprehensive checks
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
"""Health check endpoint"""
|
||||
return {
|
||||
"service": "auth-service",
|
||||
"status": "healthy",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
|
||||
# Metrics endpoint
|
||||
@app.get("/metrics")
|
||||
async def get_metrics():
|
||||
"""Prometheus metrics endpoint"""
|
||||
return metrics.get_metrics()
|
||||
"""Comprehensive health check endpoint"""
|
||||
if health_checker:
|
||||
return await health_checker.check_health()
|
||||
else:
|
||||
return {
|
||||
"service": "auth-service",
|
||||
"status": "healthy",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
|
||||
# Exception handlers
|
||||
@app.exception_handler(Exception)
|
||||
async def global_exception_handler(request: Request, exc: Exception):
|
||||
"""Global exception handler"""
|
||||
"""Global exception handler with metrics"""
|
||||
logger.error(f"Unhandled exception: {exc}", exc_info=True)
|
||||
|
||||
# Record error metric if available
|
||||
if metrics_collector:
|
||||
metrics_collector.increment_counter("errors_total", labels={"type": "unhandled"})
|
||||
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={"detail": "Internal server error"}
|
||||
)
|
||||
|
||||
# Request middleware for metrics
|
||||
@app.middleware("http")
|
||||
async def metrics_middleware(request: Request, call_next):
|
||||
"""Middleware to collect metrics"""
|
||||
import time
|
||||
start_time = time.time()
|
||||
|
||||
response = await call_next(request)
|
||||
|
||||
# Record metrics
|
||||
duration = time.time() - start_time
|
||||
metrics.observe_histogram("auth_request_duration_seconds", duration)
|
||||
metrics.increment_counter("auth_requests_total")
|
||||
|
||||
return response
|
||||
)
|
||||
Reference in New Issue
Block a user