1use 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#[derive(Clone, Debug)]
50pub enum LayoutCommand<P: Copy> {
51 Rebuild(Arc<GraphPayload>),
53 Incremental(Arc<GraphPayload>),
55 SetPinned(NodeId, bool),
57 MoveNode(NodeId, P),
59 Cancel,
61 Wake,
63}
64
65#[derive(Clone, Debug)]
67pub enum LayoutMessage<P: Copy> {
68 Frame(LayoutSnapshot<P>),
69 Poisoned,
70}
71
72type 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); }
84}
85
86pub 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 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 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 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 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 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 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 sim.move_node(id, pos);
211 flow = Flow::Running;
212 }
213 Ok(LayoutCommand::Cancel) => {}
214 Ok(LayoutCommand::Wake) => flow = Flow::Running,
215 Err(_) => return, }
217 }
218 }
219 }
220 }
221
222 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 pub fn try_message(&mut self) -> Option<LayoutMessage<S::Pos>> {
232 self.mailbox.lock().ok()?.take()
233 }
234
235 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 pub fn is_poisoned(&self) -> bool {
245 self.poisoned.load(Ordering::SeqCst)
246 }
247
248 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 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 if let Some(tx) = &self.cmd_tx {
276 let _ = tx.send(LayoutCommand::Cancel);
277 }
278 self.cmd_tx = None;
279 }
280}
281
282pub type LayoutWorker2D = LayoutWorker<crate::layout::ForceLayout2D>;
284pub type LayoutWorker3D = LayoutWorker<crate::layout::ForceLayout3D>;
286
287#[cfg(test)]
288mod tests {
289 use super::*;
290
291 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 worker.restart();
337 assert!(!worker.is_poisoned());
338 }
339
340 #[test]
341 fn layout_compute_is_not_throttled_to_publish_rate() {
342 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 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}