Skip to main content

arc_graph_core/
worker.rs

1//! 后台布局线程(方案 §4「布局在后台线程跑,不卡 UI」)。
2//!
3//! # 视图层使用方法(G3/G4/G5 照此接入)
4//!
5//! 布局在进程内独立线程逐步迭代,**每帧只拷贝坐标快照到信箱**:
6//! UI 每帧非阻塞地取走最新快照(没有就沿用上一张,绝不等待);
7//! 布局线程 panic 不带崩界面(`Poisoned` 消息 + `restart`)。
8//!
9//! ```
10//! use arc_graph_core::{GraphPayload, KnowledgeGraph, LayoutCommand,
11//!     LayoutConfig, LayoutWorker2D};
12//!
13//! // 1. 从模型图取槽位快照,启动后台布局线程(纯进程内线程,无任何后端服务)。
14//! let mut g = KnowledgeGraph::new();
15//! let a = g.add_node("A", None);
16//! let b = g.add_node("B", None);
17//! g.add_edge(a, b, 1.0, None).unwrap();
18//! let mut worker = LayoutWorker2D::spawn(LayoutConfig::default(), GraphPayload::from_graph(&g));
19//!
20//! // 2. UI 每帧:非阻塞取最新快照;冷却前每帧都会拿到更新的坐标。
21//! let mut latest = None;
22//! for _ in 0..200 {
23//!     if let Some(snapshot) = worker.try_snapshot() {
24//!         latest = Some(snapshot); // snapshot.positions 与 GraphPayload.node_ids 槽位对齐
25//!     }
26//!     if latest.as_ref().is_some_and(|s| s.cooled) {
27//!         break;
28//!     }
29//!     std::thread::sleep(std::time::Duration::from_millis(4)); // 真实 UI 是等下一帧
30//! }
31//! assert!(latest.is_some());
32//!
33//! // 3. 交互期改图 / 固定节点:发命令,布局在后台继续跑。
34//! worker.send(LayoutCommand::SetPinned(a, true));
35//! worker.send(LayoutCommand::SetPinned(a, false));
36//!
37//! // 4. 丢弃 worker 即停线程;线程 panic 后用 worker.restart() 重启。
38//! drop(worker);
39//! ```
40
41use crate::ids::NodeId;
42use crate::layout::{GraphPayload, LayoutConfig, LayoutSim, LayoutSnapshot};
43use std::sync::atomic::{AtomicBool, Ordering};
44use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
45use std::sync::{Arc, Mutex};
46use std::thread::JoinHandle;
47
48/// 发给布局线程的命令。
49#[derive(Clone, Debug)]
50pub enum LayoutCommand<P: Copy> {
51    /// 全量重建(丢弃旧位置,按种子重新铺开)。
52    Rebuild(Arc<GraphPayload>),
53    /// 增量并入:已有节点保留位置,新节点落在邻居附近。
54    Incremental(Arc<GraphPayload>),
55    /// 固定 / 解除固定节点。
56    SetPinned(NodeId, bool),
57    /// 直接设置节点位置(拖动节点用):清除速度,并唤醒已冷却的仿真。
58    MoveNode(NodeId, P),
59    /// 暂停迭代(可 `Wake` 恢复)。
60    Cancel,
61    /// 恢复迭代。
62    Wake,
63}
64
65/// 布局线程回给 UI 的消息。`Poisoned` 表示线程 panic(UI 不受影响,可 `restart`)。
66#[derive(Clone, Debug)]
67pub enum LayoutMessage<P: Copy> {
68    Frame(LayoutSnapshot<P>),
69    Poisoned,
70}
71
72/// 单槽信箱:布局线程覆盖写,UI 取走读。「最新帧必达」由覆盖语义天然保证。
73type Mailbox<P> = Mutex<Option<LayoutMessage<P>>>;
74
75enum Flow {
76    Running,
77    Paused,
78}
79
80fn post<P: Copy>(mailbox: &Arc<Mailbox<P>>, msg: LayoutMessage<P>) {
81    if let Ok(mut slot) = mailbox.lock() {
82        *slot = Some(msg); // 旧帧直接被覆盖丢弃——UI 只需要最新一张
83    }
84}
85
86/// 后台布局线程句柄。泛型驱动 [`LayoutSim`],视图层用别名
87/// [`LayoutWorker2D`] / [`LayoutWorker3D`]。
88pub struct LayoutWorker<S: LayoutSim> {
89    cmd_tx: Option<Sender<LayoutCommand<S::Pos>>>,
90    mailbox: Arc<Mailbox<S::Pos>>,
91    poisoned: Arc<AtomicBool>,
92    handle: Option<JoinHandle<()>>,
93    initial: Option<Arc<GraphPayload>>,
94    config: LayoutConfig,
95}
96
97impl<S: LayoutSim> LayoutWorker<S> {
98    /// 启动后台布局线程。
99    pub fn spawn(config: LayoutConfig, payload: GraphPayload) -> Self {
100        let initial = Arc::new(payload);
101        let (cmd_tx, cmd_rx) = mpsc::channel::<LayoutCommand<S::Pos>>();
102        let mailbox: Arc<Mailbox<S::Pos>> = Arc::new(Mutex::new(None));
103        let poisoned = Arc::new(AtomicBool::new(false));
104        let thread_config = config.clone();
105        let handle = {
106            let initial = initial.clone();
107            let mailbox = mailbox.clone();
108            let poisoned = poisoned.clone();
109            std::thread::Builder::new()
110                .name("arc-graph-layout".into())
111                .spawn(move || {
112                    // 方案 §7:布局线程 panic 不带崩 UI,只发 Poisoned。
113                    let run_mailbox = mailbox.clone();
114                    let result =
115                        std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
116                            Self::run(cmd_rx, &run_mailbox, thread_config, &initial);
117                        }));
118                    if result.is_err() {
119                        poisoned.store(true, Ordering::SeqCst);
120                        post(&mailbox, LayoutMessage::Poisoned);
121                    }
122                })
123                .expect("spawn layout thread")
124        };
125        Self {
126            cmd_tx: Some(cmd_tx),
127            mailbox,
128            poisoned,
129            handle: Some(handle),
130            initial: Some(initial),
131            config,
132        }
133    }
134
135    fn run(
136        cmd_rx: Receiver<LayoutCommand<S::Pos>>,
137        mailbox: &Arc<Mailbox<S::Pos>>,
138        config: LayoutConfig,
139        initial: &Arc<GraphPayload>,
140    ) {
141        let mut sim = S::new(config);
142        sim.rebuild(initial);
143        let mut flow = Flow::Running;
144        // 计算与发布解耦:迭代可以连续跑(冷启动尽快收敛),但快照最多按显示节拍交给
145        // UI。若把计算也压到每帧一步,600 步上限会被摊成数秒,且逐步触发整窗重绘,
146        // 实测整机 CPU 反而成倍上升。
147        let publish_interval = std::time::Duration::from_secs_f64(1.0 / 60.0);
148        let mut next_publish = std::time::Instant::now();
149        loop {
150            match flow {
151                Flow::Running => {
152                    // 排水命令:通道关闭立即退出,不等待高成本仿真自然冷却。
153                    let mut cancelled = false;
154                    loop {
155                        match cmd_rx.try_recv() {
156                            Ok(cmd) => {
157                                match cmd {
158                                    LayoutCommand::Rebuild(p) => sim.rebuild(&p),
159                                    LayoutCommand::Incremental(p) => sim.incremental(&p),
160                                    LayoutCommand::SetPinned(id, pinned) => {
161                                        sim.set_pinned(id, pinned)
162                                    }
163                                    LayoutCommand::MoveNode(id, pos) => sim.move_node(id, pos),
164                                    LayoutCommand::Cancel => {
165                                        cancelled = true;
166                                        break;
167                                    }
168                                    LayoutCommand::Wake => {}
169                                }
170                                // 图被改动:下一步立刻发布,别等节拍窗口。
171                                next_publish = std::time::Instant::now();
172                            }
173                            Err(TryRecvError::Empty) => break,
174                            Err(TryRecvError::Disconnected) => return,
175                        }
176                    }
177                    if cancelled {
178                        flow = Flow::Paused;
179                        continue;
180                    }
181                    if sim.is_cooled() {
182                        post(mailbox, LayoutMessage::Frame(sim.snapshot()));
183                        flow = Flow::Paused;
184                        continue;
185                    }
186                    sim.step();
187                    let now = std::time::Instant::now();
188                    if now >= next_publish {
189                        post(mailbox, LayoutMessage::Frame(sim.snapshot()));
190                        next_publish = now + publish_interval;
191                    }
192                }
193                Flow::Paused => {
194                    // 阻塞等命令;通道关闭(UI 丢弃句柄)则退出线程。
195                    match cmd_rx.recv() {
196                        Ok(LayoutCommand::Rebuild(p)) => {
197                            sim.rebuild(&p);
198                            flow = Flow::Running;
199                        }
200                        Ok(LayoutCommand::Incremental(p)) => {
201                            sim.incremental(&p);
202                            flow = Flow::Running;
203                        }
204                        Ok(LayoutCommand::SetPinned(id, pinned)) => {
205                            sim.set_pinned(id, pinned);
206                            post(mailbox, LayoutMessage::Frame(sim.snapshot()));
207                        }
208                        Ok(LayoutCommand::MoveNode(id, pos)) => {
209                            // 拖动节点:落位后唤醒仿真,让邻居围绕新位置松弛。
210                            sim.move_node(id, pos);
211                            flow = Flow::Running;
212                        }
213                        Ok(LayoutCommand::Cancel) => {}
214                        Ok(LayoutCommand::Wake) => flow = Flow::Running,
215                        Err(_) => return, // UI 丢弃句柄:线程收尾退出
216                    }
217                }
218            }
219        }
220    }
221
222    /// 发送命令(通道关闭时静默丢弃——worker 已停)。
223    pub fn send(&self, cmd: LayoutCommand<S::Pos>) {
224        if let Some(tx) = &self.cmd_tx {
225            let _ = tx.send(cmd);
226        }
227    }
228
229    /// 非阻塞取走一条消息(信箱是单槽,UI 每帧调用一次即可)。
230    /// `Poisoned` 表示布局线程 panic,用 [`Self::restart`] 重启。
231    pub fn try_message(&mut self) -> Option<LayoutMessage<S::Pos>> {
232        self.mailbox.lock().ok()?.take()
233    }
234
235    /// 每帧取最新快照的便捷方法;线程中毒返回 `None`(配合 [`Self::is_poisoned`])。
236    pub fn try_snapshot(&mut self) -> Option<LayoutSnapshot<S::Pos>> {
237        match self.try_message()? {
238            LayoutMessage::Frame(s) => Some(s),
239            LayoutMessage::Poisoned => None,
240        }
241    }
242
243    /// 布局线程是否已 panic(可 [`Self::restart`])。
244    pub fn is_poisoned(&self) -> bool {
245        self.poisoned.load(Ordering::SeqCst)
246    }
247
248    /// 重启布局线程(panic 后或需要彻底重跑时)。沿用当前配置与初始图数据。
249    pub fn restart(&mut self) {
250        self.join_thread();
251        let payload = self.initial.clone().unwrap_or_default();
252        let worker = Self::spawn(self.config.clone(), (*payload).clone());
253        *self = worker;
254    }
255
256    /// 彻底重跑:换配置 / 换图数据并重启线程。
257    pub fn rerun(&mut self, config: LayoutConfig, payload: GraphPayload) {
258        self.join_thread();
259        let worker = Self::spawn(config, payload);
260        *self = worker;
261    }
262
263    fn join_thread(&mut self) {
264        self.cmd_tx = None;
265        if let Some(h) = self.handle.take() {
266            let _ = h.join();
267        }
268    }
269}
270
271impl<S: LayoutSim> Drop for LayoutWorker<S> {
272    fn drop(&mut self) {
273        // 关闭命令通道 → Running/Paused 都在当前 step 完成后退出。
274        // Drop 不 join,避免 UI 线程等待一次高成本布局迭代。
275        if let Some(tx) = &self.cmd_tx {
276            let _ = tx.send(LayoutCommand::Cancel);
277        }
278        self.cmd_tx = None;
279    }
280}
281
282/// 2D 便捷别名。
283pub type LayoutWorker2D = LayoutWorker<crate::layout::ForceLayout2D>;
284/// 3D 便捷别名。
285pub type LayoutWorker3D = LayoutWorker<crate::layout::ForceLayout3D>;
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    // panic 隔离:用自定义 LayoutSim 在 step 里引爆,UI 侧只收到 Poisoned。
292    struct PanicSim;
293
294    impl LayoutSim for PanicSim {
295        type Pos = arc_flow_core::geometry::Vec2;
296        fn new(_config: LayoutConfig) -> Self {
297            Self
298        }
299        fn rebuild(&mut self, _p: &GraphPayload) {}
300        fn incremental(&mut self, _p: &GraphPayload) {}
301        fn set_pinned(&mut self, _id: NodeId, _p: bool) {}
302        fn move_node(&mut self, _id: NodeId, _pos: Self::Pos) {}
303        fn step(&mut self) {
304            panic!("layout thread explodes");
305        }
306        fn is_cooled(&self) -> bool {
307            false
308        }
309        fn snapshot(&self) -> LayoutSnapshot<Self::Pos> {
310            LayoutSnapshot {
311                positions: Arc::new(Vec::new()),
312                iteration: 0,
313                alpha: 1.0,
314                cooled: false,
315            }
316        }
317    }
318
319    #[test]
320    fn panic_in_layout_thread_poisons_but_not_kills_ui() {
321        let mut worker =
322            LayoutWorker::<PanicSim>::spawn(LayoutConfig::default(), GraphPayload::default());
323        let mut poisoned = false;
324        for _ in 0..500 {
325            if matches!(worker.try_message(), Some(LayoutMessage::Poisoned)) {
326                poisoned = true;
327            }
328            if poisoned {
329                break;
330            }
331            std::thread::sleep(std::time::Duration::from_millis(2));
332        }
333        assert!(poisoned, "UI 应收到 Poisoned 而不是崩掉");
334        assert!(worker.is_poisoned());
335        // restart 后线程恢复,可以正常收消息(PanicSim 空实现,直接冷却)。
336        worker.restart();
337        assert!(!worker.is_poisoned());
338    }
339
340    #[test]
341    fn layout_compute_is_not_throttled_to_publish_rate() {
342        // 300 步纯计算:若把计算也压到每帧一步,需要约 5 秒;解耦后应远小于 1 秒。
343        struct CountSim {
344            steps: u32,
345        }
346        impl LayoutSim for CountSim {
347            type Pos = arc_flow_core::geometry::Vec2;
348            fn new(_config: LayoutConfig) -> Self {
349                Self { steps: 0 }
350            }
351            fn rebuild(&mut self, _p: &GraphPayload) {}
352            fn incremental(&mut self, _p: &GraphPayload) {}
353            fn set_pinned(&mut self, _id: NodeId, _p: bool) {}
354            fn move_node(&mut self, _id: NodeId, _pos: Self::Pos) {}
355            fn step(&mut self) {
356                self.steps += 1;
357            }
358            fn is_cooled(&self) -> bool {
359                self.steps >= 300
360            }
361            fn snapshot(&self) -> LayoutSnapshot<Self::Pos> {
362                LayoutSnapshot {
363                    positions: Arc::new(Vec::new()),
364                    iteration: self.steps,
365                    alpha: 0.0,
366                    cooled: self.is_cooled(),
367                }
368            }
369        }
370
371        let mut worker =
372            LayoutWorker::<CountSim>::spawn(LayoutConfig::default(), GraphPayload::default());
373        let started = std::time::Instant::now();
374        let mut cooled = false;
375        while started.elapsed() < std::time::Duration::from_secs(5) {
376            if let Some(snapshot) = worker.try_snapshot()
377                && snapshot.cooled
378            {
379                cooled = true;
380                break;
381            }
382            std::thread::sleep(std::time::Duration::from_millis(2));
383        }
384        assert!(cooled, "应收到冷却快照");
385        assert!(
386            started.elapsed() < std::time::Duration::from_secs(1),
387            "计算被发布节拍限速:300 步耗时 {:?}",
388            started.elapsed()
389        );
390    }
391
392    #[test]
393    fn disconnected_running_worker_exits_before_any_step() {
394        let (tx, rx) = mpsc::channel();
395        drop(tx);
396        let mailbox = Arc::new(Mutex::new(None));
397        // PanicSim 永不冷却且 step 必 panic:关闭通道必须直接返回,不能再迭代。
398        LayoutWorker::<PanicSim>::run(rx, &mailbox, LayoutConfig::default(), &Arc::default());
399        assert!(mailbox.lock().unwrap().is_none());
400    }
401
402    #[test]
403    fn cancel_then_wake_resumes() {
404        let mut g = crate::model::KnowledgeGraph::new();
405        let a = g.add_node("a", None);
406        let b = g.add_node("b", None);
407        g.add_edge(a, b, 1.0, None).unwrap();
408        let mut worker = LayoutWorker2D::spawn(
409            LayoutConfig {
410                max_iterations: 5,
411                ..LayoutConfig::default()
412            },
413            GraphPayload::from_graph(&g),
414        );
415        worker.send(LayoutCommand::Cancel);
416        worker.send(LayoutCommand::Wake);
417        let mut got = false;
418        for _ in 0..1000 {
419            if let Some(s) = worker.try_snapshot()
420                && s.cooled
421            {
422                got = true;
423                break;
424            }
425            std::thread::sleep(std::time::Duration::from_millis(2));
426        }
427        assert!(got, "取消后唤醒应能继续跑到冷却");
428    }
429}