pi-async-task-queue 0.1.0

本地侵入式任务队列与外部任务池接入
Documentation
//! 经公开批次(TaskBatch)及本地队列(TaskQueue)验证唯一持有与保序交接。
use pi_async_task::{create, Runnable, Schedule, TaskOptions};
use pi_async_task_queue::TaskBatch;
use std::collections::VecDeque;

/// 从未绑定的批次(TaskBatch)放弃不需要调度(Schedule)。
struct NoSchedule;
impl Schedule for NoSchedule {
    fn schedule(&self, _task: Runnable) { panic!("批次(batch)不应调度(schedule)"); }
}

/// @test T5/T6/T7/T8/T15;@api TaskQueue::new/owner_id/len/is_empty。
/// 本地队列(TaskQueue)从固定所属域(owner domain)的空状态建立,释放不影响所属域。
#[test]
fn test_local_queue_starts_empty_with_fixed_owner() {
    let owner = pi_async_task::TaskThread::new();
    let queue = pi_async_task_queue::TaskQueue::new(&owner);
    assert_eq!(queue.owner_id(), owner.id());
    assert_eq!(queue.len(), 0);
    assert!(queue.is_empty());
    drop(queue);
    assert!(!owner.is_closed());
}

/// 清理持有(Runnable)交宿主后续原线程(thread)处理,本夹具只保存,不轮询(poll)。
struct Delivery(std::sync::mpsc::Sender<Runnable>);
impl Schedule for Delivery {
    fn schedule(&self, task: Runnable) { self.0.send(task).unwrap_or_else(|_| panic!("通道(channel)已关闭")); }
}

/// @test T9/T10/T11/T12/T15/T16/T17/T18/T19/T20/T92/T95/T96/T97/T98/T116/T117/T118。
/// @api TaskQueue::push_front/push_back/pop_front/pop_back;原址链接(link)摘除后可安全复用。
#[test]
fn test_local_deque_order_and_reusable_embedded_links() {
    let owner = pi_async_task::TaskThread::new();
    let (tx, rx) = std::sync::mpsc::channel();
    let a = pi_async_task::create_local(&owner, std::future::pending::<()>(), Delivery(tx.clone()), (), TaskOptions::intrusive()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    let b = pi_async_task::create_local(&owner, std::future::pending::<()>(), Delivery(tx), (), TaskOptions::intrusive()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    let ids = [a.runnable.id(), b.runnable.id()];
    let mut queue = pi_async_task_queue::TaskQueue::new(&owner);
    queue.push_back(a.runnable).unwrap_or_else(|_| panic!("尾插(push_back)失败"));
    queue.push_front(b.runnable).unwrap_or_else(|_| panic!("头插(push_front)失败"));
    assert_eq!(queue.len(), 2);
    let first = queue.pop_front().unwrap();
    assert_eq!(first.id(), ids[1]);
    queue.push_back(first).unwrap_or_else(|_| panic!("重用链接(link)失败"));
    assert_eq!(queue.pop_back().unwrap().id(), ids[1]);
    assert_eq!(queue.pop_front().unwrap().id(), ids[0]);
    assert!(queue.is_empty());
    owner.close();
    while let Ok(task) = rx.try_recv() { drop(task); }
}

/// @test T13/T14/T117;@api TaskQueue::append_batch/drain。
/// 整批拒绝(batch rejection)保留原顺序且不插入前缀;成功后按队首顺序取回所有唯一持有。
#[test]
fn test_batch_rejection_is_atomic_and_drain_preserves_order() {
    let owner = pi_async_task::TaskThread::new();
    let (tx, rx) = std::sync::mpsc::channel();
    let a = pi_async_task::create_local(&owner, std::future::pending::<()>(), Delivery(tx.clone()), (), TaskOptions::intrusive()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    let b = pi_async_task::create_local(&owner, std::future::pending::<()>(), Delivery(tx), (), TaskOptions::plain()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    let ids = [a.runnable.id(), b.runnable.id()];
    let mut queue = pi_async_task_queue::TaskQueue::new(&owner);
    let batch = TaskBatch::from_tasks(VecDeque::from([a.runnable, b.runnable]));
    let rejected = match queue.append_batch(batch) { Err(error) => error, Ok(_) => panic!("无链接(link)任务必须拒绝") };
    assert_eq!(rejected.cause, pi_async_task_queue::QueuePushErrorKind::LinkMissing);
    assert!(queue.is_empty());
    let returned: Vec<_> = rejected.batch.into_iter().collect();
    assert_eq!(returned.iter().map(Runnable::id).collect::<Vec<_>>(), ids);
    let mut returned = returned.into_iter();
    let valid = returned.next().unwrap();
    let plain = returned.next().unwrap();
    assert_eq!(queue.append_batch(TaskBatch::from_tasks(VecDeque::from([valid]))).unwrap_or_else(|_| panic!("有效批次(batch)失败")), 1);
    let drained = queue.drain();
    assert!(queue.is_empty());
    assert_eq!(drained.into_iter().next().unwrap().id(), ids[0]);
    drop(plain);
    owner.close();
    while let Ok(task) = rx.try_recv() { drop(task); }
}

/// 固定输入(random input)仅用于同档位保序测试,不声称公平性(fairness)。
#[cfg(feature = "pool")]
fn random_zero() -> u64 { 0 }

/// @test T21/T26;@api TaskPoolQueue::new及析构(drop)。
/// 空池(pool)创建及释放不能触发交付(dispatch)或执行(execution)。
#[cfg(feature = "pool")]
#[test]
fn test_empty_pool_can_be_created_and_released() {
    drop(pi_async_task_queue::TaskPoolQueue::new(random_zero));
}

/// @test T21/T22/T23/T24/T25/T26;@api TaskPoolQueue/ExternalTaskQueue。
/// 原生任务池(TaskPool)只保存透明持有(Runnable),批取保持原顺序并清零精确计数。
#[cfg(feature = "pool")]
#[test]
fn test_pool_batch_transfer_and_closed_rejection_keep_identity() {
    use pi_async_task_queue::{BatchAttempt, ExternalTaskQueue, TaskPoolQueue};
    let pool = TaskPoolQueue::new(random_zero);
    assert_eq!(pool.len(), 0);
    let a = create(std::future::pending::<()>(), NoSchedule, (), TaskOptions::plain()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    let b = create(std::future::pending::<()>(), NoSchedule, (), TaskOptions::plain()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    let ids = [a.runnable.id(), b.runnable.id()];
    pool.try_push(a.runnable).unwrap_or_else(|_| panic!("提交(submission)失败"));
    pool.try_push(b.runnable).unwrap_or_else(|_| panic!("提交(submission)失败"));
    assert_eq!(pool.len(), 2);
    let batch = match pool.try_take_batch() { BatchAttempt::Ready(batch) => batch, _ => panic!("批取(batch take)应有结果") };
    assert_eq!(batch.into_iter().map(|task| task.id()).collect::<Vec<_>>(), ids);
    assert_eq!(pool.len(), 0);
    assert!(matches!(pool.close(), BatchAttempt::Empty | BatchAttempt::Closed));
    let c = create(std::future::pending::<()>(), NoSchedule, (), TaskOptions::plain()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    let id = c.runnable.id();
    let rejected = match pool.try_push(c.runnable) { Err(error) => error, Ok(_) => panic!("关闭(close)后不得接纳") };
    assert_eq!(rejected.cause, pi_async_task_queue::ExternalPushErrorKind::Closed);
    assert_eq!(rejected.task.id(), id);
}

/// @test T22/T26;@api TaskPoolQueue::close及析构(drop)。
/// 非空关闭(close)移出原持有;未取回的池析构(drop)归还原值一次,不执行异步计算(Future)。
#[cfg(feature = "pool")]
#[test]
fn test_nonempty_pool_close_and_drop_release_future_once() {
    use pi_async_task_queue::{BatchAttempt, ExternalTaskQueue, TaskPoolQueue};
    struct CountDrop(std::sync::Arc<std::sync::atomic::AtomicUsize>);
    impl std::future::Future for CountDrop {
        type Output = ();
        fn poll(self: std::pin::Pin<&mut Self>, _: &mut std::task::Context<'_>) -> std::task::Poll<()> {
            panic!("队列(queue)不能轮询(poll)原值");
        }
    }
    impl Drop for CountDrop {
        fn drop(&mut self) { self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); }
    }
    let drops = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let pool = TaskPoolQueue::new(random_zero);
    let first = create(CountDrop(drops.clone()), NoSchedule, (), TaskOptions::plain()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    let id = first.runnable.id();
    pool.try_push(first.runnable).unwrap_or_else(|_| panic!("提交(submission)失败"));
    let batch = match pool.close() { BatchAttempt::Ready(batch) => batch, _ => panic!("关闭(close)必须取回原值") };
    assert_eq!(pool.len(), 0);
    assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 0);
    assert_eq!(batch.into_iter().next().unwrap().id(), id);
    assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 1);
    assert!(matches!(pool.close(), BatchAttempt::Closed));
    let second_pool = TaskPoolQueue::new(random_zero);
    let second = create(CountDrop(drops.clone()), NoSchedule, (), TaskOptions::plain()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    second_pool.try_push(second.runnable).unwrap_or_else(|_| panic!("提交(submission)失败"));
    drop(second_pool);
    assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 2);
}

/// @test T15;@api TaskQueue::drop。
/// 调度(Schedule)在队列析构(drop)中展开(unwind)时,剩余节点(node)仍须退出自持有。
#[test]
fn test_local_queue_drop_unwind_returns_remaining_tickets() {
    struct PanicFirst {
        calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,
        tx: std::sync::mpsc::Sender<Runnable>,
    }
    impl Schedule for PanicFirst {
        fn schedule(&self, task: Runnable) {
            if self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 { panic!("first-schedule"); }
            self.tx.send(task).unwrap_or_else(|_| panic!("通道(channel)已关闭"));
        }
    }
    let owner = pi_async_task::TaskThread::new();
    let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let metadata = std::sync::Arc::new(());
    let (tx, rx) = std::sync::mpsc::channel();
    let a = pi_async_task::create_local(&owner, std::future::pending::<()>(), PanicFirst { calls: calls.clone(), tx: tx.clone() }, metadata.clone(), TaskOptions::intrusive()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    let b = pi_async_task::create_local(&owner, std::future::pending::<()>(), PanicFirst { calls: calls.clone(), tx }, metadata.clone(), TaskOptions::intrusive()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    let mut queue = pi_async_task_queue::TaskQueue::new(&owner);
    queue.push_back(a.runnable).unwrap_or_else(|_| panic!("入队(enqueue)失败"));
    queue.push_back(b.runnable).unwrap_or_else(|_| panic!("入队(enqueue)失败"));
    let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(queue))).unwrap_err();
    assert_eq!(panic.downcast_ref::<&str>(), Some(&"first-schedule"));
    owner.close();
    while let Ok(task) = rx.try_recv() { drop(task); }
    drop((a.control, a.join, b.control, b.join));
    assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 2);
    assert_eq!(std::sync::Arc::strong_count(&metadata), 1);
}

/// @test T23/T24;@api TaskPoolQueue::try_push/try_take_batch。
/// 随机源(random source)在同线程(thread)重入接入,单次try_lock须立即Busy且原值不丢失。
#[cfg(feature = "pool")]
#[test]
fn test_pool_reentrant_access_is_busy_without_consuming_task() {
    use pi_async_task_queue::{BatchAttempt, ExternalTaskQueue, TaskPoolQueue};
    thread_local! {
        static POOL: std::cell::RefCell<Option<std::sync::Weak<TaskPoolQueue>>> = const { std::cell::RefCell::new(None) };
        static CHECKED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    }
    fn random_reenter() -> u64 {
        let pool = POOL.with(|slot| slot.borrow().as_ref().unwrap().upgrade().unwrap());
        assert!(matches!(pool.try_take_batch(), BatchAttempt::Busy));
        let parts = create(std::future::pending::<()>(), NoSchedule, (), TaskOptions::plain()).unwrap_or_else(|_| panic!("创建(creation)失败"));
        let id = parts.runnable.id();
        let error = match pool.try_push(parts.runnable) { Err(error) => error, Ok(_) => panic!("占用接入(busy access)不得成功") };
        assert_eq!(error.cause, pi_async_task_queue::ExternalPushErrorKind::Busy);
        assert_eq!(error.task.id(), id);
        CHECKED.with(|checked| checked.set(true));
        0
    }
    let pool = std::sync::Arc::new(TaskPoolQueue::new(random_reenter));
    POOL.with(|slot| *slot.borrow_mut() = Some(std::sync::Arc::downgrade(&pool)));
    let parts = create(std::future::pending::<()>(), NoSchedule, (), TaskOptions::plain()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    pool.try_push(parts.runnable).unwrap_or_else(|_| panic!("提交(submission)失败"));
    assert!(matches!(pool.try_take_batch(), BatchAttempt::Ready(_)));
    assert!(CHECKED.with(std::cell::Cell::get));
    assert_eq!(pool.len(), 0);
    POOL.with(|slot| *slot.borrow_mut() = None);
}

/// @test T24/T113/T119;@api TaskPoolQueue::try_take_batch。
/// 随机源(random source)在已移出一项后展开(unwind),先释放接入锁(access lock),
/// 再归还前缀持有(Runnable);其调度(Schedule)重入可取回剩余项,且不轮询(poll)原值。
#[cfg(feature = "pool")]
#[test]
fn test_pool_random_panic_unlocks_before_returning_taken_tasks() {
    use pi_async_task_queue::{BatchAttempt, ExternalTaskQueue, TaskPoolQueue};
    use std::sync::{Arc, Weak};
    thread_local! {
        static RANDOM_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    }
    fn panic_on_second_call() -> u64 {
        RANDOM_CALLS.with(|calls| {
            let previous = calls.get();
            calls.set(previous + 1);
            if previous == 1 { panic!("random-after-prefix"); }
        });
        0
    }
    struct Reenter {
        pool: Weak<TaskPoolQueue>,
        tx: std::sync::mpsc::Sender<(Runnable, BatchAttempt)>,
    }
    impl Schedule for Reenter {
        fn schedule(&self, task: Runnable) {
            let pool = self.pool.upgrade().unwrap();
            let attempt = pool.try_take_batch();
            self.tx.send((task, attempt)).unwrap_or_else(|_| panic!("清理交付(cleanup dispatch)失败"));
        }
    }
    RANDOM_CALLS.with(|calls| calls.set(0));
    let owner = pi_async_task::TaskThread::new();
    let pool = Arc::new(TaskPoolQueue::new(panic_on_second_call));
    let (tx, rx) = std::sync::mpsc::channel();
    let first = pi_async_task::create_local(&owner, std::future::pending::<()>(),
        Reenter { pool: Arc::downgrade(&pool), tx: tx.clone() }, (), TaskOptions::plain())
        .unwrap_or_else(|_| panic!("创建(creation)失败"));
    let second = pi_async_task::create_local(&owner, std::future::pending::<()>(),
        Reenter { pool: Arc::downgrade(&pool), tx }, (), TaskOptions::plain())
        .unwrap_or_else(|_| panic!("创建(creation)失败"));
    let ids = [first.runnable.id(), second.runnable.id()];
    pool.try_push(first.runnable).unwrap_or_else(|_| panic!("提交(submission)失败"));
    pool.try_push(second.runnable).unwrap_or_else(|_| panic!("提交(submission)失败"));
    let failure = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| pool.try_take_batch()));
    let returned = rx.try_recv();
    let remaining = pool.len();
    owner.close();
    let failure = match failure { Err(failure) => failure, Ok(_) => panic!("随机源恐慌(random-source panic)未传播") };
    assert_eq!(failure.downcast_ref::<&str>(), Some(&"random-after-prefix"));
    let (cleanup, attempt) = returned.unwrap_or_else(|_| panic!("前缀持有(Runnable)未归还"));
    assert_eq!(cleanup.id(), ids[0]);
    let batch = match attempt { BatchAttempt::Ready(batch) => batch, _ => panic!("接入锁(access lock)未先释放") };
    assert_eq!(batch.len(), 1);
    assert_eq!(batch.into_iter().next().unwrap().id(), ids[1]);
    assert_eq!(remaining, 0);
    assert!(rx.try_recv().is_err());
}

/// @test T1/T2/T3/T4;@api TaskBatch::from_tasks/len/is_empty/into_iter。
/// 批次(batch)接管原序列,不轮询(poll)、克隆(clone)或改变任务(Task)身份。
#[test]
fn test_batch_transfers_original_order_and_identity() {
    let first = create(std::future::pending::<()>(), NoSchedule, (), TaskOptions::plain()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    let second = create(std::future::pending::<()>(), NoSchedule, (), TaskOptions::plain()).unwrap_or_else(|_| panic!("创建(creation)失败"));
    let ids = [first.runnable.id(), second.runnable.id()];
    let batch = TaskBatch::from_tasks(VecDeque::from([first.runnable, second.runnable]));
    assert_eq!(batch.len(), 2);
    assert!(!batch.is_empty());
    let actual: Vec<_> = batch.into_iter().map(|task| task.id()).collect();
    assert_eq!(actual, ids);
    let empty = TaskBatch::from_tasks(VecDeque::new());
    assert!(empty.is_empty());
}