Skip to main content

pi_async_executor/
engine.rs

1//! 通用默认执行器(executor);业务接纳规则由外层运行时(runtime)传入。
2use crate::{
3    clock::ExecutorClock,
4    drive::*,
5    handle::ExecutorHandle,
6    hooks::ExecutorHooks,
7    local::ExecutorLocal,
8    parking::{ThreadNotifier, ThreadParker},
9    policy::{ExecutorSnapshot, IdlePolicy},
10    registry::TaskRegistry,
11    returns::ReturnQueue,
12    routing::{ExecutorSchedule, LocalReadySubmit},
13    state::ExecutorState,
14    timer::ExecutorTimer,
15};
16use pi_async_runtime_core::{
17    block_on::RootWakeState,
18    definitions::{RuntimeId, RuntimeStatus},
19};
20use pi_async_task::{Runnable, TaskThread};
21use pi_async_task_queue::{idle::IdleQueueManager, ExternalQueueManager, TaskQueue};
22use std::{marker::PhantomData, rc::Rc, sync::Arc, thread::ThreadId};
23struct TaskStep {
24    ran: bool,
25    deferred_task: Option<pi_async_task::definitions::TaskId>,
26}
27struct TimerStep {
28    runs: usize,
29    pending: bool,
30    deferred_task: Option<pi_async_task::definitions::TaskId>,
31}
32#[derive(Clone, Copy, Default)]
33struct ImportResult {
34    deferred: bool,
35}
36
37/// 供运行时(runtime)实现者静态组合的完整机制;本对象!Send/!Sync,不创建线程。
38/// 外部提供当前线程,创建后固定所属域。公开业务由更外层简洁类型包装,不暴露类型链。
39/// 释放(drop)停止接纳并交还原来源与本地任务(Task)责任;仍存活动可延迟本地实际退出。
40/// 上层运行时(runtime)须先撤本地权限;共享访问晚释放不成为原异步计算(Future)清理前提。
41/// 清理失败保持已关闭不可用与未完成确认,不重新执行原值或报告成功完成。
42pub struct DefaultExecutor<C, E, I, T, L>
43where
44    C: ExecutorClock,
45    E: ExternalQueueManager,
46    I: IdleQueueManager,
47    T: ExecutorTimer<Instant = C::Instant> + 'static,
48    L: LocalReadySubmit,
49{
50    pub(crate) clock: C,
51    pub(crate) external: Option<E>,
52    pub(crate) idle: Option<I>,
53    pub(crate) local: Rc<ExecutorLocal<T>>,
54    pub(crate) handle: ExecutorHandle<E::Handle, I::Handle, T, L>,
55    pub(crate) parker: ThreadParker,
56    pub(crate) options: ExecutorOptions,
57}
58/// 只持共享推进标记,!Send/!Sync;不能凭此访问队列或改变原线程。
59/// 释放(drop)只归还本服务推进权,正常与恐慌(panic)展开均配对;不通知、清理或迁移任务(Task)。
60pub struct DriveLease {
61    state: Arc<ExecutorState>,
62    runtime: RuntimeId,
63    thread: ThreadId,
64    local: PhantomData<Rc<()>>,
65}
66impl Drop for DriveLease {
67    fn drop(&mut self) {
68        drive_lease_drop_inner(self)
69    }
70}
71struct ExecutorBuildGuard<T: ExecutorTimer + 'static> {
72    // owner最先真实退出,余字段即使Drop中展开仍按此顺序自动归还。
73    owner: Option<TaskThread>,
74    ready: Option<TaskQueue>,
75    timer: Option<T>,
76    returns: Option<ReturnQueue>,
77    registry: Option<TaskRegistry>,
78}
79impl<T: ExecutorTimer + 'static> Drop for ExecutorBuildGuard<T> {
80    fn drop(&mut self) {
81        executor_build_drop_inner(self)
82    }
83}
84enum ExecutorExitPhase {
85    External,
86    Idle,
87    Local,
88    Done,
89}
90struct InternalTransferGuard {
91    state: Arc<ExecutorState>,
92    count: usize,
93}
94impl Drop for InternalTransferGuard {
95    fn drop(&mut self) {
96        internal_transfer_drop_inner(self)
97    }
98}
99struct ExecutorExitGuard<'a, C, E, I, T, L>
100where
101    C: ExecutorClock,
102    E: ExternalQueueManager,
103    I: IdleQueueManager,
104    T: ExecutorTimer<Instant = C::Instant> + 'static,
105    L: LocalReadySubmit,
106{
107    executor: &'a mut DefaultExecutor<C, E, I, T, L>,
108    phase: ExecutorExitPhase,
109    current_failed: bool,
110    failed: bool,
111}
112impl<C, E, I, T, L> DefaultExecutor<C, E, I, T, L>
113where
114    C: ExecutorClock,
115    E: ExternalQueueManager,
116    I: IdleQueueManager,
117    T: ExecutorTimer<Instant = C::Instant> + 'static,
118    L: LocalReadySubmit,
119{
120    /// 接管新建的私有普通/空闲管理对象,在本线程新建原所属域。
121    /// make_timer取得最终RuntimeId、同一clock及原线程通知,必须返回同源新拥有者。
122    /// 原来源应未公开业务访问;构造失败合法释放已接管资源,不初始化全局时钟。
123    pub fn new(
124        clock: C,
125        external: E,
126        idle: I,
127        options: ExecutorOptions,
128        make_timer: impl FnOnce(RuntimeId, &C, ThreadNotifier) -> pi_result::Result<T>,
129    ) -> pi_result::Result<Self> {
130        executor_new_inner(clock, external, idle, options, make_timer)
131    }
132    pub fn handle(&self) -> ExecutorHandle<E::Handle, I::Handle, T, L> {
133        self.handle.clone()
134    }
135    /// 框架本地权限注册目标,只供运行时(runtime)装配;最终业务不得取得它。
136    pub fn local(&self) -> &Rc<ExecutorLocal<T>> {
137        &self.local
138    }
139    /// 核当前线程并独占标记;重复推进在用户Future首次poll前panic。
140    /// 本函数不进入全局DriveScope,供block_on核心自身统一建立该范围。
141    pub fn begin_drive(&self) -> DriveLease {
142        executor_begin_drive_inner(self)
143    }
144    /// 一次有限轮转,不停放线程、不等新任务。用户Future、Drop或控制hook可同步阻塞。
145    /// 最多One到期/内部/空闲各一次业务run机会;有限批次直接清理另算。
146    /// All到期业务按序转内部,不逐项内联poll;已取消/退出者不隐式admit。
147    pub fn run_once<A: AdmissionRule, P: IdlePolicy, H: ExecutorHooks>(
148        &mut self,
149        admission: &A,
150        policy: &mut P,
151        hooks: &mut H,
152    ) -> pi_result::Result<TurnResult> {
153        executor_once_inner(self, admission, policy, hooks)
154    }
155    /// 持续推进至服务关闭;外部提交、已有唤醒、取消/关闭及超时均可使停放返回。
156    pub fn run<A: AdmissionRule, P: IdlePolicy, H: ExecutorHooks>(
157        &mut self,
158        admission: &A,
159        policy: &mut P,
160        hooks: &mut H,
161    ) -> pi_result::Result<()> {
162        executor_run_inner(self, admission, policy, hooks)
163    }
164    /// 已合法取得本次DriveLease的内部轮转;不再次进入DriveScope,不为block_on制造嵌套。
165    pub fn turn_with_lease<A: AdmissionRule, P: IdlePolicy, H: ExecutorHooks>(
166        &mut self,
167        lease: &DriveLease,
168        admission: &A,
169        policy: &mut P,
170        hooks: &mut H,
171    ) -> pi_result::Result<TurnResult> {
172        executor_turn_inner(self, lease, admission, policy, hooks)
173    }
174    /// 用上次策略建议重新核工作、通知与定时上界;root仅用于同步根的额外通知。
175    /// 返回前若通知已消费必须实际重新轮询,不能以旧snapshot继续停放。
176    pub fn park_with_lease<A: AdmissionRule>(
177        &mut self,
178        lease: &DriveLease,
179        admission: &A,
180        last: &TurnResult,
181        root: Option<&RootWakeState>,
182    ) -> pi_result::Result<()> {
183        executor_park_inner(self, lease, admission, last, root)
184    }
185    pub(crate) fn snapshot(
186        &self,
187        admit: bool,
188        timer_pending: bool,
189        maintenance: bool,
190        readiness: crate::policy::WorkReadiness,
191    ) -> ExecutorSnapshot<'_> {
192        executor_snapshot_inner(self, admit, timer_pending, maintenance, readiness)
193    }
194    pub(crate) fn import_returns(&mut self) -> pi_result::Result<ImportResult> {
195        executor_returns_inner(self)
196    }
197    pub(crate) fn import_external<A: AdmissionRule>(
198        &mut self,
199        admission: &A,
200    ) -> pi_result::Result<ImportResult> {
201        executor_external_inner(self, admission)
202    }
203    pub(crate) fn service_timers<H: ExecutorHooks>(
204        &mut self,
205        hooks: &mut H,
206    ) -> pi_result::Result<TimerStep> {
207        executor_timers_inner(self, hooks)
208    }
209    pub(crate) fn run_task<H: ExecutorHooks>(
210        &mut self,
211        task: Runnable,
212        hooks: &mut H,
213    ) -> pi_result::Result<TaskStep> {
214        executor_task_inner(self, task, hooks)
215    }
216    pub(crate) fn close_service(&mut self) -> pi_result::Result<()> {
217        executor_close_inner(self)
218    }
219    pub(crate) fn prepare_for_queue(&self, task: Runnable) -> pi_result::Result<Option<Runnable>> {
220        executor_prepare_inner(self, task)
221    }
222}
223impl<C, E, I, T, L> Drop for DefaultExecutor<C, E, I, T, L>
224where
225    C: ExecutorClock,
226    E: ExternalQueueManager,
227    I: IdleQueueManager,
228    T: ExecutorTimer<Instant = C::Instant> + 'static,
229    L: LocalReadySubmit,
230{
231    fn drop(&mut self) {
232        executor_drop_inner(self)
233    }
234}
235impl<C, E, I, T, L> ExecutorExitGuard<'_, C, E, I, T, L>
236where
237    C: ExecutorClock,
238    E: ExternalQueueManager,
239    I: IdleQueueManager,
240    T: ExecutorTimer<Instant = C::Instant> + 'static,
241    L: LocalReadySubmit,
242{
243    fn drain(&mut self) {
244        executor_exit_drain_inner(self)
245    }
246}
247impl<C, E, I, T, L> Drop for ExecutorExitGuard<'_, C, E, I, T, L>
248where
249    C: ExecutorClock,
250    E: ExternalQueueManager,
251    I: IdleQueueManager,
252    T: ExecutorTimer<Instant = C::Instant> + 'static,
253    L: LocalReadySubmit,
254{
255    fn drop(&mut self) {
256        executor_exit_drop_inner(self)
257    }
258}
259include!("engine_inner.rs");