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

171 lines
6.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
2025-07-21 19:48:56 +02:00
from app.api import forecasts, predictions
from app.services.messaging import setup_messaging, cleanup_messaging
from app.services.forecasting_alert_service import ForecastingAlertService
2025-09-29 13:13:12 +02:00
from shared.service_base import StandardFastAPIService
class ForecastingService(StandardFastAPIService):
"""Forecasting Service with standardized setup"""
2025-09-30 21:58:10 +02:00
expected_migration_version = "00001"
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 = [
'forecasts', 'prediction_batches', 'model_performance_metrics', 'prediction_cache'
]
self.alert_service = None
# 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,
api_prefix="/api/v1",
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):
"""Setup messaging for forecasting service"""
2025-07-21 19:48:56 +02:00
await setup_messaging()
2025-09-29 13:13:12 +02:00
self.logger.info("Messaging initialized")
async def _cleanup_messaging(self):
"""Cleanup messaging for forecasting service"""
await cleanup_messaging()
async def on_startup(self, app: FastAPI):
"""Custom startup logic for forecasting service"""
# Initialize forecasting alert service
2025-09-29 13:13:12 +02:00
self.alert_service = ForecastingAlertService(settings)
await self.alert_service.start()
self.logger.info("Forecasting alert service initialized")
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-09-29 13:13:12 +02:00
service.add_router(forecasts.router, tags=["forecasts"])
service.add_router(predictions.router, tags=["predictions"])
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
2025-07-21 19:48:56 +02:00