main.py 4.14 KB
"""FastAPI 装配:日志 → 路由 → 前端静态托管。业务逻辑都在各自的包里。"""
from __future__ import annotations
import logging
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, graph as graph_api, query as query_api,
                  settings as settings_api, text2sql as text2sql_api)
from .api.deps import init_state
from .core import db
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 = ROOT / "web" / "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()
    log.info("服务启动完成,数据目录 %s", settings.data_path)
    yield


app = FastAPI(title="业务本体抽取与透明深挖检索", version="2.0.0", lifespan=lifespan)


@app.middleware("http")
async def request_context(request: Request, call_next):
    rid = uuid.uuid4().hex[:12]
    request.state.request_id = rid
    started = time.time()
    try:
        response = await call_next(request)
    except Exception:
        log.exception("[%s] %s %s 未捕获异常", rid, request.method, request.url.path)
        raise
    cost = int((time.time() - started) * 1000)
    response.headers["X-Request-Id"] = rid
    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(graph_api.router)
app.include_router(graph_api.node_router)
app.include_router(query_api.router)
app.include_router(text2sql_api.router)
app.include_router(settings_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)