from fastapi import FastAPI, Request, status from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException as StarletteHTTPException from app.core.config import settings from app.core.database import init_pgvector from app.core.logging import configure_logging, get_logger from app.middleware.request_id import RequestIDMiddleware from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, admin, team, telegram_webhook, partners, notifications, products, bookings, jobs, system, meta_webhooks, voice, google_calendar, websocket_voice, websocket_chat, oauth, landing, site_settings, upload, demo, nova # ... (omitted lines) import asyncio # Trigger reload for env update import sys from slowapi import _rate_limit_exceeded_handler from slowapi.util import get_remote_address from slowapi.errors import RateLimitExceeded from app.core.limiter import limiter import sentry_sdk from sentry_sdk.integrations.fastapi import FastApiIntegration from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration # Fix for Windows: psycopg requires SelectorEventLoop on Windows if sys.platform == 'win32': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # Configure structured logging configure_logging() logger = get_logger(__name__) # Initialize Sentry (error tracking) if settings.SENTRY_DSN: sentry_sdk.init( dsn=settings.SENTRY_DSN, environment=settings.ENVIRONMENT, traces_sample_rate=0.1 if settings.ENVIRONMENT == "production" else 1.0, integrations=[ FastApiIntegration(), SqlalchemyIntegration(), ], # Don't send PII send_default_pii=False, ) logger.info("Sentry initialized", environment=settings.ENVIRONMENT) # Rate limiter is initialized in app.core.limiter app = FastAPI( title=settings.APP_NAME, debug=settings.DEBUG, version="1.0.0", description="MicroFunnel - AI Sales Platform" ) # Add rate limiter to app state app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) # ============================================================================ # ГЛОБАЛЬНЫЕ EXCEPTION HANDLERS (Production-Ready) # ============================================================================ @app.exception_handler(StarletteHTTPException) async def http_exception_handler(request: Request, exc: StarletteHTTPException): """Обработчик для всех HTTP-исключений (404, 403, и т.д.).""" request_id = getattr(request.state, 'request_id', 'unknown') logger.warning( "HTTP Exception", status_code=exc.status_code, detail=exc.detail, request_id=request_id, path=request.url.path ) return JSONResponse( status_code=exc.status_code, content={ "detail": exc.detail, "request_id": request_id } ) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): """Обработчик ошибок валидации Pydantic (422 Unprocessable Entity).""" request_id = getattr(request.state, 'request_id', 'unknown') logger.warning( "Validation Error", errors=exc.errors(), request_id=request_id, path=request.url.path ) return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={ "detail": "Ошибка валидации данных", "errors": exc.errors(), "request_id": request_id } ) @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): """ Глобальный обработчик для ВСЕХ необработанных исключений. КРИТИЧНО для production: - НЕ раскрывает технические детали клиенту - Логирует полный traceback в Sentry - Возвращает user-friendly сообщение """ request_id = getattr(request.state, 'request_id', 'unknown') # Логируем ПОЛНУЮ ошибку (с traceback) для debugging logger.error( "Unhandled Exception", exc_info=exc, request_id=request_id, path=request.url.path, method=request.method, error_type=type(exc).__name__ ) # Отправляем в Sentry (если настроен) if settings.SENTRY_DSN: sentry_sdk.capture_exception(exc) # Возвращаем безопасный ответ клиенту (БЕЗ технических деталей) return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={ "detail": "Внутренняя ошибка сервера. Мы уже работаем над исправлением.", "request_id": request_id, "support_hint": "Сообщите этот request_id в поддержку для быстрого решения проблемы." } ) # Trust Proxy Headers (Railway/Vercel) - Fixes HTTPS redirects and Mixed Content from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*") # Log CORS settings allowed_origins = settings.get_allowed_origins() logger.info(f"CORS allowed origins: {allowed_origins}") # CORS middleware - MUST be added BEFORE other middleware app.add_middleware( CORSMiddleware, allow_origins=allowed_origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], expose_headers=["*"], # Allow frontend to access all headers max_age=3600, # Cache preflight requests for 1 hour ) # Request ID middleware for tracing app.add_middleware(RequestIDMiddleware) # Include API routers with /api/v1 prefix app.include_router(auth.router, prefix="/api/v1") app.include_router(webhook.router, prefix="/api/v1") # Main Telegram AI bot (has /telegram/{tenant_id}) app.include_router(telegram_webhook.router, prefix="/api/v1") # Global notification bot (has /telegram/global) app.include_router(meta_webhooks.router, prefix="/api/v1") # Official Meta API (WA/IG) # app.include_router(linkedin_webhook.router, prefix="/api/v1") # LinkedIn webhook (TODO: Implement) app.include_router(leads.router, prefix="/api/v1") app.include_router(knowledge.router, prefix="/api/v1") app.include_router(channels.router, prefix="/api/v1") app.include_router(channels.router) # Fallback for requests missing /api/v1 app.include_router(tenants.router, prefix="/api/v1/tenants") app.include_router(analytics.router, prefix="/api/v1") app.include_router(chats.router, prefix="/api/v1") app.include_router(playbook.router, prefix="/api/v1") app.include_router(billing.router, prefix="/api/v1") # Billing & Franchise app.include_router(ai_training.router, prefix="/api/v1") # AI Training & Learning app.include_router(admin.router, prefix="/api/v1") # Admin Panel (superuser only) app.include_router(partners.router, prefix="/api/v1") # Partner Dashboard app.include_router(team.router, prefix="/api/v1") # Team Management (owner only) app.include_router(notifications.router, prefix="/api/v1") # HOT Lead Notifications app.include_router(products.router, prefix="/api/v1") app.include_router(bookings.router, prefix="/api/v1") # Products & Catalog Management app.include_router(jobs.router, prefix="/api/v1") app.include_router(system.router, prefix="/api/v1") # System Announcements app.include_router(oauth.router, prefix="/api/v1") # OAuth for Meta Embedded Signup - enable when META_APP_ID is set app.include_router(voice.router, prefix="/api/v1/voice", tags=["Voice"]) app.include_router(websocket_voice.router, prefix="/ws/voice", tags=["Voice Stream"]) app.include_router(websocket_chat.router, prefix="/ws/chat", tags=["Chat Stream"]) app.include_router(google_calendar.router, prefix="/api/v1/google-calendar", tags=["Google Calendar"]) app.include_router(landing.router, prefix="/api/v1/landing", tags=["Landing Page"]) app.include_router(site_settings.router, prefix="/api/v1", tags=["Site Settings"]) app.include_router(upload.router, prefix="/api/v1/upload", tags=["File Upload"]) app.include_router(demo.router, prefix="/api/v1", tags=["Demo Chat"]) app.include_router(nova.router, prefix="/api/v1", tags=["Nova Help"]) @app.on_event("startup") async def on_startup(): """Initialize application on startup.""" # Validate critical environment variables if not settings.GROQ_API_KEY or len(settings.GROQ_API_KEY) < 20: logger.error("Invalid or missing GROQ_API_KEY") raise RuntimeError("GROQ_API_KEY must be configured") if not settings.SECRET_KEY or len(settings.SECRET_KEY) < 32: logger.error("Invalid or missing SECRET_KEY") raise RuntimeError("SECRET_KEY must be at least 32 characters") logger.info("Environment variables validated") # Initialize pgvector extension for PostgreSQL try: await init_pgvector() logger.info("Application started") logger.info("PostgreSQL database connected") except Exception as e: logger.error("Database connection failed", exc_info=True, err=str(e)) logger.warning("Starting in NO DB mode") # Start Background Tasks asyncio.create_task(reactivation_scheduler_loop()) asyncio.create_task(hot_leads_scheduler_loop()) # Hourly for hot leads asyncio.create_task(subscription_expiry_scheduler_loop()) # Daily expiry warnings @app.on_event("shutdown") async def on_shutdown(): """Graceful shutdown: close database connections.""" try: from app.core.database import async_engine await async_engine.dispose() logger.info("Database connections closed gracefully") except Exception as e: logger.error("Error during shutdown", exc_info=True, err=str(e)) async def hot_leads_scheduler_loop(): """ Background loop to run Hot Leads follow-up every hour. Fast follow-up for HOT/WARM leads who went silent. """ from app.services.reactivation_service import get_reactivation_service from app.core.database import async_session_factory logger.info("🔥 Hot Leads Scheduler initialized (runs every hour)") # Wait 5 minutes after startup before first run await asyncio.sleep(5 * 60) while True: try: logger.info("🔥 Running hourly hot leads follow-up...") async with async_session_factory() as session: service = get_reactivation_service() await service.run_hot_leads_batch(session) # Sleep 1 hour await asyncio.sleep(60 * 60) except asyncio.CancelledError: logger.info("Hot leads scheduler cancelled") break except Exception as e: logger.error(f"Hot leads scheduler error: {e}") await asyncio.sleep(15 * 60) # Retry in 15 minutes async def reactivation_scheduler_loop(): """ Background loop to run Reactivation Service daily. """ from app.services.reactivation_service import get_reactivation_service from app.core.database import async_session_factory logger.info("⏳ Reactivation Scheduler initialized") while True: try: # Wait for 1 minute after startup before first run check? # Or run immediately if configured? # For strict daily schedule, we should check time. # Simplified: Run once every 24h, starting 1 hour after boot await asyncio.sleep(60 * 60) # Wait 1 hour after startup logger.info("⏰ Running scheduled reactivation batch...") async with async_session_factory() as session: service = get_reactivation_service() await service.run_daily_batch(session) # Sleep 24 hours await asyncio.sleep(24 * 60 * 60) except asyncio.CancelledError: logger.info("Reactivation scheduler cancelled") break except Exception as e: logger.error(f"Reactivation scheduler error: {e}") await asyncio.sleep(60 * 60) # Retry in 1 hour async def subscription_expiry_scheduler_loop(): """ Background loop to check for expiring subscriptions and send email warnings. Runs daily, sends warnings at 3 days, 1 day, and 0 days before expiry. """ from app.core.database import async_session_factory from sqlmodel import select from app.models.tenant import Tenant from app.models.user import User from app.services.email import get_email_service from datetime import datetime, timedelta logger.info("📧 Subscription Expiry Scheduler initialized (runs daily)") # Wait 10 minutes after startup before first run await asyncio.sleep(10 * 60) while True: try: logger.info("📧 Checking for expiring subscriptions...") email_service = get_email_service() async with async_session_factory() as session: now = datetime.utcnow() # Find tenants expiring in 3 days, 1 day, or today for days_left in [3, 1, 0]: target_date = now + timedelta(days=days_left) start_of_day = target_date.replace(hour=0, minute=0, second=0, microsecond=0) end_of_day = target_date.replace(hour=23, minute=59, second=59, microsecond=999999) stmt = select(Tenant).where( Tenant.subscription_end >= start_of_day, Tenant.subscription_end <= end_of_day, Tenant.subscription_status == 'active' ) result = await session.execute(stmt) expiring_tenants = result.scalars().all() for tenant in expiring_tenants: # Find owner email user_stmt = select(User).where( User.tenant_id == tenant.id, User.role == 'owner' ) user_result = await session.execute(user_stmt) owner = user_result.scalar_one_or_none() if owner and owner.email: await email_service.send_subscription_expiry_warning( to_email=owner.email, company_name=tenant.name or tenant.business_name or "Your Company", days_remaining=days_left, plan_name=tenant.subscription_plan or "trial" ) logger.info(f"📧 Sent expiry warning to {owner.email} ({days_left} days left)") # Sleep 24 hours await asyncio.sleep(24 * 60 * 60) except asyncio.CancelledError: logger.info("Subscription expiry scheduler cancelled") break except Exception as e: logger.error(f"Subscription expiry scheduler error: {e}") await asyncio.sleep(60 * 60) # Retry in 1 hour @app.get("/") async def root(): """Health check endpoint.""" return { "status": "ok", "app": settings.APP_NAME, "environment": settings.ENVIRONMENT } @app.get("/health") async def health_check(): """Detailed health check with real database connectivity test.""" from app.core.database import async_engine from sqlalchemy import text health_status = { "status": "healthy", "database": "unknown", "ai_engine": "ready", "version": "1.0.0", "environment": settings.ENVIRONMENT } # Test database connection try: async with async_engine.connect() as conn: await conn.execute(text("SELECT 1")) health_status["database"] = "connected" except Exception as e: logger.error("Health check: database failed", err=str(e)) health_status["database"] = "disconnected" health_status["status"] = "degraded" return health_status