pi-async-runtime 0.1.5

单线程串行及并发异步运行时的静态组合
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! 两种运行时(runtime)的共同拥有者及透明共享句柄(shared handle)。
use pi_async_task_queue::InternalTaskQueue;
use pi_async_executor::{ExternalAccess, IdleAccess, IdleBinding, TimerBinding};
use crate::{
    binding::RuntimeTag,
    lifecycle::{LocalSource, RuntimeBinding, RuntimeExternalSource, RuntimeSourceBinding},
    mode::{QueuePair, ConcurrentMode, RuntimeMode, SerialMode},
    options::RuntimeOptions,
    queues::{RuntimeInternalFactory, RuntimeQueues, RuntimeTimerFactory},
};
use pi_async_executor::{
    timer::{DefaultTimerAccess, DefaultTimerDriver},
    DefaultExecutor, DefaultIdlePolicy, ExecutorClock, ExecutorHandle, ExecutorHooks,
    ExecutorLocal, IdlePolicy, LocalTaskQueue, LocalTaskSourceAccess, ManualClock, NoHooks,
    ThreadNotifier,
};
use pi_async_task_queue::{
    CancelTimerOptions, ExternalQueueManager, ExternalTaskQueue,
    MpscIdleTaskQueue, MpscIdleTaskQueueHandle, MpscTaskQueue, MpscTaskQueueHandle, TaskQueue,
};
use pi_async_runtime_core::{RuntimeId, SubmitError};
#[cfg(not(target_arch = "wasm32"))]
use pi_async_task_queue::{QueueSelection, WeightedSerialParQueueHandle};
use pi_clock_manual::global::GlobalManualInstant;
use std::{cell::RefCell, rc::Rc, sync::Arc};

pub(crate) type Timer<C, Q = TaskQueue> = DefaultTimerDriver<C, RuntimeTag<C, (), Q>>;
pub(crate) type Executor<C, E, I, T, Q = TaskQueue> = DefaultExecutor<C, <E as RuntimeSourceBinding>::Source, I, T, RuntimeTag<C, T, Q>, Q>;
pub(crate) type Shared<C, E, I, T, Q = TaskQueue> = ExecutorHandle<E, I, T, RuntimeTag<C, T, Q>>;
/// 常规业务只通过RuntimeTime使用,无需拼写内部计时器(timer)参数。
pub type RuntimeTimerAccess<C = ManualClock, Q = TaskQueue> = DefaultTimerAccess<C, RuntimeTag<C, (), Q>>;
pub type TaskHandle<T, V = ()> = pi_async_runtime_core::task::TaskHandle<ThreadNotifier, T, V>;
pub type LocalTaskHandle<T, V = ()> =
    pi_async_runtime_core::task::TaskHandle<ThreadNotifier, T, V, pi_async_task::LocalOutput>;
pub type TimedTaskHandle<T, V = (), C = ManualClock, Q = TaskQueue> = pi_async_runtime_core::task::TaskHandle<
    pi_async_runtime_core::time::TimedTaskNotifier<ThreadNotifier, RuntimeTimerAccess<C, Q>>,
    T,
    V,
>;
pub type TimedTaskNotifier<C = ManualClock, Q = TaskQueue> =
    pi_async_runtime_core::time::TimedTaskNotifier<ThreadNotifier, RuntimeTimerAccess<C, Q>>;

/// 一份固定线程服务,不可Send/Sync;不创建或接管外部线程的所有权。
/// 常规使用SerialRuntime/ConcurrentRuntime,无需填写内部参数;定制类型由with_components推导。
/// 在浏览器(browser)的 `wasm32-unknown-unknown` 目标上,在所属线程(owner thread)
/// 构造并由宿主回调(callback)调用 `run_once`。保留默认定时任务队列(timer task queue)时,
/// 给同一份 `pi-clock-manual` 启用 `browser` 特性(feature)并在构造前调用
/// `pi_clock_manual::global::try_init`。省略定时时无需安装全局时钟(global clock)。
/// 释放(drop)先撤本地权限,再按原执行器(executor)及任务域约定实际退出。
/// 正在进行的同步活动可延迟实际本地清理,不等待普通共享句柄(shared handle)全部释放。
/// 关闭请求、服务不可用与成功完成分别观察,清理失败不能报CloseState::Completed。
/// waiting_for_wake_count及pending_cancel_task_count沿默认执行器按需O(n)扫描登记,n为登记规模;
/// 封装不把这两项查询转为固定成本,默认推进不主动采集。
// @trace 1
pub struct ConfiguredRuntime<M, C, P, H, E = MpscTaskQueue, I = MpscIdleTaskQueue, T = Timer<C>, Q = TaskQueue>
where
    M: RuntimeMode,
    C: ExecutorClock<Instant = GlobalManualInstant>,
    E: RuntimeSourceBinding,
    I: IdleBinding,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
    Q: InternalTaskQueue + 'static,
    P: IdlePolicy,
    H: ExecutorHooks,
{
    pub(crate) shared: RuntimeHandle<C, E::Handle, I::Handle, T, Q>,
    pub(crate) data: RefCell<Option<RuntimeData<M, C, P, H, E, I, T, Q>>>,
    pub(crate) binding: Rc<RuntimeBinding>,
}
pub(crate) struct RuntimeData<M, C, P, H, E, I, T, Q>
where
    M: RuntimeMode,
    C: ExecutorClock<Instant = GlobalManualInstant>,
    E: RuntimeSourceBinding,
    I: IdleBinding,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
    Q: InternalTaskQueue + 'static,
    P: IdlePolicy,
    H: ExecutorHooks,
{
    pub(crate) executor: Executor<C, E, I, T, Q>,
    pub(crate) mode: M,
    pub(crate) policy: P,
    pub(crate) hooks: H,
}
/// 两种方式共用的Clone+Send+Sync业务访问;一次Clone只复制同一Arc,不保本地管理者。
/// 可以从外线程提交/取消/查询;其block_on只推进调用者根,不代推原服务。
pub type Handle = RuntimeHandle<ManualClock>;
/// 默认并发服务,与ConcurrentRuntime为同一具体静态类型(type)。
pub type Runtime = ConfiguredRuntime<ConcurrentMode, ManualClock, DefaultIdlePolicy, NoHooks>;

/// 定制时钟的共享访问;通常由构造结果推导,默认用户使用不带参数的Handle。
/// 两项等待唤醒/待取消查询与ConfiguredRuntime相同,按需O(n)扫描登记,其它操作沿对应能力约定。
/// 释放(drop)本句柄不关闭服务,不延迟本地原异步计算(Future)的合法清理。
pub struct RuntimeHandle<C, E = MpscTaskQueueHandle, I = MpscIdleTaskQueueHandle, T = Timer<C>, Q = TaskQueue>
where
    C: ExecutorClock<Instant = GlobalManualInstant>,
    E: ExternalAccess,
    I: IdleAccess,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
    Q: InternalTaskQueue + 'static,
{
    pub(crate) inner: Arc<Shared<C, E, I, T, Q>>,
}
/// 串行运行时(serial runtime)的默认组合。静态本地入口无需填写内部参数。
/// 浏览器(browser)中用 `run_once`。下一批普通外部任务要等本地在途和内部任务清空才获
/// 接纳(admission)。当前任务依赖交值时,可由宿主回调(callback)或已可推进的任务交值。
pub type SerialRuntime = ConfiguredRuntime<SerialMode, ManualClock, DefaultIdlePolicy, NoHooks>;
/// 单线程并发运行时(single-threaded concurrent runtime)的默认组合,与 `Runtime` 为同一类型。
/// 浏览器(browser)中用 `run_once`。已挂起的任务(Task)等待唤醒(wake-up)时,
/// 运行时仍可接纳和推进其它任务。
pub type ConcurrentRuntime =
    ConfiguredRuntime<ConcurrentMode, ManualClock, DefaultIdlePolicy, NoHooks>;

pub(crate) type LocalService<I, T> = ConfiguredRuntime<
    ConcurrentMode, ManualClock, DefaultIdlePolicy, NoHooks, LocalSource, I, T, LocalTaskQueue,
>;

impl<I, T> LocalService<I, T>
where
    I: IdleBinding,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
{
    // 绑定槽须与构造此执行器(executor)时交给撤销闭包的槽是同一份。
    pub(crate) fn from_local_executor(
        executor: Executor<ManualClock, LocalSource, I, T, LocalTaskQueue>,
        binding: Rc<RuntimeBinding>,
    ) -> Self {
        Self::from_executor(executor, binding, DefaultIdlePolicy, NoHooks)
    }
}

// 两种运行时(runtime)选配构造共用同一顺序。先核独立串行的实际外部与内部类型,
// 合法后才取得时钟以及外部和空闲来源。默认内部队列走原 with_queues;用户值或回调
// 走原 with_queue_factories。执行器(executor)建立所属域、核接入队列后才准备定时来源。
impl<M: RuntimeMode> ConfiguredRuntime<M, ManualClock, DefaultIdlePolicy, NoHooks> {
    /// 默认配置及策略构造;外部必须已安装pi_clock全局时间轴,失败保原报告(Report)。
    pub fn new() -> pi_result::Result<Self> {
        runtime_new_inner(RuntimeOptions::default(), RuntimeQueues::default())
    }
    /// 采用指定工作额度;不改变创建线程归属,不安装全局时钟或启动线程。
    pub fn with_options(options: RuntimeOptions) -> pi_result::Result<Self> {
        runtime_new_inner(options, RuntimeQueues::default())
    }
    /// 由参数推导定制类型,不把内部队列泛型传播到调用点。
    pub fn with_components<C, P, H>(
        clock: C,
        policy: P,
        hooks: H,
        options: RuntimeOptions,
    ) -> pi_result::Result<ConfiguredRuntime<M, C, P, H>>
    where
        C: ExecutorClock<Instant = GlobalManualInstant>,
        P: IdlePolicy,
        H: ExecutorHooks,
    {
        runtime_components_inner(|| Ok(clock), policy, hooks, options, RuntimeQueues::default())
    }

    /// 当前线程构造,分别使用指定的队列(queue)和各缺项的默认来源。
    /// 时钟(clock)、空闲策略及钩子(hook)沿原默认,失败保留原报告(Report)。
    ///
    /// 按值接收选配。构造失败时,原线程释放已移交的队列管理者和未调用的回调(callback);
    /// 返回的报告(Report)不含这些值,也不会交出尚未完成的运行时(runtime)。
    /// 独立 [`SerialRuntime`] 只接收 [`MpscTaskQueue`],与原内部 [`pi_async_task_queue::TaskQueue`]
    /// 配对。其他可静态识别的类型在核对时钟或调用定时回调前返回 `InvalidInput`;
    /// 含非静态借用的外部管理者无法满足串行构造的类型约束。
    /// 省略定时时不核对全局时钟。定制内部队列时,默认定时驱动仍匹配同一实际内部队列。
    /// 当前本地访问以实际类型验证,内部队列类型需要满足 `'static`,无需是 `Send` 或 `Sync`。
    /// 泛型调用方用 `mode::QueuePair` 表达运行方式与实际内、外队列的约束。
    pub fn with_queues<E, I, F, T, Q, B>(
        options: RuntimeOptions,
        queues: RuntimeQueues<ManualClock, E, I, F, B>,
    ) -> pi_result::Result<ConfiguredRuntime<M, ManualClock, DefaultIdlePolicy, NoHooks, E, I, T, Q>>
    where
        M: QueuePair<E, Q>,
        E: ExternalQueueManager,
        I: IdleBinding,
        T: TimerBinding<ClockInstant = GlobalManualInstant>,
        F: RuntimeTimerFactory<ManualClock, T, Q>,
        Q: InternalTaskQueue + 'static,
        B: RuntimeInternalFactory<Q>,
    {
        runtime_new_inner(options, queues)
    }

    /// 同时选择同源时钟(clock)、策略、钩子(hook)及具象队列(queue)。
    /// 管理者随运行时(runtime)接管,计时构造回调使用本次的线程通知句柄(ThreadNotifier)。
    ///
    /// 按值接收选配。选项校验或任一来源准备失败时,原线程释放已接管的资源和
    /// 未调用的回调(callback)。直接返回原报告(Report),调用方不会取得半成品。
    /// 独立串行的合法队列配对、编译期限制及 `InvalidInput` 优先级与 [`Self::with_queues`] 相同。
    /// 本入口接收显式时钟;所选定时来源缺席时执行器(executor)不访问该时钟。
    pub fn with_components_and_queues<C, P, H, E, I, F, T, Q, B>(
        clock: C,
        policy: P,
        hooks: H,
        options: RuntimeOptions,
        queues: RuntimeQueues<C, E, I, F, B>,
    ) -> pi_result::Result<ConfiguredRuntime<M, C, P, H, E, I, T, Q>>
    where
        C: ExecutorClock<Instant = GlobalManualInstant>,
        P: IdlePolicy,
        H: ExecutorHooks,
        M: QueuePair<E, Q>,
        E: ExternalQueueManager,
        I: IdleBinding,
        T: TimerBinding<ClockInstant = GlobalManualInstant>,
        F: RuntimeTimerFactory<C, T, Q>,
        Q: InternalTaskQueue + 'static,
        B: RuntimeInternalFactory<Q>,
    {
        runtime_components_inner(|| Ok(clock), policy, hooks, options, queues)
    }
}
impl<M, C, P, H> ConfiguredRuntime<M, C, P, H>
where
    M: RuntimeMode,
    C: ExecutorClock<Instant = GlobalManualInstant>,
    P: IdlePolicy,
    H: ExecutorHooks,
{
    /// 静态替换同源时钟、空闲/休眠策略及钩子;无额外Send/Sync/Default约束强加给P/H。
    /// 模式M固定普通新业务接纳;策略不能把串行改成并发。
    pub fn from_components(
        clock: C,
        policy: P,
        hooks: H,
        options: RuntimeOptions,
    ) -> pi_result::Result<Self> {
        runtime_components_inner(|| Ok(clock), policy, hooks, options, RuntimeQueues::default())
    }
}
impl<M, C, P, H, E, I, T, Q> ConfiguredRuntime<M, C, P, H, E, I, T, Q>
where
    M: RuntimeMode,
    C: ExecutorClock<Instant = GlobalManualInstant>,
    E: RuntimeSourceBinding,
    I: IdleBinding,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
    Q: InternalTaskQueue + 'static,
    P: IdlePolicy,
    H: ExecutorHooks,
{
    /// 取得同一服务的共享访问;不移交服务推进权,也不延长本地Future的清理。
    pub fn handle(&self) -> RuntimeHandle<C, E::Handle, I::Handle, T, Q> {
        self.shared.clone()
    }
    pub(crate) fn shared(&self) -> &RuntimeHandle<C, E::Handle, I::Handle, T, Q> {
        &self.shared
    }

    // 只装配已经绑定的同一执行器(executor)和本地权限,不重新创建来源或任务域。
    fn from_executor(
        executor: Executor<C, E, I, T, Q>,
        binding: Rc<RuntimeBinding>,
        policy: P,
        hooks: H,
    ) -> Self {
        runtime_from_executor_inner(executor, binding, policy, hooks)
    }
}
impl<C, E, I, T, Q> RuntimeHandle<C, E, I, T, Q>
where
    C: ExecutorClock<Instant = GlobalManualInstant>,
    E: ExternalAccess,
    I: IdleAccess,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
    Q: InternalTaskQueue + 'static,
{
    pub(crate) fn shared(&self) -> &Self {
        self
    }

    // 普通创建沿原执行器登记;成功保留未提交的原任务和唯一结果句柄。
    pub(crate) fn create_task<F, M>(
        &self,
        future: F,
        config: TaskConfig<M>,
    ) -> pi_result::RawResult<(UnsubmittedTask, TaskHandle<F::Output, M>), CreateError<F, M>>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
        M: Send + Sync + 'static,
    {
        self.inner.create(future, config)
    }

    // 同一运行时的原空闲来源接收任务(Task),失败保留原值与实际原因。
    pub(crate) fn submit_idle_task(
        &self,
        task: UnsubmittedTask,
    ) -> pi_result::RawResult<(), SubmitError>
    where
        I: IdleTaskQueue,
    {
        self.inner.submit_idle(task)
    }

    // 使用绑定的定时任务队列(timer task queue),保留原定时派发(timed dispatch)结果。
    pub(crate) fn spawn_timing_task<F, M>(
        &self,
        future: F,
        delay: Duration,
        config: TaskConfig<M>,
    ) -> pi_result::RawResult<
        pi_async_runtime_core::TaskHandle<CoreTimedTaskNotifier<ThreadNotifier, T::Access>, F::Output, M>,
        SpawnError<F, CoreTimedTaskNotifier<ThreadNotifier, T::Access>, M>,
    >
    where
        T: ExecutorTimer<Instant = GlobalManualInstant> + 'static,
        F: Future + Send + 'static,
        F::Output: Send + 'static,
        M: Send + Sync + 'static,
    {
        self.inner.spawn_timing(future, delay, config)
    }

    // 原本地权限仍由执行器(executor)实查。本地定时派发不转交其它运行时。
    pub(crate) fn spawn_timing_local_task<F, M>(
        &self,
        local: &ExecutorLocal<T, Q>,
        future: F,
        delay: Duration,
        config: TaskConfig<M>,
    ) -> pi_result::RawResult<
        pi_async_runtime_core::TaskHandle<
            CoreTimedTaskNotifier<ThreadNotifier, T::Access>, F::Output, M, pi_async_task::LocalOutput,
        >,
        SpawnError<F, CoreTimedTaskNotifier<ThreadNotifier, T::Access>, M, pi_async_task::LocalOutput>,
    >
    where
        T: ExecutorTimer<Instant = GlobalManualInstant> + 'static,
        F: Future + 'static,
        F::Output: 'static,
        M: Send + Sync + 'static,
    {
        self.inner.spawn_timing_local(local, future, delay, config)
    }
}

impl<C, I, T> RuntimeHandle<C, LocalTaskSourceAccess, I, T, LocalTaskQueue>
where
    C: ExecutorClock<Instant = GlobalManualInstant>,
    I: IdleAccess,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
{
    // 原本地设施与当前服务匹配时才尾插;错误保留原待提交任务及实际原因。
    pub(crate) fn submit_same_task_queue(
        &self,
        local: &ExecutorLocal<T, LocalTaskQueue>,
        task: UnsubmittedTask,
    ) -> pi_result::RawResult<(), SubmitError> {
        self.inner.submit_same_task_queue(local, task)
    }
}
impl<C, E, I, T, Q> Clone for RuntimeHandle<C, E, I, T, Q>
where
    C: ExecutorClock<Instant = GlobalManualInstant>,
    E: ExternalAccess,
    I: IdleAccess,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
    Q: InternalTaskQueue + 'static,
{
    fn clone(&self) -> Self {
        runtime_handle_clone_inner(self)
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl<C, I, T, Q> RuntimeHandle<C, WeightedSerialParQueueHandle, I, T, Q>
where
    C: ExecutorClock<Instant = GlobalManualInstant>,
    I: IdleAccess,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
    Q: InternalTaskQueue + 'static,
{
    /// 使用同一运行时派发(dispatch)并通知原所属线程(owner thread)。
    ///
    /// 同组任务(Task)可以继续提交。前项原异步计算(Future)析构(drop)后,
    /// 后项才可取出。结果句柄(result handle)可继续保留。
    /// 并行权重影响取出概率。派发成功表示队列接收,原任务仍待执行器接纳。
    pub fn spawn_with_queue<F>(
        &self,
        future: F,
        queue: QueueSelection,
    ) -> pi_result::RawResult<TaskHandle<F::Output>, SpawnError<F, ThreadNotifier>>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        self.inner.spawn_with_queue(future, queue)
    }
}

impl<M, C, P, H, E, I, T, Q> Drop for ConfiguredRuntime<M, C, P, H, E, I, T, Q>
where
    M: RuntimeMode,
    C: ExecutorClock<Instant = GlobalManualInstant>,
    E: RuntimeSourceBinding,
    I: IdleBinding,
    T: TimerBinding<ClockInstant = GlobalManualInstant>,
    Q: InternalTaskQueue + 'static,
    P: IdlePolicy,
    H: ExecutorHooks,
{
    fn drop(&mut self) {
        runtime_drop_inner(self)
    }
}
include!("instance_inner.rs");

include!("prepared_serial_runtime.rs");