Refactor all main.py

This commit is contained in:
Urtzi Alfaro
2025-09-29 13:13:12 +02:00
parent 4777e59e7a
commit befcc126b0
35 changed files with 2537 additions and 1993 deletions

View File

@@ -6,130 +6,108 @@ Production Service - FastAPI Application
Production planning and batch management service
"""
import time
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import structlog
from app.core.config import settings
from app.core.database import init_database, get_db_health
from app.core.database import database_manager
from app.api.production import router as production_router
from app.services.production_alert_service import ProductionAlertService
# Configure logging
logger = structlog.get_logger()
from shared.service_base import StandardFastAPIService
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Manage application lifespan events"""
# Startup
try:
await init_database()
logger.info("Database initialized")
class ProductionService(StandardFastAPIService):
"""Production Service with standardized setup"""
def __init__(self):
# Define expected database tables for health checks
production_expected_tables = [
'production_batches', 'production_schedules', 'production_capacity',
'quality_check_templates', 'quality_checks', 'equipment'
]
self.alert_service = None
# Create custom checks for alert service
async def check_alert_service():
"""Check production alert service health"""
try:
return bool(self.alert_service) if self.alert_service else False
except Exception as e:
self.logger.error("Alert service health check failed", error=str(e))
return False
super().__init__(
service_name=settings.SERVICE_NAME,
app_name=settings.APP_NAME,
description=settings.DESCRIPTION,
version=settings.VERSION,
api_prefix="/api/v1",
database_manager=database_manager,
expected_tables=production_expected_tables,
custom_health_checks={"alert_service": check_alert_service}
)
async def on_startup(self, app: FastAPI):
"""Custom startup logic for production service"""
# Initialize alert service
alert_service = ProductionAlertService(settings)
await alert_service.start()
logger.info("Production alert service started")
self.alert_service = ProductionAlertService(settings)
await self.alert_service.start()
self.logger.info("Production alert service started")
# Store alert service in app state
app.state.alert_service = alert_service
logger.info("Production service started successfully")
except Exception as e:
logger.error("Failed to initialize production service", error=str(e))
raise
yield
# Shutdown
logger.info("Production service shutting down")
try:
app.state.alert_service = self.alert_service
async def on_shutdown(self, app: FastAPI):
"""Custom shutdown logic for production service"""
# Stop alert service
if hasattr(app.state, 'alert_service'):
await app.state.alert_service.stop()
logger.info("Alert service stopped")
except Exception as e:
logger.error("Error during shutdown", error=str(e))
if self.alert_service:
await self.alert_service.stop()
self.logger.info("Alert service stopped")
def get_service_features(self):
"""Return production-specific features"""
return [
"production_planning",
"batch_management",
"production_scheduling",
"quality_control",
"equipment_management",
"capacity_planning",
"alert_notifications"
]
def setup_custom_middleware(self):
"""Setup custom middleware for production service"""
@self.app.middleware("http")
async def logging_middleware(request: Request, call_next):
"""Add request logging middleware"""
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
self.logger.info("HTTP request processed",
method=request.method,
url=str(request.url),
status_code=response.status_code,
process_time=round(process_time, 4))
return response
# Create FastAPI application
app = FastAPI(
title=settings.APP_NAME,
description=settings.DESCRIPTION,
version=settings.VERSION,
lifespan=lifespan
)
# Create service instance
service = ProductionService()
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Configure based on environment
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Create FastAPI app with standardized setup
app = service.create_app()
# Setup standard endpoints
service.setup_standard_endpoints()
# Setup custom middleware
service.setup_custom_middleware()
# Include routers
app.include_router(production_router, prefix="/api/v1")
@app.get("/health")
async def health_check():
"""Health check endpoint"""
try:
db_healthy = await get_db_health()
health_status = {
"status": "healthy" if db_healthy else "unhealthy",
"service": settings.SERVICE_NAME,
"version": settings.VERSION,
"database": "connected" if db_healthy else "disconnected"
}
if not db_healthy:
health_status["status"] = "unhealthy"
return health_status
except Exception as e:
logger.error("Health check failed", error=str(e))
return {
"status": "unhealthy",
"service": settings.SERVICE_NAME,
"version": settings.VERSION,
"error": str(e)
}
@app.get("/")
async def root():
"""Root endpoint"""
return {
"service": settings.APP_NAME,
"version": settings.VERSION,
"description": settings.DESCRIPTION,
"status": "running"
}
@app.middleware("http")
async def logging_middleware(request: Request, call_next):
"""Add request logging middleware"""
import time
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
logger.info("HTTP request processed",
method=request.method,
url=str(request.url),
status_code=response.status_code,
process_time=round(process_time, 4))
return response
service.add_router(production_router)
if __name__ == "__main__":