use crate::ids::NodeId;
use crate::layout::{GraphPayload, LayoutConfig, LayoutSim, LayoutSnapshot};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
#[derive(Clone, Debug)]
pub enum LayoutCommand<P: Copy> {
Rebuild(Arc<GraphPayload>),
Incremental(Arc<GraphPayload>),
SetPinned(NodeId, bool),
MoveNode(NodeId, P),
Cancel,
Wake,
}
#[derive(Clone, Debug)]
pub enum LayoutMessage<P: Copy> {
Frame(LayoutSnapshot<P>),
Poisoned,
}
type Mailbox<P> = Mutex<Option<LayoutMessage<P>>>;
enum Flow {
Running,
Paused,
}
fn post<P: Copy>(mailbox: &Arc<Mailbox<P>>, msg: LayoutMessage<P>) {
if let Ok(mut slot) = mailbox.lock() {
*slot = Some(msg); }
}
pub struct LayoutWorker<S: LayoutSim> {
cmd_tx: Option<Sender<LayoutCommand<S::Pos>>>,
mailbox: Arc<Mailbox<S::Pos>>,
poisoned: Arc<AtomicBool>,
handle: Option<JoinHandle<()>>,
initial: Option<Arc<GraphPayload>>,
config: LayoutConfig,
}
impl<S: LayoutSim> LayoutWorker<S> {
pub fn spawn(config: LayoutConfig, payload: GraphPayload) -> Self {
let initial = Arc::new(payload);
let (cmd_tx, cmd_rx) = mpsc::channel::<LayoutCommand<S::Pos>>();
let mailbox: Arc<Mailbox<S::Pos>> = Arc::new(Mutex::new(None));
let poisoned = Arc::new(AtomicBool::new(false));
let thread_config = config.clone();
let handle = {
let initial = initial.clone();
let mailbox = mailbox.clone();
let poisoned = poisoned.clone();
std::thread::Builder::new()
.name("arc-graph-layout".into())
.spawn(move || {
let run_mailbox = mailbox.clone();
let result =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
Self::run(cmd_rx, &run_mailbox, thread_config, &initial);
}));
if result.is_err() {
poisoned.store(true, Ordering::SeqCst);
post(&mailbox, LayoutMessage::Poisoned);
}
})
.expect("spawn layout thread")
};
Self {
cmd_tx: Some(cmd_tx),
mailbox,
poisoned,
handle: Some(handle),
initial: Some(initial),
config,
}
}
fn run(
cmd_rx: Receiver<LayoutCommand<S::Pos>>,
mailbox: &Arc<Mailbox<S::Pos>>,
config: LayoutConfig,
initial: &Arc<GraphPayload>,
) {
let mut sim = S::new(config);
sim.rebuild(initial);
let mut flow = Flow::Running;
let publish_interval = std::time::Duration::from_secs_f64(1.0 / 60.0);
let mut next_publish = std::time::Instant::now();
loop {
match flow {
Flow::Running => {
let mut cancelled = false;
loop {
match cmd_rx.try_recv() {
Ok(cmd) => {
match cmd {
LayoutCommand::Rebuild(p) => sim.rebuild(&p),
LayoutCommand::Incremental(p) => sim.incremental(&p),
LayoutCommand::SetPinned(id, pinned) => {
sim.set_pinned(id, pinned)
}
LayoutCommand::MoveNode(id, pos) => sim.move_node(id, pos),
LayoutCommand::Cancel => {
cancelled = true;
break;
}
LayoutCommand::Wake => {}
}
next_publish = std::time::Instant::now();
}
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => return,
}
}
if cancelled {
flow = Flow::Paused;
continue;
}
if sim.is_cooled() {
post(mailbox, LayoutMessage::Frame(sim.snapshot()));
flow = Flow::Paused;
continue;
}
sim.step();
let now = std::time::Instant::now();
if now >= next_publish {
post(mailbox, LayoutMessage::Frame(sim.snapshot()));
next_publish = now + publish_interval;
}
}
Flow::Paused => {
match cmd_rx.recv() {
Ok(LayoutCommand::Rebuild(p)) => {
sim.rebuild(&p);
flow = Flow::Running;
}
Ok(LayoutCommand::Incremental(p)) => {
sim.incremental(&p);
flow = Flow::Running;
}
Ok(LayoutCommand::SetPinned(id, pinned)) => {
sim.set_pinned(id, pinned);
post(mailbox, LayoutMessage::Frame(sim.snapshot()));
}
Ok(LayoutCommand::MoveNode(id, pos)) => {
sim.move_node(id, pos);
flow = Flow::Running;
}
Ok(LayoutCommand::Cancel) => {}
Ok(LayoutCommand::Wake) => flow = Flow::Running,
Err(_) => return, }
}
}
}
}
pub fn send(&self, cmd: LayoutCommand<S::Pos>) {
if let Some(tx) = &self.cmd_tx {
let _ = tx.send(cmd);
}
}
pub fn try_message(&mut self) -> Option<LayoutMessage<S::Pos>> {
self.mailbox.lock().ok()?.take()
}
pub fn try_snapshot(&mut self) -> Option<LayoutSnapshot<S::Pos>> {
match self.try_message()? {
LayoutMessage::Frame(s) => Some(s),
LayoutMessage::Poisoned => None,
}
}
pub fn is_poisoned(&self) -> bool {
self.poisoned.load(Ordering::SeqCst)
}
pub fn restart(&mut self) {
self.join_thread();
let payload = self.initial.clone().unwrap_or_default();
let worker = Self::spawn(self.config.clone(), (*payload).clone());
*self = worker;
}
pub fn rerun(&mut self, config: LayoutConfig, payload: GraphPayload) {
self.join_thread();
let worker = Self::spawn(config, payload);
*self = worker;
}
fn join_thread(&mut self) {
self.cmd_tx = None;
if let Some(h) = self.handle.take() {
let _ = h.join();
}
}
}
impl<S: LayoutSim> Drop for LayoutWorker<S> {
fn drop(&mut self) {
if let Some(tx) = &self.cmd_tx {
let _ = tx.send(LayoutCommand::Cancel);
}
self.cmd_tx = None;
}
}
pub type LayoutWorker2D = LayoutWorker<crate::layout::ForceLayout2D>;
pub type LayoutWorker3D = LayoutWorker<crate::layout::ForceLayout3D>;
#[cfg(test)]
mod tests {
use super::*;
struct PanicSim;
impl LayoutSim for PanicSim {
type Pos = arc_flow_core::geometry::Vec2;
fn new(_config: LayoutConfig) -> Self {
Self
}
fn rebuild(&mut self, _p: &GraphPayload) {}
fn incremental(&mut self, _p: &GraphPayload) {}
fn set_pinned(&mut self, _id: NodeId, _p: bool) {}
fn move_node(&mut self, _id: NodeId, _pos: Self::Pos) {}
fn step(&mut self) {
panic!("layout thread explodes");
}
fn is_cooled(&self) -> bool {
false
}
fn snapshot(&self) -> LayoutSnapshot<Self::Pos> {
LayoutSnapshot {
positions: Arc::new(Vec::new()),
iteration: 0,
alpha: 1.0,
cooled: false,
}
}
}
#[test]
fn panic_in_layout_thread_poisons_but_not_kills_ui() {
let mut worker =
LayoutWorker::<PanicSim>::spawn(LayoutConfig::default(), GraphPayload::default());
let mut poisoned = false;
for _ in 0..500 {
if matches!(worker.try_message(), Some(LayoutMessage::Poisoned)) {
poisoned = true;
}
if poisoned {
break;
}
std::thread::sleep(std::time::Duration::from_millis(2));
}
assert!(poisoned, "UI 应收到 Poisoned 而不是崩掉");
assert!(worker.is_poisoned());
worker.restart();
assert!(!worker.is_poisoned());
}
#[test]
fn layout_compute_is_not_throttled_to_publish_rate() {
struct CountSim {
steps: u32,
}
impl LayoutSim for CountSim {
type Pos = arc_flow_core::geometry::Vec2;
fn new(_config: LayoutConfig) -> Self {
Self { steps: 0 }
}
fn rebuild(&mut self, _p: &GraphPayload) {}
fn incremental(&mut self, _p: &GraphPayload) {}
fn set_pinned(&mut self, _id: NodeId, _p: bool) {}
fn move_node(&mut self, _id: NodeId, _pos: Self::Pos) {}
fn step(&mut self) {
self.steps += 1;
}
fn is_cooled(&self) -> bool {
self.steps >= 300
}
fn snapshot(&self) -> LayoutSnapshot<Self::Pos> {
LayoutSnapshot {
positions: Arc::new(Vec::new()),
iteration: self.steps,
alpha: 0.0,
cooled: self.is_cooled(),
}
}
}
let mut worker =
LayoutWorker::<CountSim>::spawn(LayoutConfig::default(), GraphPayload::default());
let started = std::time::Instant::now();
let mut cooled = false;
while started.elapsed() < std::time::Duration::from_secs(5) {
if let Some(snapshot) = worker.try_snapshot()
&& snapshot.cooled
{
cooled = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(2));
}
assert!(cooled, "应收到冷却快照");
assert!(
started.elapsed() < std::time::Duration::from_secs(1),
"计算被发布节拍限速:300 步耗时 {:?}",
started.elapsed()
);
}
#[test]
fn disconnected_running_worker_exits_before_any_step() {
let (tx, rx) = mpsc::channel();
drop(tx);
let mailbox = Arc::new(Mutex::new(None));
LayoutWorker::<PanicSim>::run(rx, &mailbox, LayoutConfig::default(), &Arc::default());
assert!(mailbox.lock().unwrap().is_none());
}
#[test]
fn cancel_then_wake_resumes() {
let mut g = crate::model::KnowledgeGraph::new();
let a = g.add_node("a", None);
let b = g.add_node("b", None);
g.add_edge(a, b, 1.0, None).unwrap();
let mut worker = LayoutWorker2D::spawn(
LayoutConfig {
max_iterations: 5,
..LayoutConfig::default()
},
GraphPayload::from_graph(&g),
);
worker.send(LayoutCommand::Cancel);
worker.send(LayoutCommand::Wake);
let mut got = false;
for _ in 0..1000 {
if let Some(s) = worker.try_snapshot()
&& s.cooled
{
got = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(2));
}
assert!(got, "取消后唤醒应能继续跑到冷却");
}
}