main.py 5.99 KB
"""FastAPI 装配:日志 → 路由 → 前端静态托管。业务逻辑都在各自的包里。"""
from __future__ import annotations
import logging
import os
import time
import uuid
from contextlib import asynccontextmanager
from pathlib import Path

from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from starlette.exceptions import HTTPException as StarletteHTTPException

from .api import documents, envs as envs_api, settings as settings_api, text2sql as text2sql_api
from .api.deps import init_state
from .bootstrap import setup as bootstrap_setup
from .capability import api as cap_api, mcp as mcp_api
from .evals import api as eval_api
from .governance import api as gov_api, users as gov_users
from .kernel import api as kernel_api
from .memory import api as memory_api
from .agents import api as ask_api
from .sop import api as sop_api
from .watch import api as watch_api, scheduler as watch_scheduler
from .core import db, envs, reqcache
from .core.config import get_settings
from .ingest.parse import ParseError

settings = get_settings()
logging.basicConfig(
    level=getattr(logging, settings.log_level.upper(), logging.INFO),
    format="%(asctime)s %(levelname)-7s [%(name)s] %(message)s")
log = logging.getLogger("otlgt3")

ROOT = Path(__file__).parent.parent
# 优先用构建产物;没构建过就回退到源码目录,方便本地起服务
# 同一份代码并行跑多个实例(新旧版本对照)时,用 WEB_DIST 指定各自的前端产物目录
WEB_DIST = ROOT / "web" / (os.environ.get("WEB_DIST", "").strip() or "dist")
WEB_DEV_FALLBACK = ROOT / "web" / "public"


@asynccontextmanager
async def lifespan(app: FastAPI):
    db.init_db()
    reaped = db.reap_stale_jobs()
    if reaped:
        log.warning("清理了 %d 个上次进程残留的未完成任务", reaped)
    init_state()
    bootstrap_setup()
    from .kernel import pipeline
    if pipeline.reap_stale():
        log.warning("清理了上次进程残留的数据管道 / 业务建模运行")
    gov_users.seed()
    from .capability import actions as cap_actions
    cap_actions.recover_stuck()
    from .sop import engine as sop_engine
    sop_engine.recover_stuck()
    watch_scheduler.start()
    log.info("服务启动完成,数据目录 %s", settings.data_path)
    yield


app = FastAPI(title="本体认知引擎 Ontology Engine", version="5.0.0", lifespan=lifespan)
bootstrap_setup()


@app.middleware("http")
async def request_context(request: Request, call_next):
    rid = uuid.uuid4().hex[:12]
    request.state.request_id = rid
    started = time.time()
    # 演示版本:请求头 X-Onto-Env(直链可用 ?env=)决定这次请求读写哪个库,不认识的一律回开发环境
    env_tok = envs.set_current(envs.resolve(
        request.headers.get("x-onto-env", "") or request.query_params.get("env", "")))
    cache_tok = reqcache.begin()
    try:
        response = await call_next(request)
    except Exception:
        log.exception("[%s] %s %s 未捕获异常", rid, request.method, request.url.path)
        raise
    finally:
        reqcache.end(cache_tok)
        envs.reset(env_tok)
    cost = int((time.time() - started) * 1000)
    response.headers["X-Request-Id"] = rid
    # 页面本身不许缓存:重新构建后浏览器必须拿到新的 index.html,才会加载新的前端包
    # (带 hash 的 /assets 照常缓存)。否则旧页面会拿旧前端去调新接口。
    if response.headers.get("content-type", "").startswith("text/html"):
        response.headers["Cache-Control"] = "no-cache"
    if not request.url.path.startswith(("/assets", "/favicon")):
        log.info("[%s] %s %s -> %s %dms", rid, request.method, request.url.path,
                 response.status_code, cost)
    return response


@app.exception_handler(ParseError)
async def parse_error_handler(request: Request, exc: ParseError):
    return JSONResponse(status_code=400, content={"detail": str(exc), "kind": "parse"})


@app.exception_handler(StarletteHTTPException)
async def http_error_handler(request: Request, exc: StarletteHTTPException):
    if exc.status_code == 404 and not request.url.path.startswith("/api"):
        return await spa_fallback(request)   # 前端路由交给 SPA
    return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})


@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
    first = (exc.errors() or [{}])[0]
    loc = " → ".join(str(x) for x in (first.get("loc") or [])[1:])
    return JSONResponse(status_code=422,
                        content={"detail": f"参数有误:{loc} {first.get('msg', '')}".strip()})


app.include_router(settings_api.health_router)
app.include_router(documents.router)
app.include_router(documents.jobs_router)
app.include_router(text2sql_api.router)
app.include_router(settings_api.router)
app.include_router(envs_api.router)
app.include_router(gov_api.router)
app.include_router(kernel_api.router)
app.include_router(cap_api.router)
app.include_router(sop_api.router)
app.include_router(ask_api.router)
app.include_router(eval_api.router)
app.include_router(memory_api.router)
app.include_router(watch_api.router)
app.include_router(mcp_api.router)


async def spa_fallback(request: Request):
    index = (WEB_DIST / "index.html")
    if index.exists():
        return FileResponse(index, media_type="text/html; charset=utf-8")
    return JSONResponse(status_code=404, content={
        "detail": "前端尚未构建。请在 web/ 下执行 npm install && npm run build,"
                  "或用 npm run dev 启动开发服务器。"})


if WEB_DIST.exists():
    app.mount("/", StaticFiles(directory=str(WEB_DIST), html=True), name="web")
elif WEB_DEV_FALLBACK.exists():
    app.mount("/", StaticFiles(directory=str(WEB_DEV_FALLBACK), html=True), name="web-dev")
else:
    @app.get("/")
    async def _root(request: Request):
        return await spa_fallback(request)