Refactor all main.py
This commit is contained in:
@@ -1,97 +1,83 @@
|
||||
# services/tenant/app/main.py
|
||||
"""
|
||||
Tenant Service FastAPI application - FIXED VERSION
|
||||
Tenant Service FastAPI application
|
||||
"""
|
||||
|
||||
import structlog
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.database import database_manager
|
||||
from app.api import tenants, subscriptions, webhooks
|
||||
from shared.monitoring.logging import setup_logging
|
||||
from shared.monitoring.metrics import MetricsCollector
|
||||
from shared.service_base import StandardFastAPIService
|
||||
|
||||
# Setup logging
|
||||
setup_logging("tenant-service", settings.LOG_LEVEL)
|
||||
logger = structlog.get_logger()
|
||||
|
||||
# Create FastAPI app
|
||||
app = FastAPI(
|
||||
title="Tenant Management Service",
|
||||
description="Multi-tenant bakery management service",
|
||||
version="1.0.0",
|
||||
class TenantService(StandardFastAPIService):
|
||||
"""Tenant Service with standardized setup"""
|
||||
|
||||
def __init__(self):
|
||||
# Define expected database tables for health checks
|
||||
tenant_expected_tables = ['tenants', 'tenant_members', 'subscriptions']
|
||||
|
||||
super().__init__(
|
||||
service_name="tenant-service",
|
||||
app_name="Tenant Management Service",
|
||||
description="Multi-tenant bakery management service",
|
||||
version="1.0.0",
|
||||
log_level=settings.LOG_LEVEL,
|
||||
api_prefix="/api/v1",
|
||||
database_manager=database_manager,
|
||||
expected_tables=tenant_expected_tables
|
||||
)
|
||||
|
||||
async def on_startup(self, app: FastAPI):
|
||||
"""Custom startup logic for tenant service"""
|
||||
# Import models to ensure they're registered with SQLAlchemy
|
||||
from app.models.tenants import Tenant, TenantMember, Subscription
|
||||
self.logger.info("Tenant models imported successfully")
|
||||
|
||||
async def on_shutdown(self, app: FastAPI):
|
||||
"""Custom shutdown logic for tenant service"""
|
||||
# Database cleanup is handled by the base class
|
||||
pass
|
||||
|
||||
def get_service_features(self):
|
||||
"""Return tenant-specific features"""
|
||||
return [
|
||||
"multi_tenant_management",
|
||||
"subscription_management",
|
||||
"tenant_isolation",
|
||||
"webhook_notifications",
|
||||
"member_management"
|
||||
]
|
||||
|
||||
def setup_custom_endpoints(self):
|
||||
"""Setup custom endpoints for tenant service"""
|
||||
@self.app.get("/metrics")
|
||||
async def metrics():
|
||||
"""Prometheus metrics endpoint"""
|
||||
if self.metrics_collector:
|
||||
return self.metrics_collector.get_metrics()
|
||||
return {"metrics": "not_available"}
|
||||
|
||||
|
||||
# Create service instance
|
||||
service = TenantService()
|
||||
|
||||
# Create FastAPI app with standardized setup
|
||||
app = service.create_app(
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc"
|
||||
)
|
||||
|
||||
# Initialize metrics
|
||||
metrics_collector = MetricsCollector("tenant_service")
|
||||
app.state.metrics_collector = metrics_collector
|
||||
# Setup standard endpoints
|
||||
service.setup_standard_endpoints()
|
||||
|
||||
# CORS middleware
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
# Setup custom endpoints
|
||||
service.setup_custom_endpoints()
|
||||
|
||||
# Include routers
|
||||
app.include_router(tenants.router, prefix="/api/v1", tags=["tenants"])
|
||||
app.include_router(subscriptions.router, prefix="/api/v1", tags=["subscriptions"])
|
||||
app.include_router(webhooks.router, prefix="/api/v1", tags=["webhooks"])
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup_event():
|
||||
"""Initialize service on startup"""
|
||||
logger.info("Starting Tenant Service...")
|
||||
|
||||
try:
|
||||
# ✅ FIX: Import models to ensure they're registered with SQLAlchemy
|
||||
from app.models.tenants import Tenant, TenantMember, Subscription
|
||||
logger.info("Tenant models imported successfully")
|
||||
|
||||
# ✅ FIX: Create database tables on startup
|
||||
await database_manager.create_tables()
|
||||
logger.info("Tenant database tables created successfully")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to initialize tenant service: {e}")
|
||||
raise
|
||||
|
||||
logger.info("Tenant Service startup completed successfully")
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown_event():
|
||||
"""Cleanup on shutdown"""
|
||||
logger.info("Shutting down Tenant Service...")
|
||||
|
||||
try:
|
||||
# Close database connections properly
|
||||
if hasattr(database_manager, 'engine') and database_manager.engine:
|
||||
await database_manager.engine.dispose()
|
||||
logger.info("Database connections closed")
|
||||
except Exception as e:
|
||||
logger.error(f"Error during shutdown: {e}")
|
||||
|
||||
logger.info("Tenant Service shutdown completed")
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
"""Health check endpoint"""
|
||||
return {
|
||||
"status": "healthy",
|
||||
"service": "tenant-service",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
|
||||
@app.get("/metrics")
|
||||
async def metrics():
|
||||
"""Prometheus metrics endpoint"""
|
||||
return metrics_collector.get_metrics()
|
||||
service.add_router(tenants.router, tags=["tenants"])
|
||||
service.add_router(subscriptions.router, tags=["subscriptions"])
|
||||
service.add_router(webhooks.router, tags=["webhooks"])
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
Reference in New Issue
Block a user