pi-async-task 0.1.4

异步任务(Task)的基础类型(type)与生命周期(lifecycle)阶段定义
Documentation
//! 通过公开节点操作验证 `QueueEntry` 对原可执行句柄(Runnable)的保管。

use intrusive_collections::linked_list::LinkOps;
use intrusive_collections::{Adapter, DefaultPointerOps, LinkedList, LinkedListLink, UnsafeRef};
use pi_async_task::definitions::{CancelRequestStatus, FutureDropStatus, RunOutcome, TerminationKind};
use pi_async_task::{create, create_local, QueueEntry, Runnable, Schedule, TaskOptions, TaskThread};
use std::future::{ready, Future};
use std::ptr::NonNull;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use std::sync::Arc;
use std::task::{Context, Poll, Waker};

/// 用公开的节点投影把两个互逆地址操作交给真实链表(linked list)。
struct EntryAdapter {
    links: LinkOps,
    pointers: DefaultPointerOps<UnsafeRef<QueueEntry>>,
}

// SAFETY: 仅对原可执行句柄(Runnable)保活的节点使用公开的两个互逆投影。
unsafe impl Adapter for EntryAdapter {
    type LinkOps = LinkOps;
    type PointerOps = DefaultPointerOps<UnsafeRef<QueueEntry>>;

    unsafe fn get_value(&self, link: NonNull<LinkedListLink>) -> *const QueueEntry {
        // SAFETY: 链中链接(link)都来自本适配器的 get_link,保管槽持有原值。
        unsafe { QueueEntry::node_from_link(link) }.as_ptr()
    }

    unsafe fn get_link(&self, value: *const QueueEntry) -> NonNull<LinkedListLink> {
        let node = NonNull::new(value.cast_mut()).expect("链节点地址有效");
        // SAFETY: 节点(node)由存入的原值保活,且链仅由本线程访问。
        unsafe { QueueEntry::link_from_node(node) }
    }

    fn link_ops(&self) -> &Self::LinkOps {
        &self.links
    }

    fn link_ops_mut(&mut self) -> &mut Self::LinkOps {
        &mut self.links
    }

    fn pointer_ops(&self) -> &Self::PointerOps {
        &self.pointers
    }
}

/// 测试按真实链表(linked list)保管节点,并在断言提前退出时仍归还链中持有。
struct Entries<'owner> {
    owner: &'owner TaskThread,
    entries: LinkedList<EntryAdapter>,
}

impl<'owner> Entries<'owner> {
    /// 以原所属域(owner domain)建立空链,所有节点操作由本测试线程发起。
    fn new(owner: &'owner TaskThread) -> Self {
        let adapter = EntryAdapter { links: LinkOps, pointers: DefaultPointerOps::new() };
        Self { owner, entries: LinkedList::new(adapter) }
    }

    /// 移交唯一原值给真实存入操作,返回节点地址供同址比较。
    fn push_back(&mut self, task: Runnable) -> NonNull<QueueEntry> {
        // SAFETY: 本线程独占即将入链的节点(node),成功后本链负责摘除并取回。
        let node = unsafe { QueueEntry::store_with_unbound(task, self.owner.id()) }
            .unwrap_or_else(|_| panic!("合法原值应能存入"));
        // SAFETY: 保管槽中的原值保活节点,原链接(link)空闲且由本链独占接管。
        self.entries.push_back(unsafe { UnsafeRef::from_raw(node.as_ptr()) });
        node
    }

    /// 先经真实链表完整摘链(unlink),再把一次取回权交给生产接口。
    fn pop_front(&mut self) -> Option<Runnable> {
        let node = self.entries.pop_front()?;
        // SAFETY: 已完整摘链(unlink),仍由该节点内的原值保活,且这份取回权只使用一次。
        Some(unsafe { QueueEntry::take_with_unbound(NonNull::from(&*node), self.owner.id()) })
    }
}

impl Drop for Entries<'_> {
    fn drop(&mut self) {
        while let Some(task) = self.pop_front() {
            drop(task);
        }
    }
}

/// 观测是否发生额外调度(scheduling)。收到的值沿原可执行句柄(Runnable)的析构路径处理。
#[derive(Clone, Default)]
struct ScheduleCalls(Arc<AtomicUsize>);

impl Schedule for ScheduleCalls {
    fn schedule(&self, task: Runnable) {
        self.0.fetch_add(1, SeqCst);
        drop(task);
    }
}

/// 放进原异步计算(Future),记录原值实际析构次数。
struct DropCount(Arc<AtomicUsize>);

impl Drop for DropCount {
    fn drop(&mut self) {
        self.0.fetch_add(1, SeqCst);
    }
}

/// 验证两个实际节点按队首顺序交还。外线程重复唤醒(wake-up)及取消(cancellation)期间,
/// 原可执行句柄(Runnable)一直由链中节点保管。摘链后保留原地址重新入链,
/// 取消原值只清理一次,已接纳值经原结果句柄(result handle)交付输出。
#[test]
fn test_mixed_entries_preserve_order_and_original_state() {
    let owner = TaskThread::new();
    let schedule = ScheduleCalls::default();
    let polls = Arc::new(AtomicUsize::new(0));
    let drops = Arc::new(AtomicUsize::new(0));
    let original = create(
        {
            let polls = Arc::clone(&polls);
            let drop_count = DropCount(Arc::clone(&drops));
            async move {
                let _keep = &drop_count;
                polls.fetch_add(1, SeqCst);
            }
        },
        schedule.clone(),
        (),
        TaskOptions::intrusive_local_and_mpsc(),
    )
    .unwrap_or_else(|_| panic!("创建未绑定任务"));
    let mut entries = Entries::new(&owner);
    let original_id = original.runnable.id();
    assert_eq!(original.runnable.snapshot().owner, None);
    let first_node = entries.push_back(original.runnable);

    let local = create_local(&owner, ready(73_u32), schedule.clone(), (), TaskOptions::intrusive())
        .unwrap_or_else(|_| panic!("创建本地任务"));
    let registration = local.runnable.admit(&owner).expect("接纳本地任务");
    let local_snapshot = local.runnable.snapshot();
    let local_join = local.join;
    entries.push_back(local.runnable);

    std::thread::spawn(move || {
        let waker = original.control.waker();
        waker.wake_by_ref();
        waker.wake_by_ref();
        original.control.cancel();
    })
    .join()
    .expect("外线程完成控制请求");
    assert_eq!(schedule.0.load(SeqCst), 0);
    assert_eq!(drops.load(SeqCst), 0);

    let original = entries.pop_front().expect("队首是未绑定任务");
    assert_eq!(original.id(), original_id);
    let snapshot = original.snapshot();
    assert_eq!(snapshot.owner, None);
    assert!(!snapshot.admitted);
    assert_eq!(snapshot.cancellation, CancelRequestStatus::Recorded);
    assert_eq!(entries.push_back(original), first_node);

    let local = entries.pop_front().expect("接下来取回原本地任务");
    assert_eq!(local.snapshot(), local_snapshot);
    assert_eq!(
        local.run(&owner).unwrap_or_else(|_| panic!("运行本地任务")),
        RunOutcome::Finished(TerminationKind::Completed),
    );
    let mut local_join = std::pin::pin!(local_join);
    assert!(matches!(
        local_join.as_mut().poll(&mut Context::from_waker(Waker::noop())),
        Poll::Ready(Ok(73)),
    ));

    let original = entries.pop_front().expect("队尾是重新入链的原任务");
    assert_eq!(original.snapshot(), snapshot);
    assert_eq!(
        original.run(&owner).unwrap_or_else(|_| panic!("清理原任务")),
        RunOutcome::Finished(TerminationKind::Cancelled),
    );
    assert_eq!(polls.load(SeqCst), 0);
    assert_eq!(drops.load(SeqCst), 1);
    assert!(entries.pop_front().is_none());
    assert_eq!(schedule.0.load(SeqCst), 0);
    assert_eq!(owner.live_tasks(), 0);
    drop(registration);
}

/// 真实链表(linked list)中仍保管未绑定任务时,配对摘链和取回后可以直接放弃原值。
/// 控制句柄(control handle)继续存续,仍可观察原异步计算(Future)已清理且从未接纳。
#[test]
fn test_remaining_entry_can_be_released_without_admission() {
    let owner = TaskThread::new();
    let drops = Arc::new(AtomicUsize::new(0));
    let schedule = ScheduleCalls::default();
    let original = create(
        {
            let drop_count = DropCount(Arc::clone(&drops));
            async move {
                let _keep = &drop_count;
                std::future::pending::<()>().await;
            }
        },
        schedule.clone(),
        (),
        TaskOptions::intrusive(),
    )
    .unwrap_or_else(|_| panic!("创建待清理任务"));
    let mut entries = Entries::new(&owner);
    let id = original.runnable.id();
    entries.push_back(original.runnable);
    assert_eq!(drops.load(SeqCst), 0);

    let task = entries.pop_front().expect("退出时取回尚未运行的任务");
    assert_eq!(task.id(), id);
    drop(task);
    let snapshot = original.control.snapshot();
    assert_eq!(snapshot.owner, None);
    assert!(!snapshot.admitted);
    assert_eq!(snapshot.termination, Some(TerminationKind::Abandoned));
    assert_eq!(snapshot.future_drop, FutureDropStatus::Confirmed);
    assert!(entries.pop_front().is_none());
    assert_eq!(schedule.0.load(SeqCst), 0);
    assert_eq!(drops.load(SeqCst), 1);
}

/// 旧入口继续拒绝未绑定值。配对新入口可撤销尚未入链的存入,并复用同址节点。
#[test]
fn test_unlinked_entry_can_be_returned_and_reused() {
    let owner = TaskThread::new();
    let task = create(ready(()), ScheduleCalls::default(), (), TaskOptions::intrusive())
        .unwrap_or_else(|_| panic!("创建未绑定任务"))
        .runnable;
    let before = task.snapshot();
    // SAFETY: 原可执行句柄(Runnable)唯一,节点(node)尚未入链,当前是队列所属线程。
    let task = unsafe { QueueEntry::store(task, owner.id()) }.unwrap_err();
    let mut address = None;
    let mut task = task;
    for _ in 0..2 {
        // SAFETY: 当前线程独占原节点。每轮成功存入后在尚未入链时立即取回。
        let node = unsafe { QueueEntry::store_with_unbound(task, owner.id()) }
            .unwrap_or_else(|_| panic!("存入未绑定任务"));
        // SAFETY: 仍在当前所属线程,从未入链,且本节点保管着同一原值。
        task = unsafe { QueueEntry::take_with_unbound(node, owner.id()) };
        assert_eq!(task.snapshot(), before);
        if let Some(previous) = address {
            assert_eq!(node, previous);
        }
        address = Some(node);
    }
    assert_eq!(
        task.run(&owner).unwrap_or_else(|_| panic!("运行原任务")),
        RunOutcome::Finished(TerminationKind::Completed),
    );
}

/// 其它所属域及无本地链接(link)都必须返还同一原值,并保留原状态。
#[test]
fn test_entry_refuses_foreign_owner_and_missing_link() {
    let owner = TaskThread::new();
    let foreign = TaskThread::new();
    let task = create_local(&foreign, ready(()), ScheduleCalls::default(), (), TaskOptions::intrusive())
        .unwrap_or_else(|_| panic!("创建属于另一域的任务"))
        .runnable;
    let before = task.snapshot();
    // SAFETY: 两域属当前线程,节点(node)从未入链,调用者持有唯一原值及独占访问权。
    let task = unsafe { QueueEntry::store_with_unbound(task, owner.id()) }.unwrap_err();
    assert_eq!(task.snapshot(), before);
    assert_eq!(
        task.run(&foreign).unwrap_or_else(|_| panic!("在原所属域运行")),
        RunOutcome::Finished(TerminationKind::Completed),
    );

    for options in [TaskOptions::plain(), TaskOptions::intrusive_mpsc()] {
        let task = create(ready(()), ScheduleCalls::default(), (), options)
            .unwrap_or_else(|_| panic!("创建无本地链接的任务"))
            .runnable;
        let before = task.snapshot();
        // SAFETY: 合法提交唯一原值;由生产入口检查它是否携带所需节点(node)。
        let task = unsafe { QueueEntry::store_with_unbound(task, owner.id()) }.unwrap_err();
        assert_eq!(task.snapshot(), before);
        assert_eq!(
            task.run(&owner).unwrap_or_else(|_| panic!("运行无本地链接的原任务")),
            RunOutcome::Finished(TerminationKind::Completed),
        );
    }
}