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

204 lines
8.2 KiB
Python
Raw Normal View History

2025-07-21 19:48:56 +02:00
# ================================================================
# services/forecasting/app/main.py
# ================================================================
"""
2025-07-21 19:48:56 +02:00
Forecasting Service Main Application
Demand prediction and forecasting service for bakery operations
"""
2025-09-29 13:13:12 +02:00
from fastapi import FastAPI
2025-09-30 08:12:45 +02:00
from sqlalchemy import text
from app.core.config import settings
2025-09-29 13:13:12 +02:00
from app.core.database import database_manager
from app.services.forecasting_alert_service import ForecastingAlertService
2025-09-29 13:13:12 +02:00
from shared.service_base import StandardFastAPIService
2025-10-06 15:27:01 +02:00
# Import API routers
2025-11-30 09:12:40 +01:00
from app.api import forecasts, forecasting_operations, analytics, scenario_operations, internal_demo, audit, ml_insights, validation, historical_validation, webhooks, performance_monitoring, retraining, enterprise_forecasting
2025-10-06 15:27:01 +02:00
2025-09-29 13:13:12 +02:00
class ForecastingService(StandardFastAPIService):
"""Forecasting Service with standardized setup"""
2025-11-18 07:17:17 +01:00
expected_migration_version = "00003"
2025-09-30 08:12:45 +02:00
async def on_startup(self, app):
"""Custom startup logic including migration verification"""
await self.verify_migrations()
await super().on_startup(app)
async def verify_migrations(self):
"""Verify database schema matches the latest migrations."""
try:
async with self.database_manager.get_session() as session:
result = await session.execute(text("SELECT version_num FROM alembic_version"))
version = result.scalar()
if version != self.expected_migration_version:
self.logger.error(f"Migration version mismatch: expected {self.expected_migration_version}, got {version}")
raise RuntimeError(f"Migration version mismatch: expected {self.expected_migration_version}, got {version}")
self.logger.info(f"Migration verification successful: {version}")
except Exception as e:
self.logger.error(f"Migration verification failed: {e}")
raise
2025-09-29 13:13:12 +02:00
def __init__(self):
# Define expected database tables for health checks
forecasting_expected_tables = [
2025-11-18 07:17:17 +01:00
'forecasts', 'prediction_batches', 'model_performance_metrics', 'prediction_cache', 'validation_runs', 'sales_data_updates'
2025-09-29 13:13:12 +02:00
]
self.alert_service = None
2025-12-05 20:07:01 +01:00
self.rabbitmq_client = None
self.event_publisher = None
2025-09-29 13:13:12 +02:00
# Create custom checks for alert service
async def alert_service_check():
"""Custom health check for forecasting alert service"""
return await self.alert_service.health_check() if self.alert_service else False
# Define custom metrics for forecasting service
forecasting_custom_metrics = {
"forecasts_generated_total": {
"type": "counter",
"description": "Total forecasts generated"
},
"predictions_served_total": {
"type": "counter",
"description": "Total predictions served"
},
"prediction_errors_total": {
"type": "counter",
"description": "Total prediction errors"
},
"forecast_processing_time_seconds": {
"type": "histogram",
"description": "Time to process forecast request"
},
"prediction_processing_time_seconds": {
"type": "histogram",
"description": "Time to process prediction request"
},
"model_cache_hits_total": {
"type": "counter",
"description": "Total model cache hits"
},
"model_cache_misses_total": {
"type": "counter",
"description": "Total model cache misses"
}
}
super().__init__(
service_name="forecasting-service",
app_name="Bakery Forecasting Service",
description="AI-powered demand prediction and forecasting service for bakery operations",
version="1.0.0",
log_level=settings.LOG_LEVEL,
cors_origins=settings.CORS_ORIGINS_LIST,
2025-10-06 15:27:01 +02:00
api_prefix="", # Empty because RouteBuilder already includes /api/v1
2025-09-29 13:13:12 +02:00
database_manager=database_manager,
expected_tables=forecasting_expected_tables,
custom_health_checks={"alert_service": alert_service_check},
enable_messaging=True,
custom_metrics=forecasting_custom_metrics
)
async def _setup_messaging(self):
2025-12-05 20:07:01 +01:00
"""Setup messaging for forecasting service using unified messaging"""
from shared.messaging import UnifiedEventPublisher, RabbitMQClient
try:
self.rabbitmq_client = RabbitMQClient(settings.RABBITMQ_URL, service_name="forecasting-service")
await self.rabbitmq_client.connect()
# Create unified event publisher
self.event_publisher = UnifiedEventPublisher(self.rabbitmq_client, "forecasting-service")
self.logger.info("Forecasting service unified messaging setup completed")
except Exception as e:
self.logger.error("Failed to setup forecasting unified messaging", error=str(e))
raise
2025-09-29 13:13:12 +02:00
async def _cleanup_messaging(self):
"""Cleanup messaging for forecasting service"""
2025-12-05 20:07:01 +01:00
try:
if self.rabbitmq_client:
await self.rabbitmq_client.disconnect()
self.logger.info("Forecasting service messaging cleanup completed")
except Exception as e:
self.logger.error("Error during forecasting messaging cleanup", error=str(e))
2025-09-29 13:13:12 +02:00
async def on_startup(self, app: FastAPI):
"""Custom startup logic for forecasting service"""
2025-12-05 20:07:01 +01:00
await super().on_startup(app)
# Initialize forecasting alert service with EventPublisher
if self.event_publisher:
self.alert_service = ForecastingAlertService(self.event_publisher)
await self.alert_service.start()
self.logger.info("Forecasting alert service initialized")
else:
self.logger.error("Event publisher not initialized, alert service unavailable")
2025-09-29 13:13:12 +02:00
async def on_shutdown(self, app: FastAPI):
"""Custom shutdown logic for forecasting service"""
# Cleanup alert service
if self.alert_service:
await self.alert_service.stop()
self.logger.info("Alert service cleanup completed")
def get_service_features(self):
"""Return forecasting-specific features"""
return [
"demand_prediction",
"ai_forecasting",
"model_performance_tracking",
"prediction_caching",
"alert_notifications",
"messaging_integration"
]
def setup_custom_endpoints(self):
"""Setup custom endpoints for forecasting service"""
@self.app.get("/alert-metrics")
async def get_alert_metrics():
"""Alert service metrics endpoint"""
if self.alert_service:
return self.alert_service.get_metrics()
return {"error": "Alert service not initialized"}
# Create service instance
service = ForecastingService()
# Create FastAPI app with standardized setup
app = service.create_app(
2025-07-21 19:48:56 +02:00
docs_url="/docs",
2025-09-29 13:13:12 +02:00
redoc_url="/redoc"
2025-07-21 19:48:56 +02:00
)
2025-09-29 13:13:12 +02:00
# Setup standard endpoints
service.setup_standard_endpoints()
# Setup custom endpoints
service.setup_custom_endpoints()
2025-07-21 19:48:56 +02:00
# Include API routers
2025-11-02 20:24:44 +01:00
# IMPORTANT: Register audit router FIRST to avoid route matching conflicts
service.add_router(audit.router)
2025-10-06 15:27:01 +02:00
service.add_router(forecasts.router)
service.add_router(forecasting_operations.router)
service.add_router(analytics.router)
2025-10-07 07:15:07 +02:00
service.add_router(scenario_operations.router)
service.add_router(internal_demo.router)
2025-11-05 13:34:56 +01:00
service.add_router(ml_insights.router) # ML insights endpoint
2025-11-18 07:17:17 +01:00
service.add_router(validation.router) # Validation endpoint
service.add_router(historical_validation.router) # Historical validation endpoint
service.add_router(webhooks.router) # Webhooks endpoint
service.add_router(performance_monitoring.router) # Performance monitoring endpoint
service.add_router(retraining.router) # Retraining endpoint
2025-11-30 09:12:40 +01:00
service.add_router(enterprise_forecasting.router) # Enterprise forecasting endpoint
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
2025-07-21 19:48:56 +02:00