pi-async-runtime 0.1.5

单线程串行及并发异步运行时的静态组合
Documentation
//! 用公开构造验证内部任务队列(internal task queue)与原本地派发和定时的组合。

use pi_async_runtime::{
    CloseState, ConcurrentRuntime, DefaultIdlePolicy, LocalTaskDispatch, ManualClock, NoHooks,
    RuntimeBlockOn, RuntimeControl, RuntimeOptions, RuntimeQuery, RuntimeQueues, RuntimeTime,
    SerialRuntime, TaskDispatch,
};
use pi_async_task::{definitions::TaskOwnerId, Runnable};
use pi_async_task_queue::{InternalTaskQueue, QueueCleanupProgress, QueuePushError, TaskQueue};
use std::{
    cell::Cell,
    future::{poll_fn, Future},
    panic::{catch_unwind, panic_any, AssertUnwindSafe},
    pin::pin,
    rc::Rc,
    sync::{atomic::{AtomicUsize, Ordering}, Arc},
    task::Poll,
    time::Duration,
};

/// 一份具体内部队列(internal task queue)的管理者,完全委托原队列的保管和退出。
struct WrappedReadyQueue(TaskQueue);
impl InternalTaskQueue for WrappedReadyQueue {
    fn try_push_internal_front(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        self.0.try_push_internal_front(task)
    }
    fn try_push_internal_back(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        self.0.try_push_internal_back(task)
    }
    fn pop_internal_front(&mut self) -> Option<Runnable> {
        self.0.pop_internal_front()
    }
    fn internal_len(&self) -> usize {
        self.0.internal_len()
    }
    fn is_internal_closed(&self) -> bool {
        self.0.is_internal_closed()
    }
    fn internal_owner_id(&self) -> Option<TaskOwnerId> {
        self.0.internal_owner_id()
    }
    fn clear_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.0.clear_internal()
    }
    fn close_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.0.close_internal()
    }
}

/// 同一静态本地权限可提交非 Send 的任务,并登记到这份运行时的默认定时任务队列。
fn spawn_and_time_local<R: RuntimeBlockOn + LocalTaskDispatch + RuntimeTime + RuntimeQuery>(
    runtime: &R,
) {
    runtime.block_on(async {
        let local = Rc::new(40_u32);
        let result = R::spawn_local(async move { *local + 2 }).unwrap();
        let mut sleep = pin!(R::sleep_local(Duration::from_millis(1)).unwrap());
        poll_fn(|cx| {
            assert!(sleep.as_mut().poll(cx).is_pending());
            assert_eq!(runtime.timer_registration_count(), 1);
            Poll::Ready(())
        })
        .await;
        sleep.await.unwrap();
        assert_eq!(result.await.unwrap(), 42);
    });
}

/// 无效固定组合早于实际构造回调,默认计时随着合法新队列类型使用同一所属域。
#[test]
fn internal_queue_factory_keeps_local_timer_and_admission() {
    let options = RuntimeOptions::default();
    let calls = Cell::new(0);
    let invalid = RuntimeQueues::default().with_internal_factory(|context| {
        calls.set(calls.get() + 1);
        Ok(WrappedReadyQueue(context.task_queue()))
    });
    let error = SerialRuntime::with_queues(options, invalid).err().unwrap();
    assert_eq!(*error.current_context(), pi_result::ErrorKind::InvalidInput);
    assert!(format!("{error:?}").contains("内部任务队列"));
    assert_eq!(calls.get(), 0);
    let invalid = RuntimeQueues::default()
        .without_timer()
        .with_internal_factory(|context| {
            calls.set(calls.get() + 1);
            Ok(WrappedReadyQueue(context.task_queue()))
        });
    let explicit_error = SerialRuntime::with_components_and_queues(
        ManualClock,
        DefaultIdlePolicy,
        NoHooks,
        options,
        invalid,
    )
    .err()
    .unwrap();
    assert_eq!(
        *explicit_error.current_context(),
        pi_result::ErrorKind::InvalidInput
    );
    assert!(format!("{explicit_error:?}").contains("内部任务队列"));
    assert_eq!(calls.get(), 0);

    pi_clock_manual::global::try_init().unwrap();
    let mut runtime = ConcurrentRuntime::with_queues(
        options,
        RuntimeQueues::default().with_internal_factory(|context| {
            calls.set(calls.get() + 1);
            Ok(WrappedReadyQueue(context.task_queue()))
        }),
    )
    .unwrap();
    assert_eq!(calls.get(), 1);
    let result = runtime.spawn(async { "原普通任务" }).unwrap();
    assert_eq!(runtime.block_on(result).unwrap(), "原普通任务");
    spawn_and_time_local(&runtime);
    runtime.request_close();
    assert!(runtime.run_once().unwrap().service_closed);
    assert_eq!(runtime.close_state(), CloseState::Completed);
}

/// 一个已准备的开放空队列,无预绑定所属域(owner domain),保管同一可执行句柄(Runnable)。
#[derive(Default)]
struct UnboundReadyQueue {
    owned: std::collections::VecDeque<Runnable>,
    closed: bool,
    events: Rc<Cell<(usize, usize, usize)>>,
    push_panic: Option<Arc<u32>>,
}
impl InternalTaskQueue for UnboundReadyQueue {
    fn try_push_internal_front(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        if self.closed {
            return Err(QueuePushError {
                task,
                cause: pi_async_task_queue::QueuePushErrorKind::Closed,
            });
        }
        self.owned.push_front(task);
        Ok(())
    }
    fn try_push_internal_back(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        if self.closed {
            return Err(QueuePushError {
                task,
                cause: pi_async_task_queue::QueuePushErrorKind::Closed,
            });
        }
        if let Some(payload) = self.push_panic.take() {
            // 尚未进入队列。展开时本次入参自行归还原任务的清理责任。
            panic_any(payload);
        }
        let (pushed, popped, closed) = self.events.get();
        self.events.set((pushed + 1, popped, closed));
        self.owned.push_back(task);
        Ok(())
    }
    fn pop_internal_front(&mut self) -> Option<Runnable> {
        if let Some(task) = self.owned.pop_front() {
            let (pushed, popped, closed) = self.events.get();
            self.events.set((pushed, popped + 1, closed));
            Some(task)
        } else {
            None
        }
    }
    fn internal_len(&self) -> usize {
        self.owned.len()
    }
    fn internal_owner_id(&self) -> Option<TaskOwnerId> {
        None
    }
    fn is_internal_closed(&self) -> bool {
        self.closed
    }
    fn clear_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.owned.clear();
        Ok(QueueCleanupProgress::Complete)
    }
    fn close_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.closed = true;
        let (pushed, popped, closed) = self.events.get();
        self.events.set((pushed, popped, closed + 1));
        self.clear_internal()
    }
}

/// 现成队列按值移交,可与显式省略两种来源组合,原关闭(close)职责继续有效。
#[test]
fn internal_queue_by_value_composes_with_omitted_sources() {
    let events = Rc::new(Cell::new((0, 0, 0)));
    let queue = UnboundReadyQueue {
        events: Rc::clone(&events),
        ..UnboundReadyQueue::default()
    };
    let mut runtime = ConcurrentRuntime::with_queues(
        RuntimeOptions::default(),
        RuntimeQueues::default()
            .without_timer()
            .with_internal(queue)
            .without_idle(),
    )
    .unwrap();
    let result = runtime.spawn(async move { 201 }).unwrap();
    assert_eq!(runtime.block_on(result).unwrap(), 201);
    assert_eq!(events.get(), (1, 1, 0));
    runtime.request_close();
    assert!(runtime.run_once().unwrap().service_closed);
    assert_eq!(runtime.close_state(), CloseState::Completed);
    assert_eq!(events.get(), (1, 1, 1));
}

/// 捕获尚未入队任务的析构(drop),验证原计算只退出一次。
struct ObserveFutureDrop(Arc<AtomicUsize>);

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

/// 普通任务已接纳(admission),但自定义内部任务队列在入队前展开(unwinding)。
/// `run_once` 须传播原恐慌(panic)载荷,归还入队预留,并结清同一任务。
#[test]
fn test_internal_queue_push_panic_returns_original_payload() {
    let payload = Arc::new(31_u32);
    let queue = UnboundReadyQueue {
        push_panic: Some(Arc::clone(&payload)),
        ..UnboundReadyQueue::default()
    };
    let mut runtime = ConcurrentRuntime::with_queues(
        RuntimeOptions::default(),
        RuntimeQueues::default().without_timer().without_idle().with_internal(queue),
    )
    .unwrap();
    let dropped = Arc::new(AtomicUsize::new(0));
    let observe = ObserveFutureDrop(Arc::clone(&dropped));
    let result = runtime
        .spawn(async move {
            let _observe = observe;
            panic!("原任务尚未入队,不可被轮询");
        })
        .unwrap();
    assert_eq!(runtime.external_task_count(), 1);
    let panic = catch_unwind(AssertUnwindSafe(|| runtime.run_once()))
        .expect_err("本轮推进须传播原队列的恐慌");
    assert!(Arc::ptr_eq(panic.downcast_ref::<Arc<u32>>().unwrap(), &payload));
    assert_eq!(runtime.external_task_count(), 0);
    // 已撤回原入队预留。只留下一个交给所属线程(owner thread)的清理票。
    assert_eq!(runtime.internal_task_count(), 1);
    assert_eq!(runtime.in_flight_task_count(), 1);
    assert_eq!(dropped.load(Ordering::Relaxed), 0);
    assert!(runtime.block_on(result).is_err());
    runtime.request_close();
    assert!(runtime.run_once().unwrap().service_closed);
    assert_eq!(runtime.close_state(), CloseState::Completed);
    assert_eq!(runtime.internal_task_count(), 0);
    assert_eq!(runtime.in_flight_task_count(), 0);
    assert_eq!(dropped.load(Ordering::Relaxed), 1);
}