"""FastAPI 应用入口。 启动:cd backend && uv run uvicorn app.main:app --reload 启动时(lifespan)清理上次进程异常退出遗留的 queued/running Job → failed,防止「进程被杀后 Job 永久 running」(AGENT.md §20 状态机闭环)。 测试可用环境变量 QLIB_SKIP_STALE_JOB_CLEANUP=1 关闭(不触碰开发库)。 """ from __future__ import annotations import logging import os from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.api.router import api_router from app.core.config import get_settings logger = logging.getLogger("uvicorn.error") settings = get_settings() def _cleanup_stale_jobs() -> None: """把上次进程异常退出遗留的 queued/running Job 标记 failed。""" if os.environ.get("QLIB_SKIP_STALE_JOB_CLEANUP") == "1": return try: from app.application.services.job_executor import mark_stale_jobs_failed n = mark_stale_jobs_failed(reason="服务重启:上次未完成任务被中断") if n: logger.info("启动清理:%d 个遗留 Job 已标记 failed", n) except Exception: # noqa: BLE001 —— 启动清理失败不阻断服务 logger.exception("启动清理残留 Job 失败") @asynccontextmanager async def lifespan(_app: FastAPI): _cleanup_stale_jobs() yield app = FastAPI( title=settings.app_name, version=settings.app_version, description="A股个人量化研究平台 API(研究引擎 / Tushare 数据源)", lifespan=lifespan, ) # 开发期 CORS:允许任意来源(个人本地平台,无 Cookie 凭据,allow_credentials=False)。 # 前端默认走 Next 同源代理(见 frontend/web/next.config.ts rewrites),直连 API 也放行; # 上线部署前请收紧为明确白名单。 app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=False, allow_methods=["*"], allow_headers=["*"], ) app.include_router(api_router, prefix=settings.api_prefix)