pi-async-task-queue 0.1.5

任务队列接口及默认实现
Documentation
//! 经公开的内部任务队列(internal task queue)入口验证原值收发、拒绝与清理。

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! {
    // 本文件各测试仅由所属线程(owner thread)调用唤醒和清理。
    static PI_ASYNC_TASK_QUEUE_TEST_DELIVERED: RefCell<VecDeque<Runnable>> = const {
        RefCell::new(VecDeque::new())
    };
}

/// 按实际调度(scheduling)次序保管交出的原值。取出后结束局部借用再处理原任务。
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));
    }
}

/// @api TaskQueue::new_with_unbound 与 InternalTaskQueue 查询。
/// 构造开放的空队列,保留所属域(owner domain),释放队列不关闭所属域。
#[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());
}

/// @api TaskQueue::push_back/pop_back/drain 与 InternalTaskQueue 的单项交付。
/// 新任务与收到真实唤醒(wake-up)的同域任务按尾插顺序取回,状态和结果仍由原任务管理。
#[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());
}

/// @api TaskQueue::push_front/push_back/append_batch 与 InternalTaskQueue::close_internal。
/// 拒绝保留原身份、所属域和数量。停收优先于异域及布局(layout)检查。
#[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);
    }
}

/// @api TaskQueue::append_batch/drain。
/// 同域批次中间项缺链接(link)时,撤销前缀的临时保管并返还全部原值。
/// 取出不合格项后,剩余两项可按原顺序再次交接。
#[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);
    }
}

/// 作为原异步计算(Future)的捕获值,观察每份原值的真实析构(drop)次数。
/// 注入的恐慌(panic)在两项都成功入队后才开启,避免将前置失败误认成清理异常。
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");
        }
    }
}

/// 创建从未轮询(poll)的原异步计算(Future),只观察实际队列归还原值后的析构。
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
}

/// @api InternalTaskQueue::clear_internal/close_internal。
/// 清空时保持开放,之后仍可尾插。关闭时清理新入队的原值并永久停收。
#[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());
}

/// @api TaskQueue 的析构(drop)。
/// 正常析构非空队列时,每项原异步计算(Future)在析构返回前释放一次。
#[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());
}

/// @api TaskQueue 的析构(drop)。
/// 首项原异步计算的恐慌(panic)继续传播,余项仍摘链且每份原值仅析构一次。
#[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());
}