Skip to main content

ntex_rt/time/
callbacks.rs

1use std::num::NonZeroU64;
2use std::{cell::Cell, cmp, fmt, rc::Rc, rc::Weak};
3
4use crate::HashMap;
5
6use super::{TimerEntry, with_slot, with_timer};
7
8/// A reusable, local one-shot callback timer.
9///
10/// Each construction or reset arms one invocation of the retained callback.
11/// The callback may capture `Rc` state; this handle is neither `Send` nor `Sync`
12/// and cannot be cloned. Keep the handle alive until the callback should run.
13/// Dropping it cancels pending delivery, including an expired callback that has
14/// not started, and releases its captures. An active invocation retains its
15/// captures until it finishes.
16///
17/// Expiration and cancellation retain the callback for reuse. The callback
18/// implements `Fn`, so use interior mutability for state that changes between
19/// invocations.
20///
21/// Callbacks run outside wheel access and may create, reset, cancel or drop
22/// timers, including themselves. They must be short, synchronous and
23/// non-blocking. Callbacks due on the same tick have no guaranteed order.
24///
25/// Callback panics propagate through the runtime. They may stop the shared
26/// driver and disarm other timers; remaining callbacks need not be delivered.
27/// Runtime shutdown suppresses pending delivery. Outside of a native
28/// [`Runtime`](crate::rt::Runtime), a surviving handle retains its callback
29/// and can be explicitly reset in a new runtime on the same thread. Starting
30/// a new runtime does not automatically rearm the handle.
31///
32/// Inside a native runtime the callback is registered with the wheel of that
33/// runtime. Once the runtime is dropped, or while it is not active on the
34/// thread, the handle is stale: it reports the timer as elapsed and ignores
35/// resets.
36pub struct CallbackHandle {
37    pub(super) hnd: NonZeroU64,
38    pub(super) state: Rc<CallbackState>,
39}
40
41impl CallbackHandle {
42    #[allow(clippy::missing_panics_doc)] // unwraps only check wheel invariants
43    /// Arms a callback after `millis`, using the wheel's rounding and limits.
44    ///
45    /// The base granularity is approximately 16 ms by default, see
46    /// [`Builder::timer_resolution`](crate::Builder::timer_resolution);
47    /// longer delays use coarser rounding, and delays beyond the wheel's
48    /// capacity (about 24 days at 16 ms) are clamped. Callback delivery may be
49    /// delayed further while the runtime is busy.
50    ///
51    /// A zero delay waits for a subsequent timer tick; the callback is never
52    /// invoked inline.
53    pub fn new(millis: u64, callback: impl Fn() + 'static) -> Self {
54        let state = Rc::new(CallbackState {
55            callback: Box::new(callback),
56            arm: Cell::new(0),
57            pending: Cell::new(true),
58        });
59        with_timer(|timer| {
60            let (idx, expiry) = timer.calc_bucket(cmp::max(millis, 1));
61            let no = timer.with_wheel(|wheel| {
62                let no = wheel.timers.insert(TimerEntry {
63                    bucket: None,
64                    bucket_entry: 0,
65                    callback: true,
66                    task: None,
67                });
68                wheel
69                    .callbacks
70                    .get_or_insert_with(|| Box::new(Callbacks::default()))
71                    .entries
72                    .insert(
73                        no,
74                        CallbackTicket {
75                            state: Rc::downgrade(&state),
76                            arm: 0,
77                            generation: timer.generation.get(),
78                        },
79                    );
80                wheel.link(no, idx);
81                no
82            });
83            let handle = Self {
84                hnd: timer.handle(no),
85                state,
86            };
87            timer.update_next_expiry(expiry);
88            handle
89        })
90    }
91
92    #[allow(clippy::missing_panics_doc)] // unwraps only check wheel invariants
93    /// Arms another invocation, invalidating any previous pending delivery.
94    ///
95    /// This also suppresses an expired invocation that has been queued but has
96    /// not started. It can be called before or after expiration or cancellation.
97    ///
98    /// A zero delay waits for a subsequent tick. Resetting from within the
99    /// callback arms a new invocation, which survives completion of the old one.
100    pub fn reset(&self, millis: u64) {
101        with_slot(self.hnd, |timer, slot| {
102            let (idx, expiry) = timer.calc_bucket(cmp::max(millis, 1));
103            timer.with_wheel(|wheel| {
104                let ticket = wheel
105                    .callbacks
106                    .as_mut()
107                    .unwrap()
108                    .entries
109                    .get_mut(&slot)
110                    .unwrap();
111                ticket.arm = ticket.arm.wrapping_add(1);
112                ticket.generation = timer.generation.get();
113                self.state.arm.set(ticket.arm);
114                self.state.pending.set(true);
115                wheel.relink(slot, idx);
116            });
117            timer.update_next_expiry(expiry);
118        });
119    }
120
121    /// Disarms the timer and suppresses pending delivery, retaining the callback.
122    ///
123    /// This also suppresses an expired invocation that has not started. Calling
124    /// this method on an already disarmed timer is harmless.
125    ///
126    /// An invocation that has already started cannot be interrupted.
127    pub fn cancel(&self) {
128        self.state.pending.set(false);
129        with_slot(self.hnd, |timer, slot| {
130            timer.with_wheel(|wheel| wheel.unlink(slot))
131        });
132    }
133
134    /// Returns `true` when disarmed, including after cancellation or shutdown.
135    ///
136    /// Expiration marks the timer elapsed before callback delivery. This query
137    /// does not indicate whether the callback has run.
138    pub fn is_elapsed(&self) -> bool {
139        with_slot(self.hnd, |timer, slot| {
140            timer.with_wheel(|wheel| wheel.timers[slot].bucket.is_none())
141        })
142        .unwrap_or(true)
143    }
144}
145
146impl fmt::Debug for CallbackHandle {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        f.debug_struct("CallbackHandle")
149            .field("handle", &self.hnd)
150            .finish_non_exhaustive()
151    }
152}
153
154impl Drop for CallbackHandle {
155    fn drop(&mut self) {
156        self.state.pending.set(false);
157        with_slot(self.hnd, |timer, slot| {
158            timer.with_wheel(|wheel| {
159                wheel.unlink(slot);
160                wheel.timers.remove(slot);
161                wheel.callbacks.as_mut().unwrap().entries.remove(&slot);
162            });
163        });
164    }
165}
166
167pub(super) struct CallbackState {
168    pub(super) callback: Box<dyn Fn()>,
169    pub(super) arm: Cell<u64>,
170    pub(super) pending: Cell<bool>,
171}
172
173#[derive(Clone)]
174pub(super) struct CallbackTicket {
175    // Weak identity prevents slab reuse from redirecting a delivery and lets
176    // handle drop release captures without waiting for the queued ticket.
177    pub(super) state: Weak<CallbackState>,
178    pub(super) arm: u64,
179    pub(super) generation: u64,
180}
181
182#[derive(Default)]
183pub(super) struct Callbacks {
184    pub(super) entries: HashMap<usize, CallbackTicket>,
185    pub(super) ready: Vec<CallbackTicket>,
186}