Skip to main content

euv_core/runtime/dispatcher/
impl.rs

1use super::*;
2
3/// Human-readable formatting for `DispatchError`.
4impl fmt::Display for DispatchError {
5    /// Formats a `DispatchError` diagnostic message.
6    ///
7    /// # Arguments
8    ///
9    /// - `&mut Formatter<'_>` - Output formatter.
10    ///
11    /// # Returns
12    ///
13    /// - `fmt::Result` - Formatting status.
14    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
15        let message: &str = match self {
16            Self::QueueFull => DISPATCHER_ERR_QUEUE_FULL,
17            Self::Closed => DISPATCHER_ERR_CLOSED,
18            Self::LockPoisoned => DISPATCHER_ERR_LOCK_POISONED,
19        };
20        formatter.write_str(message)
21    }
22}
23
24/// Standard `Error` implementation for `DispatchError`.
25impl Error for DispatchError {}
26
27/// Safe optional wakeup hook getter for `UiDispatcherQueues`.
28impl UiDispatcherQueues {
29    /// Clones the installed event-loop wakeup callback without panicking when absent.
30    ///
31    /// # Returns
32    ///
33    /// - `Option<Arc<dyn Fn() + Send + Sync>>` - Cloned wakeup callback handle, if registered.
34    #[must_use]
35    pub(crate) fn try_get_wakeup_hook(&self) -> Option<Arc<dyn Fn() + Send + Sync>> {
36        self.wakeup_hook.clone()
37    }
38}
39
40/// Structured diagnostic `Debug` formatting for `UiDispatcher`.
41impl fmt::Debug for UiDispatcher {
42    /// Formats live atomic dispatcher metrics without locking the internal queue.
43    ///
44    /// # Arguments
45    ///
46    /// - `&mut Formatter<'_>` - Output formatter.
47    ///
48    /// # Returns
49    ///
50    /// - `fmt::Result` - Formatting status.
51    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
52        let snapshot: UiDispatchMetrics = self.metrics();
53        write!(
54            formatter,
55            "UiDispatcher(pending={}, capacity={}, peak={}, enqueued={}, drained={}, closed={})",
56            snapshot.get_pending_count(),
57            snapshot.get_capacity(),
58            snapshot.get_peak_depth(),
59            snapshot.get_enqueued_total(),
60            snapshot.get_drained_total(),
61            snapshot.get_closed(),
62        )
63    }
64}
65
66/// Default bounded `UiDispatcher` using `DEFAULT_DISPATCHER_CAPACITY` and `RejectNew` backpressure.
67impl Default for UiDispatcher {
68    /// Creates a default bounded `UiDispatcher`.
69    ///
70    /// # Returns
71    ///
72    /// - `Self` - Ready cross-thread UI dispatcher handle.
73    fn default() -> Self {
74        Self::with_capacity(
75            DEFAULT_DISPATCHER_CAPACITY,
76            DispatchBackpressurePolicy::RejectNew,
77        )
78    }
79}
80
81/// Cross-thread posting, wakeup coalescing, and bounded UI-thread draining for `UiDispatcher`.
82impl UiDispatcher {
83    /// Creates a new `UiDispatcher` with an explicit queue capacity and backpressure policy.
84    ///
85    /// # Arguments
86    ///
87    /// - `usize` - Maximum number of buffered pending tasks (clamped to `>= 1`).
88    /// - `DispatchBackpressurePolicy` - Policy applied when the queue reaches capacity.
89    ///
90    /// # Returns
91    ///
92    /// - `Self` - Thread-safe `UiDispatcher` handle.
93    #[must_use]
94    pub fn with_capacity(capacity: usize, policy: DispatchBackpressurePolicy) -> Self {
95        let bounded_capacity: usize = capacity.max(1);
96        let shared: UiDispatcherShared = UiDispatcherShared {
97            capacity: bounded_capacity,
98            policy,
99            queues: Mutex::new(UiDispatcherQueues::default()),
100            pending_count: AtomicUsize::new(0),
101            peak_depth: AtomicUsize::new(0),
102            enqueued_total: AtomicU64::new(0),
103            drained_total: AtomicU64::new(0),
104            rejected_total: AtomicU64::new(0),
105            dropped_total: AtomicU64::new(0),
106            wakeup_invocations: AtomicU64::new(0),
107            wakeup_pending: AtomicBool::new(false),
108            closed: AtomicBool::new(false),
109        };
110        Self {
111            shared: Arc::new(shared),
112        }
113    }
114
115    /// Registers a platform event-loop wakeup callback invoked once whenever the queue transitions from idle to pending.
116    ///
117    /// # Arguments
118    ///
119    /// - `WakeFn` - Thread-safe wakeup callback (for example, signaling a `CFRunLoopSource`, Win32 event, or eventfd).
120    pub fn set_wakeup_hook<WakeFn>(&self, hook: WakeFn)
121    where
122        WakeFn: Fn() + Send + Sync + 'static,
123    {
124        if let Ok(mut guard) = self.get_shared().get_queues().lock() {
125            guard.set_wakeup_hook(Some(Arc::new(hook)));
126        }
127    }
128
129    /// Removes any previously installed event-loop wakeup callback.
130    pub fn clear_wakeup_hook(&self) {
131        if let Ok(mut guard) = self.get_shared().get_queues().lock() {
132            guard.set_wakeup_hook(None);
133        }
134    }
135
136    /// Enqueues a normal-priority UI mutation closure from any thread and signals the wakeup hook if coalescing permits.
137    ///
138    /// # Arguments
139    ///
140    /// - `TaskFn` - Sendable closure to execute on the UI thread.
141    ///
142    /// # Returns
143    ///
144    /// - `Result<u64, DispatchError>` - Monotonic submission sequence number or backpressure/closure error.
145    pub fn dispatch<TaskFn>(&self, task: TaskFn) -> Result<u64, DispatchError>
146    where
147        TaskFn: FnOnce() + Send + 'static,
148    {
149        self.dispatch_with_priority(DispatchPriority::Normal, task)
150    }
151
152    /// Enqueues a UI mutation closure into the specified priority lane and signals the wakeup hook if needed.
153    ///
154    /// # Arguments
155    ///
156    /// - `DispatchPriority` - Priority lane (`Critical`, `Normal`, or `Background`).
157    /// - `TaskFn` - Sendable closure to execute on the UI thread.
158    ///
159    /// # Returns
160    ///
161    /// - `Result<u64, DispatchError>` - Monotonic submission sequence number or backpressure/closure error.
162    pub fn dispatch_with_priority<TaskFn>(
163        &self,
164        priority: DispatchPriority,
165        task: TaskFn,
166    ) -> Result<u64, DispatchError>
167    where
168        TaskFn: FnOnce() + Send + 'static,
169    {
170        let shared: &UiDispatcherShared = self.get_shared().as_ref();
171        if shared.get_closed().load(Ordering::Acquire) {
172            let _: u64 = shared.get_rejected_total().fetch_add(1, Ordering::Relaxed);
173            return Err(DispatchError::Closed);
174        }
175        let wakeup_to_call: Option<Arc<dyn Fn() + Send + Sync>>;
176        let assigned_sequence: u64;
177        {
178            let Ok(mut guard) = shared.get_queues().lock() else {
179                let _: u64 = shared.get_rejected_total().fetch_add(1, Ordering::Relaxed);
180                return Err(DispatchError::LockPoisoned);
181            };
182            if shared.get_closed().load(Ordering::Acquire) {
183                let _: u64 = shared.get_rejected_total().fetch_add(1, Ordering::Relaxed);
184                return Err(DispatchError::Closed);
185            }
186            let current_len: usize = total_queued_tasks(&guard);
187            if current_len >= shared.get_capacity() {
188                match shared.get_policy() {
189                    DispatchBackpressurePolicy::RejectNew => {
190                        let _: u64 = shared.get_rejected_total().fetch_add(1, Ordering::Relaxed);
191                        return Err(DispatchError::QueueFull);
192                    }
193                    DispatchBackpressurePolicy::DropOldest => {
194                        if drop_oldest_lowest_priority_task(&mut guard) {
195                            let _: u64 = shared.get_dropped_total().fetch_add(1, Ordering::Relaxed);
196                        }
197                    }
198                }
199            }
200            let next_seq: u64 = guard.get_next_sequence().saturating_add(1);
201            guard.set_next_sequence(next_seq);
202            assigned_sequence = next_seq;
203            let envelope: UiDispatchTask = UiDispatchTask {
204                sequence: assigned_sequence,
205                priority,
206                callback: Box::new(task),
207            };
208            match priority {
209                DispatchPriority::Critical => guard.get_mut_critical().push_back(envelope),
210                DispatchPriority::Normal => guard.get_mut_normal().push_back(envelope),
211                DispatchPriority::Background => guard.get_mut_background().push_back(envelope),
212            }
213            let updated_len: usize = total_queued_tasks(&guard);
214            shared
215                .get_pending_count()
216                .store(updated_len, Ordering::Release);
217            update_atomic_peak(shared.get_peak_depth(), updated_len);
218            let _: u64 = shared.get_enqueued_total().fetch_add(1, Ordering::Relaxed);
219            let should_wake: bool = !shared.get_wakeup_pending().swap(true, Ordering::AcqRel);
220            wakeup_to_call = if should_wake {
221                guard.try_get_wakeup_hook()
222            } else {
223                None
224            };
225        }
226        if let Some(wakeup_fn) = wakeup_to_call {
227            let _: u64 = shared
228                .get_wakeup_invocations()
229                .fetch_add(1, Ordering::Relaxed);
230            wakeup_fn();
231        }
232        Ok(assigned_sequence)
233    }
234
235    /// Returns `true` when at least one queued task awaits UI-thread draining (lock-free atomic read).
236    ///
237    /// # Returns
238    ///
239    /// - `bool` - `true` if pending tasks exist.
240    #[must_use]
241    pub fn has_pending(&self) -> bool {
242        self.pending_len() > 0
243    }
244
245    /// Returns the approximate count of pending queued tasks via a lock-free atomic load.
246    ///
247    /// # Returns
248    ///
249    /// - `usize` - Number of buffered tasks awaiting execution.
250    #[must_use]
251    pub fn pending_len(&self) -> usize {
252        self.get_shared()
253            .get_pending_count()
254            .load(Ordering::Acquire)
255    }
256
257    /// Pops up to `max_tasks` prioritized tasks from the internal queues and updates pending counters.
258    ///
259    /// # Arguments
260    ///
261    /// - `usize` - Maximum number of tasks to pop in one batch.
262    ///
263    /// # Returns
264    ///
265    /// - `(Vec<UiDispatchTask>, usize)` - Popped batch paired with the number of remaining queued tasks.
266    fn pop_batch(&self, max_tasks: usize) -> (Vec<UiDispatchTask>, usize) {
267        let shared: &UiDispatcherShared = self.get_shared().as_ref();
268        if max_tasks == 0 || !self.has_pending() {
269            return (Vec::new(), self.pending_len());
270        }
271        let Ok(mut guard) = shared.get_queues().lock() else {
272            return (Vec::new(), self.pending_len());
273        };
274        let available: usize = total_queued_tasks(&guard);
275        let take_count: usize = available.min(max_tasks);
276        let mut drained: Vec<UiDispatchTask> = Vec::with_capacity(take_count);
277        for _ in 0..take_count {
278            if let Some(task) = pop_next_prioritized_task(&mut guard) {
279                drained.push(task);
280            }
281        }
282        let remaining: usize = total_queued_tasks(&guard);
283        shared
284            .get_pending_count()
285            .store(remaining, Ordering::Release);
286        if remaining == 0 {
287            shared.get_wakeup_pending().store(false, Ordering::Release);
288        }
289        (drained, remaining)
290    }
291
292    /// Drains and executes up to `max_tasks` queued tasks on the UI thread inside a coalesced reactive `batch`.
293    ///
294    /// # Arguments
295    ///
296    /// - `usize` - Maximum number of tasks to execute in this frame slice.
297    ///
298    /// # Returns
299    ///
300    /// - `UiDrainSummary` - Executed count and remaining pending count.
301    pub fn drain_budget(&self, max_tasks: usize) -> UiDrainSummary {
302        let (tasks, remaining): (Vec<UiDispatchTask>, usize) = self.pop_batch(max_tasks);
303        let executed: usize = tasks.len();
304        if executed == 0 {
305            return UiDrainSummary::new(0, remaining, 0);
306        }
307        batch(|| {
308            for task in tasks {
309                let UiDispatchTask {
310                    sequence: _sequence,
311                    priority: _priority,
312                    callback,
313                } = task;
314                callback();
315            }
316        });
317        let _: u64 = self
318            .get_shared()
319            .get_drained_total()
320            .fetch_add(executed as u64, Ordering::Relaxed);
321        let live_remaining: usize = self.pending_len();
322        UiDrainSummary::new(executed, live_remaining, 0)
323    }
324
325    /// Drains up to `max_tasks` queued tasks inside a reactive `batch`, isolating each task panic with `boundary`.
326    ///
327    /// # Arguments
328    ///
329    /// - `usize` - Maximum number of tasks to execute in this frame slice.
330    /// - `&mut ErrorBoundary` - Fault boundary capturing panics from individual queued closures.
331    /// - `u64` - Monotonic timestamp in milliseconds stamped on any captured fault record.
332    ///
333    /// # Returns
334    ///
335    /// - `UiDrainSummary` - Executed count, remaining pending count, and number of panics isolated.
336    pub fn drain_budget_isolated(
337        &self,
338        max_tasks: usize,
339        boundary: &mut ErrorBoundary,
340        timestamp_ms: u64,
341    ) -> UiDrainSummary {
342        let (tasks, remaining): (Vec<UiDispatchTask>, usize) = self.pop_batch(max_tasks);
343        let executed: usize = tasks.len();
344        if executed == 0 {
345            return UiDrainSummary::new(0, remaining, 0);
346        }
347        let mut panics_caught: usize = 0;
348        batch(|| {
349            for task in tasks {
350                let UiDispatchTask {
351                    sequence: _sequence,
352                    priority: _priority,
353                    callback,
354                } = task;
355                let outcome: Result<(), FaultRecord> = boundary.guard(
356                    FaultOrigin::DispatcherTask,
357                    DISPATCHER_FAULT_SCOPE,
358                    timestamp_ms,
359                    callback,
360                );
361                if outcome.is_err() {
362                    panics_caught = panics_caught.saturating_add(1);
363                }
364            }
365        });
366        let _: u64 = self
367            .get_shared()
368            .get_drained_total()
369            .fetch_add(executed as u64, Ordering::Relaxed);
370        let live_remaining: usize = self.pending_len();
371        UiDrainSummary::new(executed, live_remaining, panics_caught)
372    }
373
374    /// Drains all currently queued tasks on the UI thread in bounded slices until the queue is empty.
375    ///
376    /// # Returns
377    ///
378    /// - `UiDrainSummary` - Aggregate executed task count and remaining pending count.
379    pub fn drain_all(&self) -> UiDrainSummary {
380        let mut total_executed: usize = 0;
381        loop {
382            let pending: usize = self.pending_len();
383            if pending == 0 {
384                break;
385            }
386            let slice: UiDrainSummary =
387                self.drain_budget(pending.max(DEFAULT_DISPATCHER_BATCH_LIMIT));
388            total_executed = total_executed.saturating_add(slice.get_executed());
389            if slice.get_executed() == 0 {
390                break;
391            }
392        }
393        UiDrainSummary::new(total_executed, self.pending_len(), 0)
394    }
395
396    /// Marks the dispatcher closed so subsequent cross-thread `dispatch` calls fail with `DispatchError::Closed`.
397    pub fn close(&self) {
398        self.get_shared()
399            .get_closed()
400            .store(true, Ordering::Release);
401    }
402
403    /// Returns `true` once `close()` has been called on this dispatcher.
404    ///
405    /// # Returns
406    ///
407    /// - `bool` - `true` when closed to new submissions.
408    #[must_use]
409    pub fn is_closed(&self) -> bool {
410        self.get_shared().get_closed().load(Ordering::Acquire)
411    }
412
413    /// Captures a lock-free telemetry snapshot of queue occupancy, peak depth, and backpressure counts.
414    ///
415    /// # Returns
416    ///
417    /// - `UiDispatchMetrics` - Current wait-free dispatcher metrics.
418    #[must_use]
419    pub fn metrics(&self) -> UiDispatchMetrics {
420        let shared: &UiDispatcherShared = self.get_shared().as_ref();
421        UiDispatchMetrics {
422            pending_count: shared.get_pending_count().load(Ordering::Acquire),
423            capacity: shared.get_capacity(),
424            peak_depth: shared.get_peak_depth().load(Ordering::Acquire),
425            enqueued_total: shared.get_enqueued_total().load(Ordering::Relaxed),
426            drained_total: shared.get_drained_total().load(Ordering::Relaxed),
427            rejected_total: shared.get_rejected_total().load(Ordering::Relaxed),
428            dropped_total: shared.get_dropped_total().load(Ordering::Relaxed),
429            wakeup_invocations: shared.get_wakeup_invocations().load(Ordering::Relaxed),
430            closed: shared.get_closed().load(Ordering::Acquire),
431        }
432    }
433}