pi-async-runtime 0.1.5

单线程串行及并发异步运行时的静态组合
Documentation
//! 单线程本地运行时(single-threaded local runtime)。
use crate::{
    dispatch,
    instance::LocalService,
    lifecycle::RuntimeBinding,
    queues::RuntimeTimerFactory,
    CloseRequestStatus, CloseState, CreateError, IdleDispatch, IdleState, LocalRuntimeAccessError,
    LocalRuntimeQueues, LocalTaskDispatch, LocalTaskHandle, RuntimeControl, RuntimeId,
    RuntimeQuery, RuntimeStatus, RuntimeTime, RuntimeWait, Sleep, SpawnError, SubmitError,
    TaskConfig, TaskDispatch, TaskHandle, TimedTaskDispatch, Timeout, TimeoutOn, TurnResult,
    UnsubmittedTask,
};
use pi_async_executor::{
    DefaultExecutor, ExecutorLocal, ExecutorOptions, ExecutorTimer, IdleBinding, LocalTaskQueue,
    LocalTaskSourceAccess, ManualClock, NoIdleQueue, NoTimerQueue, ThreadNotifier, TimerBinding,
};
use pi_async_runtime_core::time::TimedTaskNotifier;
use pi_async_task::LocalOutput;
use pi_async_task_queue::IdleQueueManager;
use pi_clock_manual::global::GlobalManualInstant;
use pi_result::RawResult;
use std::{future::Future, rc::Rc, time::Duration};

type Ready = LocalTaskQueue;
type NoTimer = NoTimerQueue<GlobalManualInstant>;

/// 只在所属线程(owner thread)上提交并推进任务。普通派发和本地重新入队共用同一份
/// `TaskQueue`。原异步计算(Future)仍在队首取出后才开始执行。
///
/// 可在第一轮推进前用 [`TaskDispatch::spawn`] 提交。取得有效本地权限后可使用
/// [`LocalTaskDispatch::spawn_local`]。默认省略定时任务队列(timer task queue)与
/// 空闲任务队列(idle task queue),无需全局时钟(global clock)。
/// 用 [`Self::with_queues`] 独立选配,得到相应能力的 [`ConfiguredLocalRuntime`]。
/// 浏览器(browser)的 `wasm32-unknown-unknown` 目标可使用 [`Self::new`] 或 [`Self::with_queues`]。
/// 由同一线程的宿主回调(callback)调用 [`Self::run_once`],提交后的结果由应用异步等待。
/// 普通 `wait_one`、`wait_any`、`wait_all` 可直接用于交值。
///
/// ```compile_fail,E0277
/// use pi_async_runtime::LocalRuntime;
/// fn needs_send<T: Send>(_: T) {}
/// needs_send(LocalRuntime::new().unwrap());
/// ```
///
/// ```compile_fail,E0277
/// use pi_async_runtime::LocalRuntime;
/// fn needs_sync<T: Sync>(_: &T) {}
/// needs_sync(&LocalRuntime::new().unwrap());
/// ```
///
/// ```compile_fail,E0599
/// use pi_async_runtime::{LocalRuntime, RuntimeTime};
/// use std::time::Duration;
/// let runtime = LocalRuntime::new().unwrap();
/// let _ = runtime.timeout(Duration::from_millis(1));
/// ```
///
/// ```compile_fail,E0599
/// use pi_async_runtime::{IdleDispatch, LocalRuntime};
/// let runtime = LocalRuntime::new().unwrap();
/// let _ = runtime.idle(async {});
/// ```
// @trace 1
pub type LocalRuntime = ConfiguredLocalRuntime<NoIdleQueue, NoTimer>;

/// 按实际队列配置使用的单线程本地运行时(single-threaded local runtime)。
///
/// 运行时(runtime)自身的提交与推进限于所属线程(owner thread)。定时任务队列(timer task queue)存在时可用
/// [`RuntimeTime`]、[`RuntimeWait`] 和 [`TimedTaskDispatch`]。空闲任务队列(idle task queue)
/// 存在时可用 [`IdleDispatch`]。本地关联方法使用构造返回的实际类型。
// @trace 4
pub struct ConfiguredLocalRuntime<I, T>
where
    I: IdleBinding,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
{
    service: LocalService<I, T>,
    local: Rc<ExecutorLocal<T, Ready>>,
}

impl LocalRuntime {
    /// 使用默认推进选项,在当前线程创建独立运行时(runtime)。
    pub fn new() -> pi_result::Result<Self> {
        Self::with_options(ExecutorOptions::default())
    }

    /// 选择推进额度及原生线程的休眠期限。普通派发与内部任务固定共用同一队列。
    // @trace 2
    pub fn with_options(options: ExecutorOptions) -> pi_result::Result<Self> {
        local_runtime_new_inner(options)
    }

    /// 在所属线程(owner thread)配置定时任务队列(timer task queue)和空闲任务队列(idle task queue)。
    ///
    /// 配置的管理者按值移交。选择定时时先检查全局时钟(global clock),通过构造前置检查后
    /// 才调用定时构造回调(callback)。
    /// 已从空闲任务队列取得的共享句柄(shared handle)沿原来源的提交和关闭(close)约定使用。
    /// 在浏览器(browser)启用默认定时时,由应用先启用 `pi-clock-manual/browser` 并安装时钟。
    ///
    /// # Errors
    ///
    /// 启用定时但时钟未安装时返回 `InvalidState`。执行器选项或来源构造失败时返回原报告。
    /// 已移交的队列和未调用的回调在所属线程(owner thread)释放。
    ///
    /// 仅选配空闲任务队列时,计时方法仍会被编译器拒绝。
    ///
    /// ```compile_fail,E0599
    /// use pi_async_runtime::{ExecutorOptions, LocalRuntime, LocalRuntimeQueues, RuntimeTime};
    /// use pi_async_task_queue::MpscIdleTaskQueue;
    /// use std::time::Duration;
    /// let idle = MpscIdleTaskQueue::new(Default::default()).unwrap();
    /// let queues = LocalRuntimeQueues::default().with_idle(idle);
    /// let runtime = LocalRuntime::with_queues(ExecutorOptions::default(), queues).unwrap();
    /// let _ = runtime.sleep(Duration::from_millis(1));
    /// ```
    // 时钟(clock)核对通过后,由 DefaultExecutor::with_local_queues 绑定同一份 TaskQueue
    // 和已选来源。交给执行器的撤销回调(callback)与 LocalService 持有同一绑定槽。
    // 退出时先撤销本地权限,再沿原执行器关闭(close)路径清理来源及本地队列。
    // @trace 5
    pub fn with_queues<I, F, T>(
        options: ExecutorOptions,
        queues: LocalRuntimeQueues<I, F>,
    ) -> pi_result::Result<ConfiguredLocalRuntime<I, T>>
    where
        I: IdleBinding,
        T: TimerBinding<ClockInstant = GlobalManualInstant>,
        F: RuntimeTimerFactory<ManualClock, T, Ready>,
    {
        local_runtime_with_queues_inner(options, queues)
    }
}

impl<I, T> ConfiguredLocalRuntime<I, T>
where
    I: IdleBinding,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
{
    /// 在原所属线程完成一次有限推进,返回本轮任务和后续立即推进的状态。
    /// 浏览器(browser)事件的回调(callback)可逐轮调用。每轮返回后将控制权交回宿主。
    /// 有 `immediate_work` 可尽快安排下一轮。宿主交值或唤醒任务后也需要安排一轮。
    /// 关闭(close)时从原线程请求关闭,再推进并查询实际完成状态。
    // @trace 3
    pub fn run_once(&mut self) -> pi_result::Result<TurnResult> {
        self.service.run_once()
    }

    /// 只在支持线程休眠的原生目标上持续推进,直到关闭(close)或首次原推进错误。
    #[cfg(not(target_family = "wasm"))]
    pub fn run(&mut self) -> pi_result::Result<()> {
        self.service.run()
    }
}

impl<I, T> TaskDispatch for ConfiguredLocalRuntime<I, T>
where
    I: IdleBinding,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
{
    type Notifier = ThreadNotifier;

    fn create_with_config<F, M>(
        &self,
        future: F,
        config: TaskConfig<M>,
    ) -> RawResult<(UnsubmittedTask, TaskHandle<F::Output, M>), CreateError<F, M>>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
        M: Send + Sync + 'static,
    {
        self.service.shared().create_task(future, config)
    }

    fn submit(&self, task: UnsubmittedTask) -> RawResult<(), SubmitError> {
        self.service
            .shared()
            .submit_same_task_queue(&self.local, task)
    }
}

impl<I, T> LocalTaskDispatch for ConfiguredLocalRuntime<I, T>
where
    I: IdleBinding,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
{
    fn create_local_with_config<F, M>(
        future: F,
        config: TaskConfig<M>,
    ) -> RawResult<(UnsubmittedTask, LocalTaskHandle<F::Output, M>), CreateError<F, M>>
    where
        F: Future + 'static,
        F::Output: 'static,
        M: Send + Sync + 'static,
    {
        dispatch::create_local::<
            ManualClock,
            LocalTaskSourceAccess,
            I::Handle,
            T,
            Ready,
            F,
            M,
        >(future, config)
    }

    fn submit_local(task: UnsubmittedTask) -> RawResult<(), SubmitError> {
        dispatch::submit_local::<ManualClock, LocalTaskSourceAccess, I::Handle, T, Ready>(
            task, false,
        )
    }
}

#[cfg(not(target_family = "wasm"))]
impl<I, T> crate::RuntimeBlockOn for ConfiguredLocalRuntime<I, T>
where
    I: IdleBinding,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
{
    fn block_on<F: Future>(&self, future: F) -> F::Output {
        self.service.block_on(future)
    }
}

impl<I, T> RuntimeQuery for ConfiguredLocalRuntime<I, T>
where
    I: IdleBinding,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
{
    fn id(&self) -> RuntimeId {
        self.service.id()
    }
    fn status(&self) -> RuntimeStatus {
        self.service.status()
    }
    fn is_driving(&self) -> bool {
        self.service.is_driving()
    }
    fn last_idle_state(&self) -> IdleState {
        self.service.last_idle_state()
    }
    fn close_state(&self) -> CloseState {
        self.service.close_state()
    }
    fn external_task_count(&self) -> usize {
        self.service.external_task_count()
    }
    fn internal_task_count(&self) -> usize {
        self.service.internal_task_count()
    }
    fn timer_registration_count(&self) -> usize {
        self.service.timer_registration_count()
    }
    fn idle_task_count(&self) -> usize {
        self.service.idle_task_count()
    }
    fn in_flight_task_count(&self) -> usize {
        self.service.in_flight_task_count()
    }
    fn waiting_for_wake_count(&self) -> usize {
        self.service.waiting_for_wake_count()
    }
    fn pending_cancel_task_count(&self) -> usize {
        self.service.pending_cancel_task_count()
    }
}

impl<I, T> RuntimeControl for ConfiguredLocalRuntime<I, T>
where
    I: IdleBinding,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
{
    fn request_close(&self) -> CloseRequestStatus {
        self.service.request_close()
    }
}

impl<I, T> RuntimeTime for ConfiguredLocalRuntime<I, T>
where
    I: IdleBinding,
    T: ExecutorTimer<Instant = GlobalManualInstant> + 'static,
{
    type Timer = T::Access;

    fn timeout(&self, duration: Duration) -> Timeout<Self::Timer> {
        self.service.timeout(duration)
    }

    fn timeout_on<F: Future>(&self, future: F, duration: Duration) -> TimeoutOn<Self::Timer, F> {
        self.service.timeout_on(future, duration)
    }

    fn sleep(&self, duration: Duration) -> Sleep<Self::Timer> {
        self.service.sleep(duration)
    }

    fn timeout_local(duration: Duration) -> RawResult<Timeout<Self::Timer>, LocalRuntimeAccessError> {
        LocalService::<I, T>::timeout_local(duration)
    }

    fn timeout_on_local<F: Future>(
        future: F,
        duration: Duration,
    ) -> RawResult<TimeoutOn<Self::Timer, F>, LocalRuntimeAccessError> {
        LocalService::<I, T>::timeout_on_local(future, duration)
    }

    fn sleep_local(duration: Duration) -> RawResult<Sleep<Self::Timer>, LocalRuntimeAccessError> {
        LocalService::<I, T>::sleep_local(duration)
    }
}

impl<I, T> RuntimeWait for ConfiguredLocalRuntime<I, T>
where
    I: IdleBinding,
    T: ExecutorTimer<Instant = GlobalManualInstant> + 'static,
{
}

impl<I, T> IdleDispatch for ConfiguredLocalRuntime<I, T>
where
    I: IdleQueueManager,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
{
    fn submit_idle(&self, task: UnsubmittedTask) -> RawResult<(), SubmitError> {
        self.service.shared().submit_idle_task(task)
    }

    fn idle_local_with_config<F, M>(
        future: F,
        config: TaskConfig<M>,
    ) -> RawResult<TaskHandle<F::Output, M>, SpawnError<F, ThreadNotifier, M>>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
        M: Send + Sync + 'static,
    {
        dispatch::idle_local::<ManualClock, LocalTaskSourceAccess, I::Handle, T, Ready, F, M>(
            future, config,
        )
    }
}

impl<I, T> TimedTaskDispatch for ConfiguredLocalRuntime<I, T>
where
    I: IdleBinding,
    T: ExecutorTimer<Instant = GlobalManualInstant> + 'static,
{
    fn spawn_timing_with_config<F, M>(
        &self,
        future: F,
        delay: Duration,
        config: TaskConfig<M>,
    ) -> RawResult<
        pi_async_runtime_core::TaskHandle<TimedTaskNotifier<ThreadNotifier, T::Access>, F::Output, M>,
        SpawnError<F, TimedTaskNotifier<ThreadNotifier, T::Access>, M>,
    >
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
        M: Send + Sync + 'static,
    {
        self.service.shared().spawn_timing_task(future, delay, config)
    }

    fn spawn_timing_local_with_config<F, M>(
        future: F,
        delay: Duration,
        config: TaskConfig<M>,
    ) -> RawResult<
        pi_async_runtime_core::TaskHandle<TimedTaskNotifier<ThreadNotifier, T::Access>, F::Output, M, LocalOutput>,
        SpawnError<F, TimedTaskNotifier<ThreadNotifier, T::Access>, M, LocalOutput>,
    >
    where
        F: Future + 'static,
        F::Output: 'static,
        M: Send + Sync + 'static,
    {
        dispatch::timing_local::<ManualClock, LocalTaskSourceAccess, I::Handle, T, Ready, F, M>(
            future, delay, config,
        )
    }
}

include!("local_runtime_inner.rs");