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

from fastapi import Request

from ..core import envs
from ..store.vector_store import HybridIndex

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

# 文档检索索引按环境各一份:演示版本读的是快照时复制出来的数据目录
_state: dict[str, HybridIndex] = {}


def _load(env_id: str) -> HybridIndex:
    return HybridIndex(envs.data_dir(env_id) / "index")


def init_state() -> None:
    with _lock:
        _state[envs.DEV] = _load(envs.DEV)


def reset_state() -> None:
    """演示快照被重置 / 删除后调用:下次访问时重新从磁盘加载。"""
    with _lock:
        for k in [k for k in _state if k != envs.DEV]:
            _state.pop(k, None)


def _current_state() -> HybridIndex:
    env_id = envs.current()
    st = _state.get(env_id)
    if st is None:
        with _lock:
            st = _state.get(env_id)
            if st is None:
                st = _state[env_id] = _load(env_id)
    return st


def index() -> HybridIndex:
    return _current_state()


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)

    # 生产线程要带上请求上下文(当前操作者、工作区),审计与数据范围都靠它
    ctx = contextvars.copy_context()
    threading.Thread(target=lambda: ctx.run(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()