Files
resolutionflow/backend/app/main.py
chihlasm 76653bab1e Fix CORS for Railway PR environments
Add ALLOW_RAILWAY_ORIGINS env var that enables regex-based CORS
allowing any *.up.railway.app origin. This makes PR environment
testing work without manually setting FRONTEND_URL for each PR.

Set ALLOW_RAILWAY_ORIGINS=true in Railway backend env vars.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 01:35:44 -05:00

90 lines
2.6 KiB
Python

import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.core.database import init_db
from app.core.logging_config import setup_logging
from app.core.middleware import RequestLoggingMiddleware, ErrorLoggingMiddleware
from app.api.router import api_router
# Initialize logging configuration
setup_logging()
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan handler."""
# Startup
logger.info("Starting Patherly API server...")
logger.info(f"Environment: {'Development' if settings.DEBUG else 'Production'}")
# Note: In production, use Alembic migrations instead of init_db
# await init_db()
yield
# Shutdown
logger.info("Shutting down Patherly API server...")
app = FastAPI(
title=settings.APP_NAME,
description="Patherly - 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
)
# Add logging middleware (BEFORE CORS to log all requests)
app.add_middleware(ErrorLoggingMiddleware)
app.add_middleware(RequestLoggingMiddleware)
# Configure CORS with dynamic origin checking for Railway PR environments
def get_allowed_origins():
"""Return origins list or callable for dynamic checking."""
if settings.ALLOW_RAILWAY_ORIGINS:
# Use callable to dynamically check Railway origins
def check_origin(origin: str) -> bool:
return settings.is_origin_allowed(origin)
return check_origin
return settings.allowed_origins
# Note: When ALLOW_RAILWAY_ORIGINS is True, we use allow_origin_regex for Railway domains
if settings.ALLOW_RAILWAY_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origin_regex=r"https://.*\.up\.railway\.app",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
else:
app.add_middleware(
CORSMiddleware,
allow_origins=settings.allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include API router
app.include_router(api_router, prefix=settings.API_V1_PREFIX)
@app.get("/")
async def root():
"""Root endpoint."""
return {
"message": "Patherly API",
"docs": "/api/docs",
"version": "1.0.0"
}
@app.get("/health")
async def health_check():
"""Health check endpoint."""
return {"status": "healthy"}