Spaces:
Sleeping
Sleeping
File size: 16,791 Bytes
cd61bf7 5e12ede e023141 1b99aeb 5e12ede 45a98e6 5e12ede 1c2c4a2 5e12ede 1c2c4a2 5e12ede 1c2c4a2 5e12ede 031be0c 5e12ede b6a8f90 20ee727 5e12ede 7c43265 cd61bf7 c997c51 5e12ede bb1b299 727ec8d c90f5cc 6404030 18d2747 6729b8b 20ee727 5b6905f 20ee727 fc39787 ba1fcd9 3bafddd f0e1c07 e023141 cd61bf7 6170320 cd61bf7 ef7edd2 9a6c2ea cd61bf7 887a0cb ef7edd2 9a6c2ea cd61bf7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 | 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
|