auto / main.py
rsnarsna
fix(lifespan): run hydration synchronously during pytest runs to guarantee test isolation
ca663dd
Raw History Blame Contribute Delete
5.83 kB
"""
ALLI Backend - Modular Pure FastAPI REST & Execution Engine
Registers CORS, GZip compression, RBAC Authentication middleware,
structured exception handlers, and modular domain routers at both root and /api prefixes.
"""
import os
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
from dotenv import load_dotenv
import env
from database.mongo import workflow_repo
from database.seeds import seed_all_collections
from language_core.node_schema import default_registry
from middleware.auth import AuthenticationMiddleware
from app.routers import ALL_CORE_ROUTERS
from app.feedback import feedback_router
from app.forums import forum_router
from app.blog import blog_router
# Backward-compatible re-exports for existing tests and scripts
from app.routers.workflows import WorkflowPayload, verify_workflow_ownership
from app.routers.users import verify_user_access
from app.routers.telemetry import verify_run_access
from lambdas.workflows_handler import (
save_workflow_logic,
get_workflow_logic,
delete_workflow_logic,
)
load_dotenv()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Startup database seeding and graceful shutdown lifecycle."""
print(f"[ALLI Backend] Modular FastAPI engine started on port {env.PORT} in {env.STAGE} mode.", flush=True)
print(f"[ALLI Backend] Database connection state: {workflow_repo.is_connected}", flush=True)
import asyncio
def _background_init():
if workflow_repo.is_connected:
seed_all_collections(workflow_repo)
try:
from library_inspector.hydration import hydrate_persisted_library_nodes
hydrated = hydrate_persisted_library_nodes(workflow_repo)
print(f"[ALLI Backend] Hydrated persisted library nodes: {hydrated}", flush=True)
except Exception as exc:
print(f"[ALLI Backend] Library hydration warning: {exc}", flush=True)
if "PYTEST_CURRENT_TEST" in os.environ or env.STAGE == "test":
_background_init()
elif workflow_repo.is_connected:
asyncio.create_task(asyncio.to_thread(_background_init))
yield
print("[ALLI Backend] FastAPI engine shutting down gracefully...")
if hasattr(workflow_repo, "client") and workflow_repo.client:
try:
workflow_repo.client.close()
print("[ALLI Backend] Database connection closed.")
except Exception:
pass
workflow_repo.client = None
workflow_repo.collection = None
workflow_repo.users_collection = None
workflow_repo._is_connected = False
workflow_repo._connected_attempted = False
app = FastAPI(
title="ALLI — Workflow Logic Backend Engine",
description="High-Performance Modular FastAPI REST & Execution Engine for ALLI Workflow Logic and Logic Studio",
version="3.0.0",
lifespan=lifespan,
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
)
default_origins = [
"http://localhost:3000",
"http://127.0.0.1:3000",
"http://localhost:8001",
"http://127.0.0.1:8001",
"https://alli.app",
"https://alli-frontend.pages.dev",
]
env_origins = os.environ.get("ALLOWED_ORIGINS")
allowed_origins = [o.strip() for o in env_origins.split(",") if o.strip()] if env_origins else default_origins
app.add_middleware(
CORSMiddleware,
allow_origins=allowed_origins,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["*"],
)
app.add_middleware(GZipMiddleware, minimum_size=1000)
supabase_client = None
SUPABASE_URL = os.environ.get("SUPABASE_URL") or env.SUPABASE_URL
SUPABASE_KEY = os.environ.get("SUPABASE_KEY") or env.SUPABASE_KEY
if SUPABASE_URL and SUPABASE_KEY:
try:
from supabase import create_client
supabase_client = create_client(SUPABASE_URL, SUPABASE_KEY)
print(f"[ALLI Backend] Supabase initialized for project: {SUPABASE_URL}")
except Exception as e:
print(f"[ALLI Backend] Supabase init warning: {e}")
app.state.supabase_client = supabase_client
app.add_middleware(AuthenticationMiddleware, supabase_client=supabase_client)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=exc.status_code,
content={
"detail": exc.detail,
"status_code": exc.status_code,
"path": str(request.url.path),
"timestamp": datetime.now(timezone.utc).isoformat(),
},
)
@app.exception_handler(Exception)
async def unhandled_exception_handler(request: Request, exc: Exception):
print(f"[ALLI Backend Error] Unhandled exception on {request.url.path}: {str(exc)}")
return JSONResponse(
status_code=500,
content={
"detail": f"Internal server error: {str(exc)}",
"status_code": 500,
"path": str(request.url.path),
"timestamp": datetime.now(timezone.utc).isoformat(),
},
)
# Mount all modular domain routers at both root and /api prefixes
for core_router in ALL_CORE_ROUTERS:
app.include_router(core_router)
app.include_router(core_router, prefix="/api")
for domain_router in (feedback_router, forum_router, blog_router):
app.include_router(domain_router, prefix="/api")
app.include_router(domain_router)
if __name__ == "__main__":
import uvicorn
print(f"[ALLI Backend] Starting traditional Uvicorn server on http://127.0.0.1:{env.PORT}")
uvicorn.run("main:app", host="127.0.0.1", port=env.PORT, reload=True)