from contextlib import asynccontextmanager import asyncio import logging import time from fastapi import Depends, FastAPI from fastapi.responses import JSONResponse from sqlalchemy import text from sqlalchemy.exc import SQLAlchemyError from . import assets, auth, events, jobs, submissions, tokens, workflows, batches, shared_assets from .config import Settings from .coordinator import Coordinator from .database import Database def create_app(settings=None, *, provider=None): @asynccontextmanager async def lifespan(app): configuration = settings or Settings.from_env() for root in (configuration.asset_root, configuration.job_work_root, configuration.state_root): root.mkdir(parents=True, exist_ok=True) db = Database(configuration) app.state.settings, app.state.db = configuration, db live_provider = provider if live_provider is None: from .providers import Provider live_provider = Provider(configuration) app.state.provider = live_provider coordinator = Coordinator(configuration, db, live_provider) app.state.coordinator = coordinator app.state.draining = False async def after_tick(): from .workflow_engine import advance_workflows await advance_workflows(db, configuration, live_provider) coordinator.after_tick = after_tick try: await db.initialize() await auth.bootstrap_admin(db, configuration) from .public_preflight import require_public_ready await require_public_ready(db, configuration) if configuration.run_coordinator: await coordinator.start() yield finally: app.state.draining = True await coordinator.close() await live_provider.aclose() await db.close() app = FastAPI(title="CMVR Visual", lifespan=lifespan) from .upload_guard import UploadGuard app.add_middleware(UploadGuard) @app.middleware("http") async def maintenance_writes(request, call_next): from .maintenance import maintenance_active configuration = getattr(request.app.state, "settings", None) if (configuration and request.method in {"POST", "PUT", "PATCH", "DELETE"} and request.url.path.startswith("/api/") and request.url.path not in {"/api/auth/login", "/api/auth/logout"} and maintenance_active(configuration)): return JSONResponse(status_code=503, content={"detail":{ "code":"maintenance", "message":"系统维护中,任务和草稿已保留,请稍后重试"}}) return await call_next(request) @app.exception_handler(SQLAlchemyError) async def database_failure(request, exc): logging.getLogger(__name__).error("Database request failed: %s", type(exc).__name__) return JSONResponse(status_code=503, content={"detail": {"code": "database_unavailable", "message": "数据库暂不可用,请稍后重试"}}) @app.exception_handler(Exception) async def internal_failure(request, exc): logging.getLogger(__name__).exception("Unhandled application error") return JSONResponse(status_code=500, content={"detail": {"code": "internal_error", "message": "服务处理失败,请联系管理员"}}) for router in (auth.router, assets.router, shared_assets.router, shared_assets.publish_router, jobs.router, events.router, submissions.router, tokens.router, workflows.router, workflows.runs_router, batches.router): app.include_router(router, prefix="/api") @app.get("/api/health") async def health(): async with app.state.db.session() as session: await session.execute(text("SELECT 1")) return {"status": "ok", "database": app.state.settings.sqlalchemy_url.get_backend_name()} @app.get("/api/live") async def live(): return {"status": "ok"} @app.get("/api/ready") async def ready(): from .maintenance import maintenance_active checks = {"database": False, "coordinator": True, "upstream_protocol": False, "accepting": not app.state.draining and not maintenance_active(app.state.settings)} try: async with app.state.db.session() as session: await session.execute(text("SELECT 1")) checks["database"] = True # Schema was verified before coordinator startup. except SQLAlchemyError: pass coordinator = app.state.coordinator if app.state.settings.run_coordinator: heartbeat = getattr(coordinator, "last_tick_success", None) checks["coordinator"] = bool(coordinator._task and not coordinator._task.done() and heartbeat is not None and time.monotonic() - heartbeat < 90) try: caps = await asyncio.wait_for(app.state.provider.upstream_capabilities(), 3) checks["upstream_protocol"] = caps.get("protocol_version", 0) >= 2 and bool(caps.get("admission_policy")) except (Exception, asyncio.TimeoutError): pass healthy = all(checks.values()) return JSONResponse(status_code=200 if healthy else 503, content={"status": "ready" if healthy else "not_ready", "checks": checks}) @app.get("/api/capabilities", dependencies=[Depends(auth.current_actor)]) async def capabilities(): from .providers import capabilities as provider_capabilities from .resource_policy import execution_policy from .runtime_policy import read_runtime_policy policy=read_runtime_policy(app.state.settings) return {"items": provider_capabilities(app.state.settings), "scheduler": await app.state.provider.scheduler_status(), "execution_policy": execution_policy(settings=app.state.settings), "workflow_limits":{"max_shots":policy["workflow_max_shots"],"source_frames":121,"max_clip_frames":120,"fps":24}} @app.get("/api/system/status", dependencies=[Depends(auth.current_actor)]) async def status(): from .providers import capabilities as provider_capabilities from .resource_policy import execution_policy from .runtime_policy import read_runtime_policy policy=read_runtime_policy(app.state.settings) online, scheduler = await asyncio.gather(app.state.provider.health(), app.state.provider.scheduler_status()) return {"inference_online": online, "scheduler": scheduler, "models": provider_capabilities(app.state.settings), "environment": app.state.settings.mode, "database_backend": app.state.settings.sqlalchemy_url.get_backend_name(), "execution_policy": execution_policy(settings=app.state.settings), "workflow_limits":{"max_shots":policy["workflow_max_shots"],"source_frames":121,"max_clip_frames":120,"fps":24}, "public_access": getattr(app.state.settings, "public_access", False)} return app app = create_app()