use pi_async_task::definitions::{RunOutcome, TerminationKind};
use pi_async_task::{create, create_local, Runnable, Schedule, TaskOptions, TaskThread};
use pi_async_task_queue::{
InternalTaskQueue, QueueCleanupProgress, QueuePushErrorKind, TaskBatch, TaskQueue,
};
use std::collections::VecDeque;
use std::future::{pending, poll_fn, ready, Future};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed};
use std::{cell::RefCell, rc::Rc, sync::Arc};
use std::task::{Context, Poll, Waker};
thread_local! {
static PI_ASYNC_TASK_QUEUE_TEST_DELIVERED: RefCell<VecDeque<Runnable>> = const {
RefCell::new(VecDeque::new())
};
}
struct Delivery;
impl Delivery {
fn take() -> Option<Runnable> {
PI_ASYNC_TASK_QUEUE_TEST_DELIVERED.with(|received| received.borrow_mut().pop_front())
}
}
impl Schedule for Delivery {
fn schedule(&self, task: Runnable) {
PI_ASYNC_TASK_QUEUE_TEST_DELIVERED.with(|received| received.borrow_mut().push_back(task));
}
}
#[test]
fn test_unbound_queue_starts_empty_with_original_owner() {
let owner = TaskThread::new();
let mut queue = TaskQueue::new_with_unbound(&owner);
assert_eq!(queue.internal_owner_id(), Some(owner.id()));
assert_eq!(queue.internal_len(), 0);
assert!(queue.pop_internal_front().is_none());
assert!(!queue.is_internal_closed());
drop(queue);
assert!(!owner.is_closed());
}
#[test]
fn test_unbound_submission_and_admitted_wake_share_tail_order() {
let owner = TaskThread::new();
let waker = Rc::new(RefCell::new(None));
let captured = Rc::clone(&waker);
let mut first_poll = true;
let local = create_local(
&owner,
poll_fn(move |cx| {
if std::mem::take(&mut first_poll) {
assert!(captured.borrow_mut().replace(cx.waker().clone()).is_none());
Poll::Pending
} else {
Poll::Ready(22_u32)
}
}),
Delivery,
(),
TaskOptions::intrusive(),
)
.unwrap_or_else(|_| panic!("创建同域任务"));
let local_id = local.runnable.id();
let local_registration = local.runnable.admit(&owner).expect("接纳(admission)同域任务");
assert!(matches!(local.runnable.run(&owner), Ok(RunOutcome::Pending)));
let new = create(ready(11_u32), Delivery, (), TaskOptions::intrusive_local_and_mpsc())
.unwrap_or_else(|_| panic!("创建未绑定任务"));
let new_id = new.runnable.id();
let mut default_queue = TaskQueue::new(&owner);
let rejected = default_queue.push_back(new.runnable).expect_err("默认尾插要求同域");
assert_eq!(rejected.cause, QueuePushErrorKind::WrongOwner);
assert!(default_queue.is_empty());
let mut queue = TaskQueue::new_with_unbound(&owner);
queue.try_push_internal_back(rejected.task).unwrap_or_else(|_| panic!("尾插未绑定原值"));
assert_eq!(new.control.snapshot().owner, None);
assert!(!new.control.snapshot().admitted);
let first_waker = waker.borrow_mut().take().expect("首轮已登记的唤醒器(Waker)");
first_waker.wake();
let woken = Delivery::take().expect("同线程唤醒交付原任务");
assert_eq!(woken.id(), local_id);
assert!(woken.snapshot().admitted);
queue.push_back(woken).unwrap_or_else(|_| panic!("尾插已接纳的同域原值"));
assert_eq!(queue.internal_len(), 2);
let first = queue.pop_internal_front().expect("先取到新任务");
assert_eq!(first.id(), new_id);
assert_eq!(first.snapshot().owner, None);
assert!(!first.snapshot().admitted);
queue.push_back(first).unwrap_or_else(|_| panic!("复用已摘链的原值"));
let last = queue.pop_back().expect("从队尾取回复用的原值");
assert_eq!(last.id(), new_id);
queue.push_back(last).unwrap_or_else(|_| panic!("再次尾插已摘链的原值"));
let mut batch = queue.drain().into_iter();
assert!(queue.is_empty());
let local_value = batch.next().expect("已接纳任务现位于队首");
assert_eq!(local_value.id(), local_id);
assert_eq!(local_value.snapshot().owner, Some(owner.id()));
assert!(local_value.snapshot().admitted);
let new_value = batch.next().expect("取回原未绑定任务");
assert_eq!(new_value.id(), new_id);
assert_eq!(new_value.snapshot().owner, None);
assert!(batch.next().is_none());
let new_registration = new_value.admit(&owner).expect("取回后才接纳");
assert!(matches!(local_value.run(&owner), Ok(RunOutcome::Finished(TerminationKind::Completed))));
assert!(matches!(new_value.run(&owner), Ok(RunOutcome::Finished(TerminationKind::Completed))));
let mut cx = Context::from_waker(Waker::noop());
assert!(matches!(std::pin::pin!(local.join).poll(&mut cx), Poll::Ready(Ok(22))));
assert!(matches!(std::pin::pin!(new.join).poll(&mut cx), Poll::Ready(Ok(11))));
drop((local_registration, new_registration));
assert!(Delivery::take().is_none());
}
#[test]
fn test_unbound_queue_rejections_preserve_original_values() {
let owner = TaskThread::new();
let other_owner = TaskThread::new();
let mut queue = TaskQueue::new_with_unbound(&owner);
let unbound = create(ready(()), Delivery, (), TaskOptions::intrusive())
.unwrap_or_else(|_| panic!("创建未绑定任务"));
let id = unbound.runnable.id();
let rejected = queue.try_push_internal_front(unbound.runnable).expect_err("头插要求同域");
assert_eq!(rejected.cause, QueuePushErrorKind::WrongOwner);
assert_eq!(rejected.task.id(), id);
let batch = TaskBatch::from_tasks(VecDeque::from([rejected.task]));
let rejected = queue.append_batch(batch).expect_err("整批追加要求同域");
assert_eq!(rejected.cause, QueuePushErrorKind::WrongOwner);
let returned = rejected.batch.into_iter().next().expect("原批次仍有该值");
assert_eq!(returned.id(), id);
assert_eq!(returned.snapshot().owner, None);
drop(returned);
let foreign = create_local(&other_owner, ready(()), Delivery, (), TaskOptions::intrusive())
.unwrap_or_else(|_| panic!("创建异域任务"));
let foreign_id = foreign.runnable.id();
let rejected = queue.push_back(foreign.runnable).expect_err("尾插拒绝异域");
assert_eq!(rejected.cause, QueuePushErrorKind::WrongOwner);
assert_eq!(rejected.task.id(), foreign_id);
assert_eq!(rejected.task.snapshot().owner, Some(other_owner.id()));
let plain = create(ready(()), Delivery, (), TaskOptions::plain())
.unwrap_or_else(|_| panic!("创建无本地链接(link)的任务"));
let plain_id = plain.runnable.id();
let missing = queue.push_back(plain.runnable).expect_err("尾插需要本地链接");
assert_eq!(missing.cause, QueuePushErrorKind::LinkMissing);
assert_eq!(missing.task.id(), plain_id);
assert_eq!(missing.task.snapshot().owner, None);
assert_eq!(queue.internal_len(), 0);
assert!(matches!(queue.close_internal(), Ok(QueueCleanupProgress::Complete)));
for task in [rejected.task, missing.task] {
let id = task.id();
let before = task.snapshot();
let closed = queue.try_push_internal_back(task).expect_err("停收优先");
assert_eq!(closed.cause, QueuePushErrorKind::Closed);
assert_eq!(closed.task.id(), id);
assert_eq!(closed.task.snapshot(), before);
drop(closed.task);
}
assert_eq!(queue.internal_len(), 0);
other_owner.close();
while let Some(task) = Delivery::take() {
drop(task);
}
}
#[test]
fn test_unbound_queue_batch_returns_full_order_after_link_rejection() {
let owner = TaskThread::new();
let mut queue = TaskQueue::new_with_unbound(&owner);
let tasks = [TaskOptions::intrusive(), TaskOptions::plain(), TaskOptions::intrusive()].map(
|options| {
create_local(&owner, ready(()), Delivery, (), options)
.unwrap_or_else(|_| panic!("创建同域任务"))
.runnable
},
);
let expected = [&tasks[0], &tasks[1], &tasks[2]].map(Runnable::id);
let error = queue
.append_batch(TaskBatch::from_tasks(VecDeque::from(tasks)))
.expect_err("批次中间项缺少链接");
assert_eq!(error.cause, QueuePushErrorKind::LinkMissing);
assert_eq!(queue.len(), 0);
let mut returned = error.batch.into_iter();
let first = returned.next().expect("返还第一项");
let missing = returned.next().expect("返还中间项");
let last = returned.next().expect("返还末项");
assert_eq!([first.id(), missing.id(), last.id()], expected);
assert!(returned.next().is_none());
let batch = TaskBatch::from_tasks(VecDeque::from([first, last]));
assert!(matches!(queue.append_batch(batch), Ok(2)));
assert_eq!(queue.len(), 2);
let drained = queue.drain();
assert_eq!(queue.len(), 0);
assert!(drained.into_iter().map(|task| task.id()).eq([expected[0], expected[2]]));
drop(missing);
owner.close();
while let Some(task) = Delivery::take() {
drop(task);
}
}
struct DropCount {
count: Arc<AtomicUsize>,
panic_on_drop: Option<Arc<AtomicBool>>,
}
impl Drop for DropCount {
fn drop(&mut self) {
self.count.fetch_add(1, Relaxed);
if self.panic_on_drop.as_ref().is_some_and(|armed| armed.load(Relaxed)) {
panic!("unbound-future-drop");
}
}
}
fn unbound_with_drop(probe: DropCount, schedule: Delivery) -> Runnable {
create(
async move {
let _keep = &probe;
pending::<()>().await;
},
schedule,
(),
TaskOptions::intrusive_local_and_mpsc(),
)
.unwrap_or_else(|_| panic!("创建带析构观察的任务"))
.runnable
}
#[test]
fn test_unbound_clear_keeps_queue_open_and_close_is_idempotent() {
let owner = TaskThread::new();
let mut queue = TaskQueue::new_with_unbound(&owner);
let cleared = Arc::new(AtomicUsize::new(0));
let closed = Arc::new(AtomicUsize::new(0));
let probe = DropCount { count: Arc::clone(&cleared), panic_on_drop: None };
let task = unbound_with_drop(probe, Delivery);
queue.push_back(task).unwrap_or_else(|_| panic!("压入待清空原值"));
assert!(matches!(queue.clear_internal(), Ok(QueueCleanupProgress::Complete)));
assert!(queue.is_empty());
assert!(!queue.is_internal_closed());
assert_eq!(cleared.load(Relaxed), 1);
let probe = DropCount { count: Arc::clone(&closed), panic_on_drop: None };
let task = unbound_with_drop(probe, Delivery);
queue.push_back(task).unwrap_or_else(|_| panic!("仍可接收新原值"));
for _ in 0..2 {
assert!(matches!(queue.close_internal(), Ok(QueueCleanupProgress::Complete)));
assert!(queue.is_internal_closed());
assert!(queue.is_empty());
assert_eq!(closed.load(Relaxed), 1);
}
drop(queue);
assert_eq!(cleared.load(Relaxed), 1);
assert_eq!(closed.load(Relaxed), 1);
assert!(Delivery::take().is_none());
}
#[test]
fn test_unbound_queue_drop_releases_each_original_once() {
let owner = TaskThread::new();
let first = Arc::new(AtomicUsize::new(0));
let second = Arc::new(AtomicUsize::new(0));
let mut queue = TaskQueue::new_with_unbound(&owner);
for count in [&first, &second] {
let probe = DropCount { count: Arc::clone(count), panic_on_drop: None };
let task = unbound_with_drop(probe, Delivery);
queue.push_back(task).unwrap_or_else(|_| panic!("压入待析构原值"));
assert_eq!(count.load(Relaxed), 0);
}
assert_eq!(queue.len(), 2);
drop(queue);
assert_eq!(first.load(Relaxed), 1);
assert_eq!(second.load(Relaxed), 1);
assert!(Delivery::take().is_none());
}
#[test]
fn test_unbound_queue_drop_unwind_releases_each_original_once() {
let owner = TaskThread::new();
let first = Arc::new(AtomicUsize::new(0));
let second = Arc::new(AtomicUsize::new(0));
let armed = Arc::new(AtomicBool::new(false));
let mut queue = TaskQueue::new_with_unbound(&owner);
let probes = [
DropCount { count: Arc::clone(&first), panic_on_drop: Some(Arc::clone(&armed)) },
DropCount { count: Arc::clone(&second), panic_on_drop: None },
];
for probe in probes {
let task = unbound_with_drop(probe, Delivery);
queue.push_back(task).unwrap_or_else(|_| panic!("压入待析构原值"));
}
armed.store(true, Relaxed);
let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(queue)))
.expect_err("原析构恐慌应继续传播");
assert_eq!(panic.downcast_ref::<&str>(), Some(&"unbound-future-drop"));
assert_eq!(first.load(Relaxed), 1);
assert_eq!(second.load(Relaxed), 1);
assert!(Delivery::take().is_none());
}