pi-async-runtime 0.1.5

单线程串行及并发异步运行时的静态组合
Documentation
//! 运行时(runtime)构造时选择四类任务队列。
use crate::instance::Timer;
use pi_async_executor::{
    routing::LocalReadySubmit, DefaultExecutor, DefaultTimerDriver, ExecutorClock, ExecutorOptions,
    ExecutorTimer, IdleBinding, InternalQueueContext, MakeTimer, ManualClock, NoIdleQueue,
    NoTimerQueue, ThreadNotifier, TimerBinding,
};
use pi_async_runtime_core::RuntimeId;
use pi_async_task_queue::{
    CancelTimerOptions, ExternalQueueManager, IdleQueueManager, InternalTaskQueue, MpscIdleTaskQueue,
    MpscQueueOptions, MpscTaskQueue, TaskQueue,
};
use pi_clock_manual::global::GlobalManualInstant;
use std::marker::PhantomData;

pub(crate) enum QueueSelection<Q> {
    Default(fn(MpscQueueOptions) -> pi_result::Result<Q>),
    Specified(Q),
}

/// 默认定时构造(construction),根据实际内部任务队列的类型选用同源本地访问。
#[doc(hidden)]
pub struct MakeDefaultTimer<C>(PhantomData<fn() -> C>);

/// 默认内部任务队列(internal task queue)的构造选择。
#[doc(hidden)]
pub struct DefaultInternalQueue;

/// 单线程本地运行时(single-threaded local runtime)的定时任务队列(timer task queue)
/// 和空闲任务队列(idle task queue)配置。默认两项均省略,可独立选配。
/// 普通和内部任务队列仍共用该运行时拥有的同一份 `TaskQueue`。
// @trace 8
pub struct LocalRuntimeQueues<I = NoIdleQueue, F = NoTimerQueue<GlobalManualInstant>> {
    idle: I,
    timer: F,
}

impl Default for LocalRuntimeQueues {
    fn default() -> Self {
        Self { idle: NoIdleQueue, timer: NoTimerQueue::default() }
    }
}

impl<I, F> LocalRuntimeQueues<I, F> {
    // 构造时一次移交两项实际选择,由原所属线程(owner thread)接管。
    pub(crate) fn into_parts(self) -> (I, F) {
        (self.idle, self.timer)
    }

    /// 按值移交空闲任务队列(idle task queue)的管理者。保留原定时选择。
    /// 移交前已取得的共享句柄(shared handle)继续指向原空闲任务队列。
    pub fn with_idle<Q: IdleQueueManager>(self, idle: Q) -> LocalRuntimeQueues<Q, F> {
        LocalRuntimeQueues { idle, timer: self.timer }
    }

    /// 选择默认定时任务队列(timer task queue)。在构造运行时(runtime)前安装全局时钟(global clock)。
    pub fn with_default_timer(self) -> LocalRuntimeQueues<I, MakeDefaultTimer<ManualClock>> {
        LocalRuntimeQueues { idle: self.idle, timer: MakeDefaultTimer(PhantomData) }
    }

    /// 选择定时构造回调(callback)。构造时使用本次实际运行时编号(RuntimeId)、时钟(clock)
    /// 和线程通知句柄(ThreadNotifier)准备定时来源。定时和空闲选择可按任意顺序设置。
    pub fn with_timer<T, G>(
        self,
        make: G,
    ) -> LocalRuntimeQueues<
        I,
        impl FnOnce(RuntimeId, &ManualClock, ThreadNotifier, CancelTimerOptions) -> pi_result::Result<T>,
    >
    where
        T: ExecutorTimer<Instant = GlobalManualInstant> + 'static,
        G: FnOnce(RuntimeId, &ManualClock, ThreadNotifier) -> pi_result::Result<T>,
    {
        LocalRuntimeQueues {
            idle: self.idle,
            timer: move |runtime, clock: &ManualClock, notifier, _options| make(runtime, clock, notifier),
        }
    }
}

/// 分别选择外部任务队列(external task queue)、内部任务队列(internal task queue)、
/// 定时任务队列(timer task queue)和空闲任务队列(idle task queue)。
/// 缺项使用默认配置。定时和空闲可分别省略。构造运行时(runtime)时移交原实例,
/// 由执行器(executor)绑定。独立串行运行时只接受原外部与内部组合。
pub struct RuntimeQueues<
    C: ExecutorClock<Instant = GlobalManualInstant> = ManualClock,
    E = MpscTaskQueue,
    I = MpscIdleTaskQueue,
    F = MakeDefaultTimer<C>,
    B = DefaultInternalQueue,
> {
    pub(crate) external: QueueSelection<E>,
    pub(crate) idle: QueueSelection<I>,
    pub(crate) timer: F,
    pub(crate) internal: B,
    clock: PhantomData<fn() -> C>,
}

impl<C: ExecutorClock<Instant = GlobalManualInstant>> Default for RuntimeQueues<C> {
    fn default() -> Self {
        Self {
            external: QueueSelection::Default(MpscTaskQueue::new),
            idle: QueueSelection::Default(MpscIdleTaskQueue::new),
            timer: MakeDefaultTimer(PhantomData),
            internal: DefaultInternalQueue,
            clock: PhantomData,
        }
    }
}

impl<C: ExecutorClock<Instant = GlobalManualInstant>, E, I, F, B> RuntimeQueues<C, E, I, F, B> {
    /// 移交外部任务队列(external task queue)的管理者。已有共享访问按队列原约定使用。
    /// 经运行时(runtime)派发时由运行时核对任务归属并安排通知(notification)。
    pub fn with_external<Q: ExternalQueueManager>(self, queue: Q) -> RuntimeQueues<C, Q, I, F, B> {
        RuntimeQueues {
            external: QueueSelection::Specified(queue),
            idle: self.idle,
            timer: self.timer,
            internal: self.internal,
            clock: PhantomData,
        }
    }

    /// 移交空闲任务队列(idle task queue)的管理者。空闲判定仍由原执行器(executor)负责。
    /// 已有共享访问按队列原约定使用,经运行时派发时由运行时负责归属和通知(notification)。
    pub fn with_idle<Q: IdleQueueManager>(self, queue: Q) -> RuntimeQueues<C, E, Q, F, B> {
        RuntimeQueues {
            external: self.external,
            idle: QueueSelection::Specified(queue),
            timer: self.timer,
            internal: self.internal,
            clock: PhantomData,
        }
    }

    /// 按值移交内部任务队列(internal task queue)。
    ///
    /// 运行时构造只接管此原值,要求队列开放、为空且仅绑定当前执行器(executor)。
    /// 已绑定另一所属域(owner domain)的队列无法接入。选择已移交,构造失败时沿原释放约定。
    // @trace 3
    pub fn with_internal<Q>(
        self,
        queue: Q,
    ) -> RuntimeQueues<C, E, I, F, impl RuntimeInternalFactory<Q>>
    where
        Q: InternalTaskQueue + 'static,
    {
        self.with_internal_factory(move |_| Ok(queue))
    }

    /// 在实际所属域(owner domain)建立后调用一次回调(callback),接管回调交出的队列。
    ///
    /// 回调持有的构造权限仅在本次调用中有效。独立串行的队列类型检查早于回调。
    /// 执行器(executor)检查实际队列后才建立定时来源,并沿原约定接管构造和关闭责任。
    // @trace 4
    pub fn with_internal_factory<Q, G>(
        self,
        make: G,
    ) -> RuntimeQueues<C, E, I, F, G>
    where
        Q: InternalTaskQueue + 'static,
        G: for<'owner> FnOnce(InternalQueueContext<'owner>) -> pi_result::Result<Q>,
    {
        queues_with_internal_factory_inner::<C, E, I, F, B, Q, G>(self, make)
    }

    /// 省略空闲任务队列(idle task queue),相应派发入口在编译期不可用。
    /// 已指定的空闲管理者在调用线程释放,其余选择保留。
    // @trace 1
    pub fn without_idle(self) -> RuntimeQueues<C, E, NoIdleQueue, F, B> {
        queues_without_idle_inner(self)
    }

    /// 省略定时任务队列(timer task queue),相应计时、带超时等待和定时派发入口不可用。
    /// 默认构造无需安装全局时钟(clock)。原定时构造回调及其捕获值在调用线程释放,
    /// 回调不执行,其余选择保留。
    // @trace 2
    pub fn without_timer(self) -> RuntimeQueues<C, E, I, NoTimerQueue<GlobalManualInstant>, B> {
        queues_without_timer_inner(self)
    }

    /// 使用一次原计时构造回调准备所选实例。回调使用本次实际身份、时钟(clock)和通知状态。
    /// 回调返回的拥有者在创建线程(thread)交给原执行器。失败时保留原报告(Report)。
    pub fn with_timer<T, G>(
        self,
        make: G,
    ) -> RuntimeQueues<
        C,
        E,
        I,
        impl FnOnce(RuntimeId, &C, ThreadNotifier, CancelTimerOptions) -> pi_result::Result<T>,
        B,
    >
    where
        T: ExecutorTimer<Instant = GlobalManualInstant> + 'static,
        G: FnOnce(RuntimeId, &C, ThreadNotifier) -> pi_result::Result<T>,
    {
        RuntimeQueues {
            external: self.external,
            idle: self.idle,
            timer: move |runtime, clock: &C, notifier, _options| make(runtime, clock, notifier),
            internal: self.internal,
            clock: PhantomData,
        }
    }
}

/// 根据实际队列组合兑现定时构造。
#[doc(hidden)]
pub trait RuntimeTimerFactory<C, T, Q: InternalTaskQueue + 'static>
where
    C: ExecutorClock<Instant = GlobalManualInstant>,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
{
    fn prepare(self, options: CancelTimerOptions) -> impl MakeTimer<C, T>;
}

impl<C, T, F, Q: InternalTaskQueue + 'static> RuntimeTimerFactory<C, T, Q> for F
where
    C: ExecutorClock<Instant = GlobalManualInstant>,
    T: ExecutorTimer<Instant = GlobalManualInstant> + 'static,
    F: FnOnce(RuntimeId, &C, ThreadNotifier, CancelTimerOptions) -> pi_result::Result<T>,
{
    fn prepare(self, options: CancelTimerOptions) -> impl MakeTimer<C, T> {
        move |id, clock: &C, notifier| self(id, clock, notifier, options)
    }
}

impl<C, Q> RuntimeTimerFactory<C, NoTimerQueue<GlobalManualInstant>, Q>
    for NoTimerQueue<GlobalManualInstant>
where
    C: ExecutorClock<Instant = GlobalManualInstant>,
    Q: InternalTaskQueue + 'static,
{
    fn prepare(self, _: CancelTimerOptions) -> impl MakeTimer<C, NoTimerQueue<GlobalManualInstant>> {
        self
    }
}

// @trace 5
impl<C, Q> RuntimeTimerFactory<C, Timer<C, Q>, Q> for MakeDefaultTimer<C>
where
    C: ExecutorClock<Instant = GlobalManualInstant>,
    Q: InternalTaskQueue + 'static,
{
    fn prepare(self, options: CancelTimerOptions) -> impl MakeTimer<C, Timer<C, Q>> {
        move |runtime, clock: &C, notifier| DefaultTimerDriver::new(runtime, clock.clone(), notifier, options)
    }
}

/// 选择原默认内部任务队列或用户移交的原队列。
#[doc(hidden)]
pub trait RuntimeInternalFactory<Q: InternalTaskQueue + 'static> {
    fn bind<C, E, I, T, L>(
        self,
        clock: C,
        external: E,
        idle: I,
        options: ExecutorOptions,
        timer: impl MakeTimer<C, T>,
    ) -> pi_result::Result<DefaultExecutor<C, E, I, T, L, Q>>
    where
        C: ExecutorClock,
        E: ExternalQueueManager,
        I: IdleBinding,
        T: TimerBinding<ClockInstant = C::Instant>,
        L: LocalReadySubmit;
}

// @trace 6
impl RuntimeInternalFactory<TaskQueue> for DefaultInternalQueue {
    fn bind<C, E, I, T, L>(
        self,
        clock: C,
        external: E,
        idle: I,
        options: ExecutorOptions,
        timer: impl MakeTimer<C, T>,
    ) -> pi_result::Result<DefaultExecutor<C, E, I, T, L, TaskQueue>>
    where
        C: ExecutorClock,
        E: ExternalQueueManager,
        I: IdleBinding,
        T: TimerBinding<ClockInstant = C::Instant>,
        L: LocalReadySubmit,
    {
        DefaultExecutor::with_queues(clock, external, idle, options, timer)
    }
}

// @trace 7
impl<Q, G> RuntimeInternalFactory<Q> for G
where
    Q: InternalTaskQueue + 'static,
    G: for<'owner> FnOnce(InternalQueueContext<'owner>) -> pi_result::Result<Q>,
{
    fn bind<C, E, I, T, L>(
        self,
        clock: C,
        external: E,
        idle: I,
        options: ExecutorOptions,
        timer: impl MakeTimer<C, T>,
    ) -> pi_result::Result<DefaultExecutor<C, E, I, T, L, Q>>
    where
        C: ExecutorClock,
        E: ExternalQueueManager,
        I: IdleBinding,
        T: TimerBinding<ClockInstant = C::Instant>,
        L: LocalReadySubmit,
    {
        DefaultExecutor::with_queue_factories(clock, external, idle, self, options, timer)
    }
}

include!("queues_inner.rs");