deps.py
2.59 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
"""共享的应用级单例与 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()