deps.py
2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""共享的应用级单例与 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()