Skip to main content

ntex_rt/
task.rs

1use std::{future::Future, sync::Arc, sync::atomic::AtomicUsize, sync::atomic::Ordering};
2
3// The Callbacks static holds a pointer to the global callbacks. It is protected by
4// the STATE static which determines whether `CBS` has been initialized yet.
5static mut CBS: Option<Arc<dyn CallbacksApi>> = None;
6
7static STATE: AtomicUsize = AtomicUsize::new(0);
8
9// There are three different states that we care about: the callback's
10// uninitialized, the callback's initializing (set_cbs's been called but
11// CBS hasn't actually been set yet), or the callbacks's active.
12const UNINITIALIZED: usize = 0;
13const INITIALIZING: usize = 1;
14const INITIALIZED: usize = 2;
15
16trait CallbacksApi {
17    fn before(&self) -> Option<*const ()>;
18    fn enter(&self, _: *const ()) -> *const ();
19    fn exit(&self, _: *const ());
20    fn after(&self, _: *const ());
21}
22
23#[allow(clippy::struct_field_names)]
24struct Callbacks<A, B, C, D> {
25    f_before: A,
26    f_enter: B,
27    f_exit: C,
28    f_after: D,
29}
30
31impl<A, B, C, D> CallbacksApi for Callbacks<A, B, C, D>
32where
33    A: Fn() -> Option<*const ()> + 'static,
34    B: Fn(*const ()) -> *const () + 'static,
35    C: Fn(*const ()) + 'static,
36    D: Fn(*const ()) + 'static,
37{
38    fn before(&self) -> Option<*const ()> {
39        (self.f_before)()
40    }
41    fn enter(&self, d: *const ()) -> *const () {
42        (self.f_enter)(d)
43    }
44    fn exit(&self, d: *const ()) {
45        (self.f_exit)(d);
46    }
47    fn after(&self, d: *const ()) {
48        (self.f_after)(d);
49    }
50}
51
52pub(crate) struct Data {
53    cb: &'static dyn CallbacksApi,
54    ptr: *const (),
55}
56
57impl Data {
58    #[allow(clippy::if_not_else)]
59    pub(crate) fn load() -> Option<Data> {
60        // `Acquire` pairs with the `Release` store in `set_cbs`, so `CBS` is visible
61        let cb = if STATE.load(Ordering::Acquire) != INITIALIZED {
62            None
63        } else {
64            #[allow(static_mut_refs)]
65            unsafe {
66                Some(CBS.as_ref().map(AsRef::as_ref).unwrap())
67            }
68        };
69
70        if let Some(cb) = cb
71            && let Some(ptr) = cb.before()
72        {
73            return Some(Data { cb, ptr });
74        }
75        None
76    }
77
78    pub(crate) fn run<F, R>(&mut self, f: F) -> R
79    where
80        F: FnOnce() -> R,
81    {
82        struct Exit(&'static dyn CallbacksApi, *const ());
83
84        impl Drop for Exit {
85            fn drop(&mut self) {
86                self.0.exit(self.1);
87            }
88        }
89
90        // `exit` also runs if `f` panics, so the context set by `enter` is restored
91        let _exit = Exit(self.cb, self.cb.enter(self.ptr));
92        f()
93    }
94}
95
96/// Wraps a future so that task callbacks, if registered, run around each poll.
97///
98/// Always returns the same future type, so spawning code is generated once
99/// per future rather than once per callback mode.
100pub(crate) fn wrap<F: Future>(fut: F) -> impl Future<Output = F::Output> {
101    let mut data = Data::load();
102    async move {
103        let mut f = std::pin::pin!(fut);
104        std::future::poll_fn(|cx| match data.as_mut() {
105            Some(data) => data.run(|| f.as_mut().poll(cx)),
106            None => f.as_mut().poll(cx),
107        })
108        .await
109    }
110}
111
112impl Drop for Data {
113    fn drop(&mut self) {
114        self.cb.after(self.ptr);
115    }
116}
117
118/// Installs process-wide callbacks for instrumenting spawned tasks.
119///
120/// Callbacks apply when [`crate::spawn`], [`crate::spawn_detached`],
121/// [`crate::rt::spawn`], or [`crate::rt::spawn_detached`] wraps a future, not
122/// retroactively to existing tasks. Direct [`crate::rt::Runtime`] spawning
123/// methods do not apply them.
124///
125/// - `f_before` runs synchronously when the future is wrapped. Returning `None`
126///   disables the remaining callbacks for that future.
127/// - `f_enter` receives the task's pointer before each poll and returns a pointer
128///   representing the previous context.
129/// - `f_exit` receives that previous-context pointer after the poll, including
130///   when polling unwinds.
131/// - `f_after` receives the task's original pointer when its callback state is
132///   dropped, including cancellation before the first poll.
133///
134/// Registration is permanent and first-wins. Does nothing if callbacks were
135/// already installed; use [`task_opt_callbacks`] to observe registration success.
136///
137/// # Safety
138///
139/// Pointers are opaque to the runtime. The caller must keep the state returned
140/// by `f_before` valid until `f_after`, and the state returned by `f_enter` valid
141/// until its matching `f_exit`. Callbacks must safely handle concurrent use by
142/// different runtime threads and any nested task activity they trigger.
143pub unsafe fn task_callbacks<FBefore, FEnter, FExit, FAfter>(
144    f_before: FBefore,
145    f_enter: FEnter,
146    f_exit: FExit,
147    f_after: FAfter,
148) where
149    FBefore: Fn() -> Option<*const ()> + 'static + Sync,
150    FEnter: Fn(*const ()) -> *const () + 'static + Sync,
151    FExit: Fn(*const ()) + 'static + Sync,
152    FAfter: Fn(*const ()) + 'static + Sync,
153{
154    let new = Arc::new(Callbacks {
155        f_before,
156        f_enter,
157        f_exit,
158        f_after,
159    });
160    let _ = set_cbs(new);
161}
162
163/// Attempts to install process-wide task callbacks.
164///
165/// Uses the callback lifecycle described by [`task_callbacks`]. Returns `true`
166/// if this call installs the callbacks, or `false` if another registration has
167/// already won. Installed callbacks cannot be replaced or removed.
168///
169/// # Safety
170///
171/// The pointer lifetimes and callback thread-safety requirements of
172/// [`task_callbacks`] apply.
173pub unsafe fn task_opt_callbacks<FBefore, FEnter, FExit, FAfter>(
174    f_before: FBefore,
175    f_enter: FEnter,
176    f_exit: FExit,
177    f_after: FAfter,
178) -> bool
179where
180    FBefore: Fn() -> Option<*const ()> + Sync + 'static,
181    FEnter: Fn(*const ()) -> *const () + Sync + 'static,
182    FExit: Fn(*const ()) + Sync + 'static,
183    FAfter: Fn(*const ()) + Sync + 'static,
184{
185    let new = Arc::new(Callbacks {
186        f_before,
187        f_enter,
188        f_exit,
189        f_after,
190    });
191    set_cbs(new).is_ok()
192}
193
194fn set_cbs(cbs: Arc<dyn CallbacksApi>) -> Result<(), ()> {
195    match STATE.compare_exchange(
196        UNINITIALIZED,
197        INITIALIZING,
198        Ordering::Acquire,
199        Ordering::Relaxed,
200    ) {
201        Ok(UNINITIALIZED) => {
202            unsafe {
203                CBS = Some(cbs);
204            }
205            STATE.store(INITIALIZED, Ordering::Release);
206            Ok(())
207        }
208        Err(INITIALIZING) => {
209            while STATE.load(Ordering::Relaxed) == INITIALIZING {
210                std::hint::spin_loop();
211            }
212            Err(())
213        }
214        _ => Err(()),
215    }
216}
217
218#[cfg(test)]
219#[path = "../tests/unit/task.rs"]
220mod tests;