pi-async-task-queue 0.1.5

任务队列接口及默认实现
Documentation
#![cfg(not(target_arch = "wasm32"))]

use pi_async_task::{create, Runnable, Schedule, TaskOptions};
use pi_async_task_queue::{
    BatchAttempt, ExternalPushErrorKind, ExternalQueueManager, ExternalTaskQueue,
    QueueCleanupProgress, QueueNotifier, SerialQueueIndex, WeightedSerialParQueue,
    WeightedSerialParQueueHandle,
};
use std::{
    future::Future,
    pin::Pin,
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
    task::{Context, Poll},
};

struct NoSchedule;

impl Schedule for NoSchedule {
    fn schedule(&self, _: Runnable) {
        panic!("队列(queue)清理期间不得调度(schedule)");
    }
}

struct CountDrop(Arc<AtomicUsize>);

impl Future for CountDrop {
    type Output = ();

    fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<()> {
        panic!("队列(queue)清理期间不得轮询(poll)");
    }
}

impl Drop for CountDrop {
    fn drop(&mut self) {
        self.0.fetch_add(1, Ordering::Relaxed);
    }
}

fn task(drops: &Arc<AtomicUsize>) -> Runnable {
    create(
        CountDrop(Arc::clone(drops)),
        NoSchedule,
        (),
        TaskOptions::plain(),
    )
    .ok()
    .expect("创建测试任务")
    .runnable
}

struct Notify;

impl QueueNotifier for Notify {
    fn notify(&self) {}
}

fn submit_serial(
    queue: &WeightedSerialParQueueHandle,
    index: SerialQueueIndex,
    future: impl Future<Output = ()> + Send + 'static,
) {
    let submission = queue.prepare_serial(index).unwrap();
    let (task, publication) = submission
        .create(future, NoSchedule, (), TaskOptions::plain(), Notify)
        .ok()
        .unwrap();
    assert!(publication.publish(task.runnable).is_ok());
}

#[test]
fn close_drains_original_tasks_then_reports_native_allocation() {
    let mut owner = WeightedSerialParQueue::new();
    let handle = owner.handle();
    let drops = Arc::new(AtomicUsize::new(0));
    let old = handle.clone();
    drop(old);
    assert!(handle.try_push(task(&drops)).is_ok());
    assert_eq!(handle.len(), 1);

    let error = owner.close().err().expect("原生池分配保留");
    assert_eq!(*error.current_context(), pi_result::ErrorKind::Unsupported);
    assert_eq!(drops.load(Ordering::Relaxed), 1);
    assert_eq!(handle.len(), 0);
    assert!(matches!(handle.try_take_batch(), BatchAttempt::Closed));

    let rejected = task(&drops);
    let id = rejected.id();
    let error = handle.try_push(rejected).err().expect("停收后返还原值");
    assert_eq!(error.cause, ExternalPushErrorKind::Closed);
    assert_eq!(error.task.id(), id);
    drop(error);
    assert_eq!(drops.load(Ordering::Relaxed), 2);
    assert!(owner.close().is_err());
}

/// 普通取出保管同组占用,即使管理者退出也由原异步计算(Future)真实释放后接续清理。
#[test]
fn selected_serial_task_keeps_its_own_cleanup_responsibility() {
    let mut owner = WeightedSerialParQueue::new();
    let handle = owner.handle();
    let group = SerialQueueIndex::new(0).unwrap();
    let first = Arc::new(AtomicUsize::new(0));
    let second = Arc::new(AtomicUsize::new(0));
    submit_serial(&handle, group, CountDrop(Arc::clone(&first)));
    let BatchAttempt::Ready(batch) = handle.try_take_batch() else {
        panic!("应取出首项");
    };
    let first_task = batch.into_iter().next().unwrap();
    // 持有首项期间仍可提交同组后项。
    submit_serial(&handle, group, CountDrop(Arc::clone(&second)));
    assert!(matches!(handle.try_take_batch(), BatchAttempt::WouldBlock));
    let pending = owner.close().err().expect("公开关闭还在等待实际串行占用");
    assert_eq!(*pending.current_context(), pi_result::ErrorKind::Busy);
    assert!(pi_async_task_queue::weighted_close_pending(
        &pending,
        || handle.clone()
    ));
    let unrelated = WeightedSerialParQueue::new();
    assert!(!pi_async_task_queue::weighted_close_pending(
        &pending,
        || unrelated.handle()
    ));
    assert!(!pi_async_task_queue::weighted_close_pending::<
        pi_async_task_queue::MpscTaskQueueHandle,
    >(&pending, || panic!("其它来源无需取得共享句柄"),));
    let pending = ExternalQueueManager::close(&mut owner)
        .err()
        .expect("通用关闭也返回实际待处理错误");
    assert_eq!(*pending.current_context(), pi_result::ErrorKind::Busy);
    assert_eq!(handle.len(), 1);

    drop(owner);
    assert_eq!(second.load(Ordering::Acquire), 0);
    drop(first_task);
    assert_eq!(first.load(Ordering::Acquire), 1);
    assert_eq!(second.load(Ordering::Acquire), 1);
    assert_eq!(handle.len(), 0);
    assert!(matches!(handle.try_take_batch(), BatchAttempt::Closed));
}

struct DuringClear {
    take: Option<Box<dyn FnOnce() + Send>>,
}

impl Future for DuringClear {
    type Output = ();

    fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<()> {
        panic!("清理不轮询(poll)业务");
    }
}

impl Drop for DuringClear {
    fn drop(&mut self) {
        self.take.take().unwrap()();
    }
}

/// 清理首项时即使仍在原析构(drop)中,后项也可从同一串行队列取出。
#[test]
fn clear_releases_native_handle_before_dropping_original_task() {
    let mut owner = WeightedSerialParQueue::new();
    let handle = owner.handle();
    let group = SerialQueueIndex::new(0).unwrap();
    let next = Arc::new(AtomicUsize::new(0));
    let check = handle.clone();
    let next_count = Arc::clone(&next);
    submit_serial(
        &handle,
        group,
        DuringClear {
            take: Some(Box::new(move || {
                // 模拟清理已经开始后才提交同组后项。
                submit_serial(&check, group, CountDrop(Arc::clone(&next_count)));
                let BatchAttempt::Ready(batch) = check.try_take_batch() else {
                    panic!("清理释放原生句柄后,同组可取");
                };
                drop(batch);
                assert_eq!(next_count.load(Ordering::Acquire), 1);
            })),
        },
    );
    assert!(matches!(owner.clear(), Ok(QueueCleanupProgress::Complete)));
    assert_eq!(next.load(Ordering::Acquire), 1);
    assert_eq!(handle.len(), 0);
}

/// 开放清理(clear)可以清理本次调用开始后实际被取出的任务。
#[test]
fn open_clear_may_include_a_later_submission() {
    let mut owner = WeightedSerialParQueue::new();
    let handle = owner.handle();
    let later = Arc::new(AtomicUsize::new(0));
    let later_count = Arc::clone(&later);
    let producer = handle.clone();
    let group = SerialQueueIndex::new(0).unwrap();
    submit_serial(
        &handle,
        group,
        DuringClear {
            take: Some(Box::new(move || {
                assert!(producer.try_push(task(&later_count)).is_ok());
            })),
        },
    );

    assert!(matches!(owner.clear(), Ok(QueueCleanupProgress::Complete)));
    assert_eq!(later.load(Ordering::Acquire), 1);
    assert!(matches!(handle.try_take_batch(), BatchAttempt::Empty));
}

/// 用户析构(drop)展开时,原管理者退出的接续仍清理其余实际任务。
#[test]
fn owner_drop_continues_after_one_task_drop_panics() {
    let owner = WeightedSerialParQueue::new();
    let handle = owner.handle();
    let remaining = Arc::new(AtomicUsize::new(0));
    let group = SerialQueueIndex::new(0).unwrap();
    submit_serial(
        &handle,
        group,
        DuringClear {
            take: Some(Box::new(|| panic!("清理首项时展开"))),
        },
    );
    submit_serial(&handle, group, CountDrop(Arc::clone(&remaining)));

    let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(owner))).unwrap_err();
    assert_eq!(
        panic.downcast_ref::<&'static str>(),
        Some(&"清理首项时展开")
    );
    assert_eq!(remaining.load(Ordering::Acquire), 1);
    assert_eq!(handle.len(), 0);
}

/// 两份真实任务的串行发布权限不能相互替换。拒绝保留被误传的原任务。
#[test]
fn serial_publication_rejects_an_unrelated_runnable() {
    let mut owner = WeightedSerialParQueue::new();
    let handle = owner.handle();
    let group = SerialQueueIndex::new(0).unwrap();
    let drops = Arc::new(AtomicUsize::new(0));
    let (original, publication) = handle
        .prepare_serial(group)
        .unwrap()
        .create(
            CountDrop(Arc::clone(&drops)),
            NoSchedule,
            (),
            TaskOptions::plain(),
            Notify,
        )
        .ok()
        .unwrap();
    let other = task(&drops);
    let id = other.id();
    let error = publication
        .publish(other)
        .err()
        .expect("拒绝和本次创建不匹配的任意 Runnable");
    assert_eq!(error.cause, ExternalPushErrorKind::LinkMissing);
    assert_eq!(error.task.id(), id);
    assert_eq!(handle.len(), 0);
    drop(error);
    drop(original);
    assert_eq!(drops.load(Ordering::Acquire), 2);
    assert!(owner.close().is_err());
}