euv_core/runtime/dispatcher/
impl.rs1use super::*;
2
3impl fmt::Display for DispatchError {
5 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
24impl Error for DispatchError {}
26
27impl UiDispatcherQueues {
29 #[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
40impl fmt::Debug for UiDispatcher {
42 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
66impl Default for UiDispatcher {
68 fn default() -> Self {
74 Self::with_capacity(
75 DEFAULT_DISPATCHER_CAPACITY,
76 DispatchBackpressurePolicy::RejectNew,
77 )
78 }
79}
80
81impl UiDispatcher {
83 #[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 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 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 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 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 #[must_use]
241 pub fn has_pending(&self) -> bool {
242 self.pending_len() > 0
243 }
244
245 #[must_use]
251 pub fn pending_len(&self) -> usize {
252 self.get_shared()
253 .get_pending_count()
254 .load(Ordering::Acquire)
255 }
256
257 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 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 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 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 pub fn close(&self) {
398 self.get_shared()
399 .get_closed()
400 .store(true, Ordering::Release);
401 }
402
403 #[must_use]
409 pub fn is_closed(&self) -> bool {
410 self.get_shared().get_closed().load(Ordering::Acquire)
411 }
412
413 #[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}