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

152 lines
5.0 KiB
Python
Raw Normal View History

2025-08-12 18:17:30 +02:00
# services/sales/app/main.py
"""
2025-08-12 18:17:30 +02:00
Sales Service Main Application
"""
2025-07-18 14:41:39 +02:00
import structlog
2025-07-18 11:51:43 +02:00
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
2025-07-18 11:51:43 +02:00
from fastapi.responses import JSONResponse
from app.core.config import settings
2025-08-12 18:17:30 +02:00
from app.core.database import init_db, close_db
2025-07-18 12:34:28 +02:00
from shared.monitoring import setup_logging, HealthChecker
from shared.monitoring.metrics import setup_metrics_early
2025-07-18 12:34:28 +02:00
# Setup logging first
2025-08-12 18:17:30 +02:00
setup_logging("sales-service", settings.LOG_LEVEL)
2025-07-18 14:41:39 +02:00
logger = structlog.get_logger()
2025-07-18 11:51:43 +02:00
2025-07-18 12:34:28 +02:00
# Global variables for lifespan access
metrics_collector = None
health_checker = None
2025-07-18 12:34:28 +02:00
# Create FastAPI app FIRST
app = FastAPI(
2025-08-12 18:17:30 +02:00
title="Bakery Sales Service",
description="Sales data management service for bakery operations",
2025-07-18 12:34:28 +02:00
version="1.0.0"
)
2025-07-18 12:34:28 +02:00
# Setup metrics BEFORE any middleware and BEFORE lifespan
2025-08-12 18:17:30 +02:00
metrics_collector = setup_metrics_early(app, "sales-service")
2025-07-18 12:34:28 +02:00
@asynccontextmanager
async def lifespan(app: FastAPI):
2025-08-12 18:17:30 +02:00
"""Application lifespan events"""
2025-07-18 12:34:28 +02:00
global health_checker
# Startup
2025-08-12 18:17:30 +02:00
logger.info("Starting Sales Service...")
2025-07-18 12:34:28 +02:00
try:
# Initialize database
await init_db()
logger.info("Database initialized")
2025-08-12 18:17:30 +02:00
# Register custom metrics
2025-07-18 12:34:28 +02:00
metrics_collector.register_counter("sales_records_created_total", "Total sales records created")
2025-08-12 18:17:30 +02:00
metrics_collector.register_counter("sales_records_updated_total", "Total sales records updated")
2025-07-18 12:34:28 +02:00
metrics_collector.register_counter("sales_queries_total", "Sales record queries")
2025-08-12 18:17:30 +02:00
metrics_collector.register_counter("product_queries_total", "Product catalog queries")
2025-07-18 12:34:28 +02:00
metrics_collector.register_counter("import_jobs_total", "Data import jobs")
2025-08-12 18:17:30 +02:00
metrics_collector.register_counter("export_jobs_total", "Data export jobs")
2025-07-18 12:34:28 +02:00
metrics_collector.register_histogram("sales_create_duration_seconds", "Sales record creation duration")
2025-08-12 18:17:30 +02:00
metrics_collector.register_histogram("sales_query_duration_seconds", "Sales query duration")
metrics_collector.register_histogram("import_processing_duration_seconds", "Import processing duration")
metrics_collector.register_histogram("export_generation_duration_seconds", "Export generation duration")
2025-07-18 12:34:28 +02:00
# Setup health checker
2025-08-12 18:17:30 +02:00
health_checker = HealthChecker("sales-service")
2025-07-18 12:34:28 +02:00
# Add database health check
async def check_database():
try:
from app.core.database import get_db
2025-08-08 09:08:41 +02:00
from sqlalchemy import text
2025-07-18 12:34:28 +02:00
async for db in get_db():
2025-08-08 09:08:41 +02:00
await db.execute(text("SELECT 1"))
2025-07-18 12:34:28 +02:00
return True
except Exception as e:
return f"Database error: {e}"
health_checker.add_check("database", check_database, timeout=5.0, critical=True)
# Store health checker in app state
app.state.health_checker = health_checker
2025-08-12 18:17:30 +02:00
logger.info("Sales Service started successfully")
2025-07-18 12:34:28 +02:00
except Exception as e:
2025-08-12 18:17:30 +02:00
logger.error(f"Failed to start Sales Service: {e}")
2025-07-18 12:34:28 +02:00
raise
yield
# Shutdown
2025-08-12 18:17:30 +02:00
logger.info("Shutting down Sales Service...")
await close_db()
2025-07-18 12:34:28 +02:00
# Set lifespan AFTER metrics setup
app.router.lifespan_context = lifespan
2025-07-18 12:34:28 +02:00
# CORS middleware (added after metrics setup)
app.add_middleware(
CORSMiddleware,
2025-08-12 18:17:30 +02:00
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
2025-08-12 18:17:30 +02:00
# Include routers - import router BEFORE sales router to avoid conflicts
from app.api.sales import router as sales_router
from app.api.import_data import router as import_router
app.include_router(import_router, prefix="/api/v1", tags=["import"])
2025-07-26 18:46:52 +02:00
app.include_router(sales_router, prefix="/api/v1", tags=["sales"])
2025-07-18 12:34:28 +02:00
# Health check endpoint
@app.get("/health")
async def health_check():
2025-07-18 12:34:28 +02:00
"""Comprehensive health check endpoint"""
if health_checker:
return await health_checker.check_health()
else:
return {
2025-08-12 18:17:30 +02:00
"service": "sales-service",
2025-07-18 12:34:28 +02:00
"status": "healthy",
"version": "1.0.0"
}
2025-07-18 11:51:43 +02:00
2025-08-12 18:17:30 +02:00
# Root endpoint
@app.get("/")
async def root():
"""Root endpoint"""
return {
"service": "Sales Service",
"version": "1.0.0",
"status": "running",
"endpoints": {
"health": "/health",
"docs": "/docs",
"sales": "/api/v1/sales",
"products": "/api/v1/products"
}
}
2025-07-18 12:34:28 +02:00
# Exception handlers
2025-07-18 11:51:43 +02:00
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
2025-07-18 12:34:28 +02:00
"""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"})
2025-07-18 11:51:43 +02:00
return JSONResponse(
status_code=500,
content={"detail": "Internal server error"}
2025-07-18 12:34:28 +02:00
)