Spaces:
Running

contiai / apps /api /app /main.py
aliabozahra315's picture
Deploy 6cc2312
0671a8c
Raw History Blame Contribute Delete
7.92 kB
"""FastAPI application."""
from __future__ import annotations
import asyncio
import logging
import pathlib
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.v1 import admin as admin_routes
from app.api.v1 import admin_users as admin_user_routes
from app.api.v1 import blueprint_read as blueprint_read_routes
from app.api.v1 import design as design_routes
from app.api.v1 import novel as novel_routes
from app.api.v1 import register as register_routes
from app.api.v1 import routes as v1_routes
from app.api.v1 import studio as studio_routes
from app.api.v1 import task_types as task_type_routes
from app.api.v1 import uploads as upload_routes
from app.api.v1 import workspace as workspace_routes
from app.core.config import settings
# Called before any pipeline can print. The ported code logs with emoji, and a
# console that cannot encode one used to take a paid run down with it.
from app.core.console import enable_utf8_output
from app.core.queue import close_pool, get_pool
from app.core.runlog import install_tee
from app.db.session import SessionLocal
from app.observability import llm_meter
enable_utf8_output()
# After the UTF-8 wrapper, so the tee wraps the stream that can encode.
install_tee()
logging.basicConfig(
level=logging.DEBUG if settings.debug else logging.INFO,
format="%(asctime)s %(levelname)-5s [%(name)s] %(message)s",
)
log = logging.getLogger("contiai.api")
async def _release_orphaned_runs() -> None:
"""Fail runs whose executor is gone, so they can be resumed.
A run is marked ``running`` by the process executing it. If that process
dies - a restart, a crash, a deploy - the row keeps saying ``running``
forever, and resume refuses because only a failed run may be resumed. The
work was stranded with no way back.
Nothing is executing at startup by definition, so anything still marked
running is stale. Its completed steps keep their stored output; resuming
picks up from the step that was interrupted.
"""
from sqlalchemy import select, update
from app.db.models import Run, RunStatus, StepRun, StepStatus
async with SessionLocal() as db:
stale = (
await db.scalars(select(Run.id).where(Run.status == RunStatus.running))
).all()
if not stale:
return
await db.execute(
update(StepRun)
.where(StepRun.run_id.in_(stale), StepRun.status == StepStatus.running)
.values(status=StepStatus.failed, error="توقف الخادم أثناء تنفيذ الخطوة")
)
await db.execute(
update(Run)
.where(Run.id.in_(stale))
.values(
status=RunStatus.failed,
error="توقف الخادم أثناء التنفيذ — استأنف لإكمال ما تبقّى",
)
)
await db.commit()
log.warning("released %d run(s) stranded by a previous shutdown", len(stale))
@asynccontextmanager
async def lifespan(app: FastAPI):
llm_meter.install()
try:
await _release_orphaned_runs()
except Exception:
log.exception("could not release orphaned runs")
# The registry pulls in CrewAI and sentence-transformers, which take a few
# seconds. Doing it off the startup path keeps the health check responsive
# while the process warms up.
async def warm() -> None:
try:
# Decided before the first crew is built: CrewAI reads REDIS_URL
# from the environment and would otherwise put a pub/sub lock on
# the hosted Redis around a SQLite file in this container.
from app.core import crew_locks
crew_locks.install()
from app.pipelines.registry import all_pipelines
await asyncio.to_thread(all_pipelines)
log.info("pipelines loaded")
# Steps import what they need inside `run()`, so a missing name is
# never looked up until the step executes - which on a book is
# after four paid steps. `llm_meter.ensure` was missing exactly
# that way. Resolving them here costs a second at boot.
from app.core import preflight
await asyncio.to_thread(preflight.check_contracts)
# After `get_pool()` has decided, so the queue line is the truth
# rather than a guess.
await get_pool()
preflight.report(settings)
except Exception:
log.exception("failed to load pipelines")
warm_task = asyncio.create_task(warm())
flusher = asyncio.create_task(llm_meter.flush_loop(SessionLocal))
yield
for task in (warm_task, flusher):
task.cancel()
await llm_meter.flush_once(SessionLocal)
await close_pool()
app = FastAPI(
title="ContiAI Platform API",
version="1.0.0",
description=(
"Server-orchestrated pipelines for generating Arabic books, courses and "
"training material."
),
lifespan=lifespan,
)
# The previous deployment had no CORS layer at all - it only worked because the
# Hugging Face proxy injected the headers. Nothing implicit here.
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["Content-Disposition"],
)
app.include_router(register_routes.router, prefix=settings.api_prefix)
app.include_router(v1_routes.router, prefix=settings.api_prefix)
app.include_router(upload_routes.router, prefix=settings.api_prefix)
app.include_router(task_type_routes.router, prefix=settings.api_prefix)
app.include_router(workspace_routes.router, prefix=settings.api_prefix)
app.include_router(admin_routes.router, prefix=settings.api_prefix)
app.include_router(admin_user_routes.router, prefix=settings.api_prefix)
app.include_router(design_routes.router, prefix=settings.api_prefix)
app.include_router(studio_routes.router, prefix=settings.api_prefix)
app.include_router(novel_routes.router, prefix=settings.api_prefix)
app.include_router(blueprint_read_routes.router, prefix=settings.api_prefix)
def _build() -> str:
"""Which commit this container is actually running.
Nothing reported it, so «did the deploy land?» was answered by guessing at
a marker from some earlier commit - and once by resuming a run against
code that was still building, which failed with the error the deploy was
meant to fix. The deploy writes the SHA into this file; the endpoint reads
it back.
"""
try:
return (pathlib.Path(__file__).with_name("BUILD.txt")
.read_text(encoding="utf-8").strip() or "unknown")
except Exception:
return "unknown"
@app.get("/health", tags=["meta"])
async def health() -> dict:
return {"status": "ok", "env": settings.env, "version": app.version,
"build": _build()}
@app.get("/health/ready", tags=["meta"])
async def ready() -> dict:
"""Readiness: can we actually reach the database?"""
from sqlalchemy import text
checks: dict[str, str] = {}
try:
async with SessionLocal() as db:
await db.execute(text("select 1"))
checks["database"] = "ok"
except Exception as e:
checks["database"] = f"error: {type(e).__name__}"
try:
from app.core.queue import get_pool
checks["queue"] = "ok" if await get_pool() is not None else "inline (no redis)"
except Exception as e:
checks["queue"] = f"error: {type(e).__name__}"
healthy = not any(v.startswith("error") for v in checks.values())
return {"status": "ok" if healthy else "degraded", "checks": checks}
@app.get("/", tags=["meta"])
async def root() -> dict:
return {"name": "ContiAI Platform API", "docs": "/docs", "health": "/health"}