Skip to main content

pi_async_executor/timer/
access.rs

1//! 默认计时共享访问与原登记的一次预备节点。
2use super::{
3    protocol::LocalTimerSubmit,
4    retry::{RetryHandle, RetryOwner, RetryShared, RetryWork},
5};
6use crate::{clock::ExecutorClock, parking::ThreadNotifier};
7use cordyceps::{mpsc_queue::Links, Linked};
8use pi_async_runtime_core::{
9    definitions::{RuntimeId, TimerError},
10    time::{
11        resume_timer_cancel, TimerAccess, TimerEntry, TimerRegistration, TimerRegistrationKind,
12    },
13};
14use pi_async_task_queue::{
15    timer::{TimerQueueError, TimerQueueHandle, TimerSubmitError},
16    CancelTimerKey, CancelTimerQueueHandle,
17};
18use pi_clock_manual::global::GlobalManualInstant;
19use std::{
20    cell::UnsafeCell,
21    marker::{PhantomData, PhantomPinned},
22    ptr::NonNull,
23    sync::{
24        atomic::{AtomicBool, AtomicU8},
25        Arc, Weak,
26    },
27    time::Duration,
28};
29
30/// 默认适配的登记载荷;只有运行时(runtime)构造和执行器(executor)交付,不向普通业务拆出。
31pub type DefaultTimerItem<C, L> = TimerEntry<CancelTimerKey, DefaultTimerRegistration<C, L>>;
32
33/// 同一计时来源的Clone+Send+Sync访问;不保本地容器或可写线程局部指针。
34///
35/// 正常业务通过运行时(runtime)的timeout/sleep等使用。C为同源时钟,L为静态本地接入;
36/// 外部签名不要求业务Future的Unpin或额外Sync,最终运行时别名隐藏这两个实现参数。
37pub struct DefaultTimerAccess<C: ExecutorClock<Instant = GlobalManualInstant>, L: 'static> {
38    pub(super) shared: Arc<TimerSourceShared<C, L>>,
39}
40/// 核心登记与其一次准备节点的共享句柄;复制只增加同一Arc,不复制键或任务(Task)。
41pub struct DefaultTimerRegistration<C: ExecutorClock<Instant = GlobalManualInstant>, L: 'static> {
42    pub(super) node: Arc<CancelRetryNode<C, L>>,
43}
44pub(super) struct TimerSourceShared<C: ExecutorClock<Instant = GlobalManualInstant>, L: 'static> {
45    pub(super) runtime: RuntimeId,
46    pub(super) clock: C,
47    pub(super) backend: CancelTimerQueueHandle<DefaultTimerItem<C, L>, ThreadNotifier>,
48    pub(super) retries: Arc<RetryShared<CancelRetryNode<C, L>>>,
49    pub(super) owner_exiting: AtomicBool,
50    pub(super) local: PhantomData<fn() -> L>,
51}
52// Node不含原Future、ControlHandle或本地Rc;原业务持有只在TimerEntry。
53// error仅在一次链接资格的Publishing期间写,保留第一份真实原错误直到节点最终释放;
54// 不是把Report字符串化或变成用户控制错误的副本。重复送入不是第二取消责任。
55// links地址用原始投影;Arc只保地址,不能对已发布节点try_unwrap/get_mut移动。
56// 没有Access→Node→Access强环:origin与retry均为Weak。驱动退出先撤权限/停收意图,
57// 实际本地活动者和本地核心负责原生来源Drop,之后才退出RetryOwner。
58pub(super) struct CancelRetryNode<C: ExecutorClock<Instant = GlobalManualInstant>, L: 'static> {
59    facts: TimerRegistration<CancelTimerKey>,
60    links: Links<Self>,
61    origin: Weak<TimerSourceShared<C, L>>,
62    retry: Weak<RetryShared<Self>>,
63    membership: AtomicU8,
64    error: UnsafeCell<Option<TimerQueueError>>,
65    stub: bool,
66    pin: PhantomPinned,
67}
68const NODE_IDLE: u8 = 0;
69const NODE_PUBLISHING: u8 = 1;
70const NODE_QUEUED: u8 = 2;
71// SAFETY: error只有IDLE->PUBLISHING成功者访问;成功CAS使用AcqRel,取得上次恢复IDLE的Release。
72// 失败分支不访问error。下一次成功取得或最终独占Drop之前,不在其它资格外读写该槽。
73// 同一节点最多一份RetryHandle入队;Links仅原生原始指针投影,facts已有独立发布协议。
74// origin/retry为线程安全Weak,L仅类型标记,绝不存跨线程可访问的本地数据。
75unsafe impl<C: ExecutorClock<Instant = GlobalManualInstant>, L: 'static> Sync
76    for CancelRetryNode<C, L>
77{
78}
79
80impl<C: ExecutorClock<Instant = GlobalManualInstant>, L: 'static> Clone
81    for DefaultTimerAccess<C, L>
82{
83    fn clone(&self) -> Self {
84        default_access_clone_inner(self)
85    }
86}
87impl<C: ExecutorClock<Instant = GlobalManualInstant>, L: 'static> Clone
88    for DefaultTimerRegistration<C, L>
89{
90    fn clone(&self) -> Self {
91        default_registration_clone_inner(self)
92    }
93}
94impl<C: ExecutorClock<Instant = GlobalManualInstant>, L: 'static>
95    AsRef<TimerRegistration<CancelTimerKey>> for DefaultTimerRegistration<C, L>
96{
97    fn as_ref(&self) -> &TimerRegistration<CancelTimerKey> {
98        &self.node.facts
99    }
100}
101impl<C, L> TimerAccess for DefaultTimerAccess<C, L>
102where
103    C: ExecutorClock<Instant = GlobalManualInstant>,
104    L: LocalTimerSubmit<DefaultTimerItem<C, L>>,
105{
106    type Instant = GlobalManualInstant;
107    type Key = CancelTimerKey;
108    type Registration = DefaultTimerRegistration<C, L>;
109    fn runtime_id(&self) -> RuntimeId {
110        self.shared.runtime
111    }
112    fn deadline_after(
113        &self,
114        duration: Duration,
115    ) -> pi_result::RawResult<Self::Instant, TimerError> {
116        default_deadline_inner(self, duration)
117    }
118    fn prepare_registration(
119        &self,
120        kind: TimerRegistrationKind,
121    ) -> pi_result::RawResult<Self::Registration, TimerError> {
122        default_prepare_inner(self, kind)
123    }
124    fn try_register(
125        &self,
126        deadline: Self::Instant,
127        item: DefaultTimerItem<C, L>,
128    ) -> pi_result::RawResult<Self::Key, TimerSubmitError<DefaultTimerItem<C, L>>> {
129        default_register_inner(self, deadline, item)
130    }
131    fn try_register_local(
132        &self,
133        deadline: Self::Instant,
134        item: DefaultTimerItem<C, L>,
135    ) -> pi_result::RawResult<Self::Key, TimerSubmitError<DefaultTimerItem<C, L>>> {
136        default_register_local_inner(self, deadline, item)
137    }
138    fn request_cancel(&self, key: &Self::Key) -> pi_result::RawResult<(), TimerQueueError> {
139        default_cancel_inner(self, key)
140    }
141    fn defer_cancel(&self, registration: Self::Registration, error: Option<TimerQueueError>) {
142        default_defer_inner(self, registration, error)
143    }
144}
145impl<C, L> RetryWork for CancelRetryNode<C, L>
146where
147    C: ExecutorClock<Instant = GlobalManualInstant>,
148    L: LocalTimerSubmit<DefaultTimerItem<C, L>>,
149{
150    fn resume(this: &Arc<Self>) {
151        default_retry_resume_inner(this)
152    }
153}
154// SAFETY: 唯一RetryHandle只在节点资格成功后构造;原生入队仅移动这份持有。
155// Arc数据固定,Self含PhantomPinned;原生安全归还后才可复用Links;stub不进入核心resume。
156// into_ptr抑制包装Drop,from_ptr仅按原生合法归还重建同一单位和内部结算函数。
157unsafe impl<C: ExecutorClock<Instant = GlobalManualInstant>, L: 'static> Linked<Links<Self>>
158    for CancelRetryNode<C, L>
159{
160    type Handle = RetryHandle<Self>;
161    fn into_ptr(handle: Self::Handle) -> NonNull<Self> {
162        default_retry_into_ptr_inner(handle)
163    }
164    unsafe fn from_ptr(ptr: NonNull<Self>) -> Self::Handle {
165        default_retry_from_ptr_inner(ptr)
166    }
167    unsafe fn links(ptr: NonNull<Self>) -> NonNull<Links<Self>> {
168        default_retry_links_inner(ptr)
169    }
170}
171pub(super) fn release_retry_unit<C: ExecutorClock<Instant = GlobalManualInstant>, L: 'static>(
172    node: &CancelRetryNode<C, L>,
173) {
174    default_release_unit_inner(node)
175}
176// 原节点表示留在本模块;本地拥有者只取得已配对的取消接续拥有者。
177pub(super) fn new_retry_owner<C, L>(
178    notifier: ThreadNotifier,
179    batch: std::num::NonZeroUsize,
180) -> RetryOwner<CancelRetryNode<C, L>>
181where
182    C: ExecutorClock<Instant = GlobalManualInstant>,
183    L: LocalTimerSubmit<DefaultTimerItem<C, L>>,
184{
185    default_retry_owner_new_inner(notifier, batch)
186}
187include!("access_inner.rs");