deps.py 2.59 KB
"""共享的应用级单例与 SSE 工具。"""
from __future__ import annotations
import asyncio
import json
import logging
import threading
from typing import Iterable, Iterator

from fastapi import Request

from ..core.config import get_settings
from ..extract.community import CommunityStore
from ..store.graph_store import GraphStore
from ..store.vector_store import HybridIndex

log = logging.getLogger(__name__)
_settings = get_settings()
_lock = threading.Lock()

_graph: GraphStore | None = None
_index: HybridIndex | None = None
_communities: CommunityStore | None = None


def init_state() -> None:
    global _graph, _index, _communities
    with _lock:
        data = _settings.data_path
        _graph = GraphStore(data / "graph.json")
        _index = HybridIndex(data / "index")
        _communities = CommunityStore(data / "communities.json")


def graph() -> GraphStore:
    if _graph is None:
        init_state()
    return _graph  # type: ignore[return-value]


def index() -> HybridIndex:
    if _index is None:
        init_state()
    return _index  # type: ignore[return-value]


def communities() -> CommunityStore:
    if _communities is None:
        init_state()
    return _communities  # type: ignore[return-value]


async def sse(blocking_gen: Iterable[dict], request: Request | None = None,
              on_event=None) -> Iterator[dict]:
    """把阻塞生成器桥接成 SSE。客户端断开时置位停止标志,让生产线程尽早退出。"""
    loop = asyncio.get_running_loop()
    q: asyncio.Queue = asyncio.Queue()
    DONE = object()
    stop = threading.Event()

    def run():
        try:
            for ev in blocking_gen:
                if stop.is_set():
                    break
                loop.call_soon_threadsafe(q.put_nowait, ev)
        except Exception as e:  # noqa: BLE001
            log.exception("SSE 生产端异常")
            loop.call_soon_threadsafe(
                q.put_nowait, {"type": "error", "stage": "error", "error": str(e)[:500]})
        finally:
            loop.call_soon_threadsafe(q.put_nowait, DONE)

    threading.Thread(target=run, daemon=True).start()
    try:
        while True:
            ev = await q.get()
            if ev is DONE:
                break
            if on_event:
                try:
                    on_event(ev)
                except Exception:  # noqa: BLE001
                    log.debug("on_event 回调异常", exc_info=True)
            yield {"data": json.dumps(ev, ensure_ascii=False)}
            if request is not None and await request.is_disconnected():
                break
    finally:
        stop.set()