pi-async-executor 0.1.4

默认执行器的统一时钟与线程通知基础
Documentation
//! 以具体类型选择是否装配定时任务队列(timer task queue)与空闲任务队列(idle task queue)。
use crate::{
    clock::ExecutorClock, drive::TimerDelivery, parking::ThreadNotifier, timer::ExecutorTimer,
};
use pi_async_runtime_core::{definitions::RuntimeId, time::TimerAccess};
use pi_async_task::Runnable;
use pi_async_task_queue::{
    IdleQueueError, IdleQueueManager, IdleTake, IdleTaskQueue, QueueCleanupProgress,
    TimerQueueError, TimerQueueHandle, TimerTake, TimerTaskQueue,
};
use std::{cell::RefCell, convert::Infallible, marker::PhantomData, num::NonZeroUsize};

// @trace 1
/// 选择省略空闲任务队列(idle task queue)。空闲策略(idle policy)与限时休眠仍有效。
#[derive(Clone, Copy, Debug, Default)]
pub struct NoIdleQueue;

// @trace 2
/// 选择省略定时任务队列(timer task queue)。类型参数与执行器(executor)的时钟(clock)时刻匹配。
/// 普通定时派发(timed task dispatch)要求真实的定时来源。
///
/// ```compile_fail,E0599
/// use pi_async_executor::{routing::LocalReadySubmit, ExecutorHandle, NoIdleQueue, NoTimerQueue};
/// use pi_async_runtime_core::TaskConfig;
/// use pi_async_task_queue::MpscTaskQueueHandle;
/// use std::time::Duration;
/// fn unavailable<L: LocalReadySubmit>(handle: &ExecutorHandle<MpscTaskQueueHandle, NoIdleQueue, NoTimerQueue<()>, L>) {
///     handle.spawn_timing(async {}, Duration::ZERO, TaskConfig::<()>::default());
/// }
/// ```
///
/// 本地定时派发也要求真实的定时来源。
///
/// ```compile_fail,E0599
/// use pi_async_executor::{routing::LocalReadySubmit, ExecutorHandle, ExecutorLocal, NoIdleQueue, NoTimerQueue};
/// use pi_async_runtime_core::TaskConfig;
/// use pi_async_task_queue::MpscTaskQueueHandle;
/// use std::time::Duration;
/// fn unavailable<L: LocalReadySubmit>(handle: &ExecutorHandle<MpscTaskQueueHandle, NoIdleQueue, NoTimerQueue<()>, L>, local: &ExecutorLocal<NoTimerQueue<()>>) {
///     handle.spawn_timing_local(local, async {}, Duration::ZERO, TaskConfig::<()>::default());
/// }
/// ```
///
/// ```compile_fail,E0599
/// use pi_async_executor::{ExecutorLocal, NoTimerQueue};
/// fn unavailable(local: &ExecutorLocal<NoTimerQueue<()>>) {
///     local.try_push_timer((), ());
/// }
/// ```
pub struct NoTimerQueue<I>(PhantomData<fn() -> I>);

// 所属线程(owner thread)持有原空闲管理者。实装时用 Option<I> 支持一次取出;
// NoIdleQueue 为 ()。取得共享访问早于移走管理者。关闭借用原管理者,调用者处理原报告后再释放管理者。
// @trace 3
#[allow(private_bounds)]
pub trait IdleBinding: IdleOwnerOperations<Shared = Self::Handle> {
    type Handle: IdleAccess;
}

pub(crate) trait IdleOwnerOperations: Sized {
    type Owner;
    type Shared: IdleAccess;
    fn shared_idle(&self) -> Self::Shared;
    fn own_idle(self) -> Self::Owner;
    fn take_idle(slot: &mut Self::Owner) -> Option<Self>;
    fn close_idle(&mut self) -> pi_result::Result<()>;
}

// 实装时按原 IdleTaskQueue 取得数量、原清理结果和实际任务。省略时数量为零,
// 事件循环(event loop)依具体类型省去清理与取出。空闲派发仍要求真实 IdleTaskQueue。
// @trace 4
#[allow(private_bounds)]
pub trait IdleAccess: IdleHandleOperations + Clone + Send + Sync + 'static {}

pub(crate) trait IdleHandleOperations: Sized {
    const PRESENT: bool;
    fn idle_count(&self) -> usize;
    fn cleanup_idle(&self) -> pi_result::Result<(QueueCleanupProgress, bool)>;
    fn take_ready_idle(&self, max: NonZeroUsize) -> pi_result::RawResult<IdleTake, IdleQueueError>;
}

type Due<T> = (
    Option<<T as TimerOperations>::Entry>,
    Option<<T as TimerOperations>::Batch>,
);

// 实装时本地来源放入 RefCell<Option<T>>,计时访问和查询为对应的真实句柄;
// NoTimerQueue 的三项存储均为 (),无原到期任务可产生。先核计时访问身份,
// 再按原构造次序取得其它来源句柄和定时查询。已接管资源由原构造守卫(guard)结清。
// @trace 5
#[allow(private_bounds)]
pub trait TimerBinding: TimerOperations<TimePoint = Self::ClockInstant> {
    const PRESENT: bool;
    type ClockInstant;
}

pub(crate) trait TimerOperations: Sized + 'static {
    type TimePoint;
    type LocalTimer;
    type SharedAccess: Clone + Send + Sync + 'static;
    type SharedQuery: Clone + Send + Sync + 'static;
    type Entry;
    type Batch: IntoIterator<Item = Self::Entry>;
    fn shared_timer(
        timer: Option<&Self>,
        runtime: RuntimeId,
    ) -> pi_result::Result<Self::SharedAccess>;
    fn shared_timer_query(timer: Option<&Self>) -> Self::SharedQuery;
    fn own_timer(timer: Option<Self>) -> Self::LocalTimer;
    fn take_timer(local: &Self::LocalTimer) -> Option<Self>;
    fn local_timer_count(local: &Self::LocalTimer) -> usize;
    fn timer_count(query: &Self::SharedQuery) -> usize;
    // 先在本地半段处理取消接续与清理,再由事件循环独立取时。取出到期项后归还
    // 来源借用,才顺序交付原值。关闭和后续重查保留实际错误及原资源的释放次序。
    fn cleanup_timer(
        local: &Self::LocalTimer,
        open: impl FnOnce() -> bool,
    ) -> pi_result::Result<bool>;
    fn take_due(
        local: &Self::LocalTimer,
        now: &Self::TimePoint,
        delivery: TimerDelivery,
        open: impl FnOnce() -> bool,
    ) -> pi_result::Result<Option<Due<Self>>>;
    fn into_runnable(entry: Self::Entry) -> Option<Runnable>;
    fn next_check(
        local: &Self::LocalTimer,
        now: &Self::TimePoint,
    ) -> pi_result::Result<Option<Self::TimePoint>>;
    fn close_timer(local: &Self::LocalTimer) -> pi_result::Result<()>;
}

// 原身份和通知已建立。只有选择真实定时来源才调用回调(callback),至多一次;
// 缺席选择直接报告无来源,不采样时钟(clock),不为其复制通知句柄。
// @trace 6
#[allow(private_bounds)]
pub trait MakeTimer<C: ExecutorClock, T: TimerBinding<ClockInstant = C::Instant>>:
    TimerFactoryOperations<C, T>
{}

pub(crate) trait TimerFactoryOperations<C: ExecutorClock, T: TimerBinding<ClockInstant = C::Instant>> {
    fn make(
        self,
        runtime: RuntimeId,
        clock: &C,
        notifier: &ThreadNotifier,
    ) -> pi_result::Result<Option<T>>;
}

impl<I> Default for NoTimerQueue<I> {
    fn default() -> Self {
        Self(PhantomData)
    }
}

impl<I: IdleQueueManager> IdleBinding for I {
    type Handle = I::Handle;
}

impl<I: IdleQueueManager> IdleOwnerOperations for I {
    type Owner = Option<Self>;
    type Shared = I::Handle;
    fn shared_idle(&self) -> Self::Shared {
        self.handle()
    }
    fn own_idle(self) -> Self::Owner {
        Some(self)
    }
    fn take_idle(slot: &mut Self::Owner) -> Option<Self> {
        slot.take()
    }
    fn close_idle(&mut self) -> pi_result::Result<()> {
        self.close().map(|_| ())
    }
}

impl IdleBinding for NoIdleQueue {
    type Handle = Self;
}

impl IdleOwnerOperations for NoIdleQueue {
    type Owner = ();
    type Shared = Self;
    fn shared_idle(&self) -> Self::Shared {
        omitted_idle_handle_inner()
    }
    fn own_idle(self) {}
    fn take_idle(_: &mut ()) -> Option<Self> {
        None
    }
    fn close_idle(&mut self) -> pi_result::Result<()> {
        Ok(())
    }
}

impl<I: IdleTaskQueue> IdleAccess for I {}

impl<I: IdleTaskQueue> IdleHandleOperations for I {
    const PRESENT: bool = true;
    fn idle_count(&self) -> usize {
        self.len()
    }
    fn cleanup_idle(&self) -> pi_result::Result<(QueueCleanupProgress, bool)> {
        self.process_cleanup_with_readiness()
    }
    fn take_ready_idle(&self, max: NonZeroUsize) -> pi_result::RawResult<IdleTake, IdleQueueError> {
        self.try_take_batch(max)
    }
}

impl IdleAccess for NoIdleQueue {}

impl IdleHandleOperations for NoIdleQueue {
    const PRESENT: bool = false;
    fn idle_count(&self) -> usize {
        0
    }
    fn cleanup_idle(&self) -> pi_result::Result<(QueueCleanupProgress, bool)> {
        Ok((QueueCleanupProgress::Complete, false))
    }
    fn take_ready_idle(&self, _: NonZeroUsize) -> pi_result::RawResult<IdleTake, IdleQueueError> {
        Ok(IdleTake::Empty)
    }
}

impl<T: ExecutorTimer + 'static> TimerBinding for T {
    const PRESENT: bool = true;
    type ClockInstant = T::Instant;
}

impl<T: ExecutorTimer + 'static> TimerOperations for T {
    type TimePoint = <T as TimerTaskQueue>::Instant;
    type LocalTimer = RefCell<Option<T>>;
    type SharedAccess = T::Access;
    type SharedQuery = T::Handle;
    type Entry = T::Item;
    type Batch = T::DueBatch;
    fn shared_timer(
        timer: Option<&Self>,
        runtime: RuntimeId,
    ) -> pi_result::Result<Self::SharedAccess> {
        timer_shared_access_inner(timer, runtime)
    }
    fn shared_timer_query(timer: Option<&Self>) -> Self::SharedQuery {
        timer
            .expect("已装配原定时任务队列(timer task queue)")
            .handle()
    }
    fn own_timer(timer: Option<Self>) -> Self::LocalTimer {
        RefCell::new(timer)
    }
    fn take_timer(local: &Self::LocalTimer) -> Option<Self> {
        local.borrow_mut().take()
    }
    fn local_timer_count(local: &Self::LocalTimer) -> usize {
        local.borrow().as_ref().map_or(0, TimerTaskQueue::len)
    }
    fn timer_count(query: &Self::SharedQuery) -> usize {
        query.len()
    }
    fn cleanup_timer(
        local: &Self::LocalTimer,
        open: impl FnOnce() -> bool,
    ) -> pi_result::Result<bool> {
        timer_cleanup_inner(local, open)
    }
    fn take_due(
        local: &Self::LocalTimer,
        now: &Self::TimePoint,
        delivery: TimerDelivery,
        open: impl FnOnce() -> bool,
    ) -> pi_result::Result<Option<Due<Self>>> {
        timer_take_due_inner(local, now, delivery, open)
    }
    fn into_runnable(entry: Self::Entry) -> Option<Runnable> {
        entry.into_due()
    }
    fn next_check(
        local: &Self::LocalTimer,
        now: &Self::TimePoint,
    ) -> pi_result::Result<Option<Self::TimePoint>> {
        timer_next_check_inner(local, now)
    }
    fn close_timer(local: &Self::LocalTimer) -> pi_result::Result<()> {
        timer_close_inner(local)
    }
}

impl<I: 'static> TimerBinding for NoTimerQueue<I> {
    const PRESENT: bool = false;
    type ClockInstant = I;
}

impl<I: 'static> TimerOperations for NoTimerQueue<I> {
    type TimePoint = I;
    type LocalTimer = ();
    type SharedAccess = ();
    type SharedQuery = ();
    type Entry = Infallible;
    type Batch = std::iter::Empty<Infallible>;
    fn shared_timer(_: Option<&Self>, _: RuntimeId) -> pi_result::Result<()> {
        Ok(())
    }
    fn shared_timer_query(_: Option<&Self>) {}
    fn own_timer(_: Option<Self>) {}
    fn take_timer(_: &()) -> Option<Self> {
        None
    }
    fn local_timer_count(_: &()) -> usize {
        0
    }
    fn timer_count(_: &()) -> usize {
        0
    }
    fn cleanup_timer(_: &(), _: impl FnOnce() -> bool) -> pi_result::Result<bool> {
        Ok(false)
    }
    fn take_due(
        _: &(),
        _: &I,
        _: TimerDelivery,
        _: impl FnOnce() -> bool,
    ) -> pi_result::Result<Option<Due<Self>>> {
        Ok(None)
    }
    fn into_runnable(entry: Infallible) -> Option<Runnable> {
        match entry {}
    }
    fn next_check(_: &(), _: &I) -> pi_result::Result<Option<I>> {
        Ok(None)
    }
    fn close_timer(_: &()) -> pi_result::Result<()> {
        Ok(())
    }
}

impl<C, T, F> TimerFactoryOperations<C, T> for F
where
    C: ExecutorClock,
    T: ExecutorTimer<Instant = C::Instant> + 'static,
    F: FnOnce(RuntimeId, &C, ThreadNotifier) -> pi_result::Result<T>,
{
    fn make(
        self,
        runtime: RuntimeId,
        clock: &C,
        notifier: &ThreadNotifier,
    ) -> pi_result::Result<Option<T>> {
        self(runtime, clock, notifier.clone()).map(Some)
    }
}

impl<C: ExecutorClock> TimerFactoryOperations<C, NoTimerQueue<C::Instant>> for NoTimerQueue<C::Instant> {
    fn make(self, _: RuntimeId, _: &C, _: &ThreadNotifier) -> pi_result::Result<Option<Self>> {
        omitted_timer_inner()
    }
}

impl<C, T, F> MakeTimer<C, T> for F
where
    C: ExecutorClock,
    T: TimerBinding<ClockInstant = C::Instant>,
    F: TimerFactoryOperations<C, T>,
{}

include!("optional_queues_inner.rs");