Files
2026-11-27 06:03:56 +00:00

293 lines
9.6 KiB
Rust

//! 用握手控制真实工作线程,验证排队取消与已启动计算的收尾边界。
use dever_runtime::task::{self, DEFAULT_WORKERS, RunError};
use dever_runtime::value::{FaultInfo, fault};
use std::{
collections::HashSet,
future::{Future, poll_fn},
pin::pin,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc,
},
task::Poll,
time::Duration,
};
use tokio::sync::oneshot;
#[test]
fn workers_are_bounded_move_values_and_cancel_before_admission() {
task::run(true, DEFAULT_WORKERS + 1, async |scope| {
let mut tasks = Vec::new();
let mut releases = Vec::new();
let mut threads = HashSet::new();
for _ in 0..DEFAULT_WORKERS {
let (started, ready) = oneshot::channel();
let (release, gate) = mpsc::channel();
let text = String::from("owned worker input");
let address = text.as_ptr() as usize;
let task = scope
.spawn(async move |child| {
child
.parallel(move || {
started.send(std::thread::current().id()).unwrap();
gate.recv_timeout(Duration::from_secs(10)).unwrap();
assert_eq!(text.as_ptr() as usize, address);
(text, address)
})
.await
.unwrap()
})
.unwrap();
threads.insert(ready.await.unwrap());
tasks.push(task);
releases.push(release);
}
assert_eq!(threads.len(), DEFAULT_WORKERS);
assert!(!threads.contains(&std::thread::current().id()));
let executed = Arc::new(AtomicBool::new(false));
let flag = executed.clone();
let (entered, queued) = oneshot::channel();
let queued_task = scope
.spawn(async move |child| {
entered.send(()).unwrap();
child
.parallel(move || flag.store(true, Ordering::SeqCst))
.await
.unwrap();
})
.unwrap();
queued.await.unwrap();
// 工作线程仍全部占用,排队任务也必须立即停止。
assert_eq!(
tokio::time::timeout(Duration::from_secs(1), queued_task.stop())
.await
.unwrap(),
Ok(None)
);
assert!(!executed.load(Ordering::SeqCst));
let flag = executed.clone();
let queued_task = scope
.spawn_blocking(move || flag.store(true, Ordering::SeqCst))
.unwrap();
tokio::task::yield_now().await;
assert_eq!(
tokio::time::timeout(Duration::from_secs(1), queued_task.stop())
.await
.unwrap(),
Ok(None)
);
assert!(!executed.load(Ordering::SeqCst));
for release in releases {
release.send(()).unwrap();
}
for task in tasks {
let (text, address) = task.await.unwrap();
assert_eq!(text.as_ptr() as usize, address);
}
assert!(!executed.load(Ordering::SeqCst));
assert_eq!(
scope.parallel(|| Err::<(), _>("business")).await.unwrap(),
Err("business")
);
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn stopping_or_timing_out_started_blocking_tasks_preserves_late_business_failure() {
for timed in [false, true] {
task::run(true, 1, async |scope| {
let (started, ready) = oneshot::channel();
let (release, gate) = mpsc::channel();
let task = scope
.spawn_blocking(move || {
started.send(()).unwrap();
gate.recv_timeout(Duration::from_secs(10)).unwrap();
Err::<(), _>("late business failure")
})
.unwrap();
ready.await.unwrap();
let mut ending = pin!(async move {
if timed {
let task::Timed::Expired(value) = task.timeout(1).await.unwrap() else {
panic!("must expire")
};
value
} else {
task.stop().await.unwrap()
}
});
poll_fn(|context| {
assert!(ending.as_mut().poll(context).is_pending());
Poll::Ready(())
})
.await;
task::sleep(5).await.unwrap();
poll_fn(|context| {
assert!(ending.as_mut().poll(context).is_pending());
Poll::Ready(())
})
.await;
release.send(()).unwrap();
assert_eq!(ending.await, Some(Err("late business failure")));
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
}
#[test]
fn group_stop_preserves_late_blocking_failure_and_releases_owned_output() {
let released = Arc::new(AtomicBool::new(false));
task::run(true, 1, async |scope| {
let (started, ready) = oneshot::channel();
let (release, gate) = mpsc::channel();
let mut group = task::Group::new(scope, 1).unwrap();
group
.run(|| {
scope.spawn_blocking(move || {
started.send(()).unwrap();
gate.recv_timeout(Duration::from_secs(10)).unwrap();
Err::<(), _>("late group failure")
})
})
.await
.unwrap()
.unwrap();
ready.await.unwrap();
let mut stopping = pin!(group.stop());
poll_fn(|context| {
assert!(stopping.as_mut().poll(context).is_pending());
Poll::Ready(())
})
.await;
release.send(()).unwrap();
assert_eq!(stopping.await, Ok(Err("late group failure")));
let owned = Released(released.clone());
let (started, ready) = oneshot::channel();
let work = scope
.spawn_blocking(move || {
started.send(()).unwrap();
owned
})
.unwrap();
ready.await.unwrap();
drop(work);
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
assert!(released.load(Ordering::SeqCst));
}
struct Released(Arc<AtomicBool>);
impl Drop for Released {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
#[test]
fn cancellation_waits_for_running_worker_and_skips_later_steps() {
let released = Arc::new(AtomicBool::new(false));
let continued = Arc::new(AtomicBool::new(false));
task::run(true, 1, async |scope| {
let held = Released(released.clone());
let flag = continued.clone();
let (started, ready) = oneshot::channel();
let (release, gate) = mpsc::channel();
let task = scope
.spawn(async move |child| {
child
.parallel(move || {
let _held = held;
started.send(()).unwrap();
gate.recv_timeout(Duration::from_secs(10)).unwrap();
})
.await
.unwrap();
flag.store(true, Ordering::SeqCst);
})
.unwrap();
ready.await.unwrap();
let mut stopping = pin!(task.stop());
poll_fn(|context| {
assert!(stopping.as_mut().poll(context).is_pending());
Poll::Ready(())
})
.await;
assert!(!released.load(Ordering::SeqCst));
release.send(()).unwrap();
assert_eq!(stopping.await, Ok(None));
assert!(released.load(Ordering::SeqCst));
assert!(!continued.load(Ordering::SeqCst));
Ok::<_, ()>(())
})
.unwrap()
.unwrap();
}
#[test]
fn worker_fault_keeps_original_payload_and_does_not_replace_business_error() {
static ORIGINAL: FaultInfo = FaultInfo {
message: "original worker fault",
source: "worker.dever",
line: 1,
column: 1,
};
let result = task::run::<(), ()>(true, 1, async |scope| {
scope.parallel(|| fault(&ORIGINAL)).await.unwrap();
Ok(())
})
.unwrap();
let Err(RunError::Fault {
primary,
additional,
}) = result
else {
panic!("expected fault")
};
assert!(std::ptr::eq(
*primary.downcast_ref::<&'static FaultInfo>().unwrap(),
&ORIGINAL
));
assert!(additional.is_empty());
let result = task::run::<(), _>(true, 1, async |scope| {
let (started, ready) = oneshot::channel();
let (release, gate) = mpsc::channel();
let task = scope
.spawn(async move |child| {
child
.parallel(move || {
started.send(()).unwrap();
gate.recv_timeout(Duration::from_secs(10)).unwrap();
fault(&ORIGINAL);
})
.await
.unwrap();
})
.unwrap();
ready.await.unwrap();
// 取消父任务后仍要保留工作线程实际发生的故障。
drop(task);
tokio::task::yield_now().await;
release.send(()).unwrap();
Err("primary business error")
})
.unwrap();
let Err(RunError::Business { error, additional }) = result else {
panic!("expected business error")
};
assert_eq!(error, "primary business error");
assert_eq!(additional.len(), 1);
assert!(std::ptr::eq(
*additional[0].downcast_ref::<&'static FaultInfo>().unwrap(),
&ORIGINAL
));
}