Some checks failed
Backups: pg_dump scripts with daily/weekly rotation and Cloudflare R2 offsite sync. Monitoring: Prometheus, Grafana, node-exporter, cAdvisor in docker-compose; /metrics endpoint activated via prometheus_client. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
117 lines
3.2 KiB
Python
117 lines
3.2 KiB
Python
# app/core/lifespan.py
|
|
"""Application lifespan management - Clean Migration Approach.
|
|
|
|
This module provides classes and functions for:
|
|
- Application startup and shutdown events
|
|
- Logging setup
|
|
- Default user creation
|
|
- NO database table creation (handled by Alembic)
|
|
"""
|
|
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI
|
|
from sqlalchemy import text
|
|
|
|
from middleware.auth import AuthManager
|
|
|
|
from .config import settings
|
|
from .database import engine
|
|
from .logging import setup_logging
|
|
from .observability import init_observability, shutdown_observability
|
|
|
|
# Remove this import if not needed: from models.database.base import Base
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
auth_manager = AuthManager()
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""Application lifespan events - Clean migration approach."""
|
|
|
|
# === STARTUP ===
|
|
app_logger = setup_logging()
|
|
app_logger.info("Starting Orion multi-tenant platform")
|
|
|
|
init_observability(
|
|
enable_metrics=settings.enable_metrics,
|
|
sentry_dsn=settings.sentry_dsn,
|
|
environment=settings.sentry_environment,
|
|
flower_url=settings.flower_url,
|
|
grafana_url=settings.grafana_url,
|
|
)
|
|
|
|
logger.info("[OK] Application startup completed")
|
|
|
|
yield
|
|
|
|
# === SHUTDOWN ===
|
|
app_logger.info("Shutting down Orion platform")
|
|
shutdown_observability()
|
|
|
|
|
|
# === NEW HELPER FUNCTION ===
|
|
def check_database_ready():
|
|
"""Check if database is ready (migrations have been run)."""
|
|
try:
|
|
with engine.connect() as conn:
|
|
# Check for tables in the public schema (PostgreSQL)
|
|
result = conn.execute(
|
|
text(
|
|
"SELECT tablename FROM pg_catalog.pg_tables "
|
|
"WHERE schemaname = 'public' LIMIT 1"
|
|
)
|
|
)
|
|
tables = result.fetchall()
|
|
return len(tables) > 0
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def get_migration_status():
|
|
"""Get current Alembic migration status."""
|
|
try:
|
|
from alembic.config import Config
|
|
|
|
Config("alembic.ini")
|
|
|
|
# This would need more implementation to actually check status
|
|
# For now, just return a placeholder
|
|
return "Migration status check not implemented"
|
|
except Exception as e:
|
|
logger.warning(f"Could not check migration status: {e}")
|
|
return "Unknown"
|
|
|
|
|
|
# === STARTUP VERIFICATION (Optional) ===
|
|
def verify_startup_requirements():
|
|
"""Verify that all startup requirements are met."""
|
|
|
|
issues = []
|
|
|
|
# Check if database exists and has tables
|
|
if not check_database_ready():
|
|
issues.append("Database not ready - run 'make migrate-up' first")
|
|
|
|
# Add other checks as needed
|
|
# - Configuration validation
|
|
# - External service connectivity
|
|
# - Required environment variables
|
|
|
|
if issues:
|
|
logger.error("[ERROR] Startup verification failed:")
|
|
for issue in issues:
|
|
logger.error(f" - {issue}")
|
|
return False
|
|
|
|
logger.info("[OK] Startup verification passed")
|
|
return True
|
|
|
|
|
|
# You can call this in your main.py if desired:
|
|
# if not verify_startup_requirements():
|
|
# raise RuntimeError("Application startup requirements not met")
|