Files
resolutionflow/backend/app/main.py
chihlasm 5abff028bc feat: APScheduler integration for maintenance flow auto-session creation
- Add backend/app/core/scheduler.py with AsyncIOScheduler, CronTrigger-based
  job registration, and _fire_maintenance_schedule to create batch sessions
- Wire scheduler.start()/load_all_schedules()/shutdown() into main.py lifespan
- Call register_schedule() in create_schedule endpoint after commit
- Call register_schedule()/unregister_schedule() in update_schedule based on is_active
- Add TreeShare to models/__init__.py so all SQLAlchemy mapper relationships
  resolve before ORM queries in the scheduler context

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-17 14:21:29 -05:00

113 lines
3.5 KiB
Python

import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from app.core.config import settings
from app.core.database import init_db, async_session_maker
from app.core.logging_config import setup_logging
from app.core.middleware import RequestLoggingMiddleware, ErrorLoggingMiddleware
from app.core.rate_limit import limiter
from app.api.router import api_router
from app.core.scheduler import scheduler, load_all_schedules
# Initialize logging configuration
setup_logging()
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan handler."""
# Startup
logger.info("Starting ResolutionFlow API server...")
logger.info(f"Environment: {'Development' if settings.DEBUG else 'Production'}")
logger.info(f"ALLOW_RAILWAY_ORIGINS: {settings.ALLOW_RAILWAY_ORIGINS}")
# Note: In production, use Alembic migrations instead of init_db
# await init_db()
# Start maintenance schedule runner
scheduler.start()
async with async_session_maker() as db:
await load_all_schedules(db)
yield
# Shutdown
scheduler.shutdown(wait=False)
logger.info("Shutting down ResolutionFlow API server...")
app = FastAPI(
title=settings.APP_NAME,
description="ResolutionFlow - Take the path MOST traveled. Guided troubleshooting with automatic documentation.",
version="1.0.0",
docs_url="/api/docs",
redoc_url="/api/redoc",
openapi_url="/api/openapi.json",
lifespan=lifespan
)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# Add logging middleware (BEFORE CORS to log all requests)
app.add_middleware(ErrorLoggingMiddleware)
app.add_middleware(RequestLoggingMiddleware)
# Configure CORS
# Note: When ALLOW_RAILWAY_ORIGINS is True, we use allow_origin_regex for Railway domains
# PLUS the explicit allowed_origins list (for custom domains like app.resolutionflow.com)
if settings.ALLOW_RAILWAY_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=settings.allowed_origins,
allow_origin_regex=r"https://.*\.up\.railway\.app",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["X-Redaction-Mode", "X-Redaction-Summary"],
)
else:
app.add_middleware(
CORSMiddleware,
allow_origins=settings.allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["X-Redaction-Mode", "X-Redaction-Summary"],
)
# Include API router
app.include_router(api_router, prefix=settings.API_V1_PREFIX)
@app.get("/")
async def root():
"""Root endpoint."""
return {
"message": "ResolutionFlow API",
"docs": "/api/docs",
"version": "1.0.0"
}
@app.get("/health")
async def health_check():
"""Health check endpoint."""
return {"status": "healthy"}
if settings.DEBUG:
@app.get("/debug/cors")
async def debug_cors():
"""Debug endpoint to check CORS configuration."""
return {
"allow_railway_origins": settings.ALLOW_RAILWAY_ORIGINS,
"cors_mode": "regex + list" if settings.ALLOW_RAILWAY_ORIGINS else "list",
"allowed_origins": settings.allowed_origins,
"railway_regex": r"https://.*\.up\.railway\.app" if settings.ALLOW_RAILWAY_ORIGINS else None
}