Debian Codegraph @

third_party/rust/glean-core/src/dispatcher/mod.rs

raw
1 // This Source Code Form is subject to the terms of the Mozilla Public
2 // License, v. 2.0. If a copy of the MPL was not distributed with this
3 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5 //! A global dispatcher queue.
6 //!
7 //! # Example - Global Dispatch queue
8 //!
9 //! The global dispatch queue is pre-configured with a maximum queue size of 100 tasks.
10 //!
11 //! ```rust,ignore
12 //! // Ensure the dispatcher queue is being worked on.
13 //! dispatcher::flush_init();
14 //!
15 //! dispatcher::launch(|| {
16 //! println!("Executing expensive task");
17 //! // Run your expensive task in a separate thread.
18 //! });
19 //!
20 //! dispatcher::launch(|| {
21 //! println!("A second task that's executed sequentially, but off the main thread.");
22 //! });
23 //! ```
24
25 use std::{
26 mem,
27 sync::{
28 atomic::{AtomicBool, AtomicUsize, Ordering},
29 Arc,
30 },
31 thread::{self, JoinHandle},
32 time::Duration,
33 };
34
35 use crossbeam_channel::{bounded, unbounded, RecvTimeoutError, SendError, Sender};
36 use thiserror::Error;
37
38 pub use global::*;
39
40 pub(crate) mod global;
41
42 /// Command received while blocked from further work.
43 enum Blocked {
44 /// Shutdown immediately without processing the queue.
45 Shutdown,
46 /// Unblock and continue with work as normal.
47 Continue,
48 }
49
50 /// The command a worker should execute.
51 enum Command {
52 /// A task is a user-defined function to run.
53 Task(Box<dyn FnOnce() + Send>),
54
55 /// Swap the channel
56 Swap(Sender<()>),
57
58 /// Signal the worker to finish work and shut down.
59 Shutdown,
60 }
61
62 /// The error returned from operations on the dispatcher
63 #[derive(Error, Debug, PartialEq, Eq)]
64 pub enum DispatchError {
65 /// The worker panicked while running a task
66 #[error("The worker panicked while running a task")]
67 WorkerPanic,
68
69 /// Maximum queue size reached
70 #[error("Maximum queue size reached")]
71 QueueFull,
72
73 /// Pre-init buffer was already flushed
74 #[error("Pre-init buffer was already flushed")]
75 AlreadyFlushed,
76
77 /// Failed to send command to worker thread
78 #[error("Failed to send command to worker thread")]
79 SendError,
80
81 /// Failed to receive from channel
82 #[error("Failed to receive from channel")]
83 RecvError(#[from] crossbeam_channel::RecvError),
84 }
85
86 impl<T> From<SendError<T>> for DispatchError {
87 fn from(_: SendError<T>) -> Self {
88 DispatchError::SendError
89 }
90 }
91
92 /// A clonable guard for a dispatch queue.
93 #[derive(Clone)]
94 struct DispatchGuard {
95 /// Whether to queue on the preinit buffer or on the unbounded queue
96 queue_preinit: Arc<AtomicBool>,
97
98 /// The number of items that were added to the queue after it filled up.
99 overflow_count: Arc<AtomicUsize>,
100
101 /// The maximum pre-init queue size
102 max_queue_size: usize,
103
104 /// Used to unblock the worker thread initially.
105 block_sender: Sender<Blocked>,
106
107 /// Sender for the preinit queue.
108 preinit_sender: Sender<Command>,
109
110 /// Sender for the unbounded queue.
111 sender: Sender<Command>,
112 }
113
114 impl DispatchGuard {
115 pub fn launch(&self, task: impl FnOnce() + Send + 'static) -> Result<(), DispatchError> {
116 let task = Command::Task(Box::new(task));
117 self.send(task)
118 }
119
120 pub fn shutdown(&mut self) -> Result<(), DispatchError> {
121 // Need to flush in order for the thread to actually process anything,
122 // including the shutdown command.
123 self.flush_init().ok();
124 self.send(Command::Shutdown)
125 }
126
127 fn send(&self, task: Command) -> Result<(), DispatchError> {
128 if self.queue_preinit.load(Ordering::SeqCst) {
129 if self.preinit_sender.len() < self.max_queue_size {
130 self.preinit_sender.send(task)?;
131 Ok(())
132 } else {
133 self.overflow_count.fetch_add(1, Ordering::SeqCst);
134 // Instead of using a bounded queue, we are handling the bounds
135 // checking ourselves. If a bounded queue were full, we would return
136 // a QueueFull DispatchError, so we do the same here.
137 Err(DispatchError::QueueFull)
138 }
139 } else {
140 self.sender.send(task)?;
141 Ok(())
142 }
143 }
144
145 fn block_on_queue(&self) {
146 let (tx, rx) = crossbeam_channel::bounded(0);
147
148 // We explicitly don't use `self.launch` here.
149 // We always put this task on the unbounded queue.
150 // The pre-init queue might be full before its flushed, in which case this would panic.
151 // Blocking on the queue can only work if it is eventually flushed anyway.
152
153 let task = Command::Task(Box::new(move || {
154 tx.send(())
155 .expect("(worker) Can't send message on single-use channel");
156 }));
157 self.sender
158 .send(task)
159 .expect("Failed to launch the blocking task");
160
161 rx.recv()
162 .expect("Failed to receive message on single-use channel");
163 }
164
165 /// Block on the task queue emptying, with a timeout.
166 fn block_on_queue_timeout(&self, timeout: Duration) -> Result<(), RecvTimeoutError> {
167 let (tx, rx) = crossbeam_channel::bounded(0);
168
169 // We explicitly don't use `self.launch` here.
170 // We always put this task on the unbounded queue.
171 // The pre-init queue might be full before its flushed, in which case this would panic.
172 // Blocking on the queue can only work if it is eventually flushed anyway.
173
174 let task = Command::Task(Box::new(move || {
175 // In case the calling thread times out waiting for this
176 // the channel will be dropped.
177 // But in case the work continues we don't want to panic.
178 _ = tx.send(());
179 }));
180 self.sender
181 .send(task)
182 .expect("Failed to launch the blocking task");
183
184 rx.recv_timeout(timeout)
185 }
186
187 fn kill(&mut self) -> Result<(), DispatchError> {
188 // We immediately stop queueing in the pre-init buffer.
189 let old_val = self.queue_preinit.swap(false, Ordering::SeqCst);
190 if !old_val {
191 return Err(DispatchError::AlreadyFlushed);
192 }
193
194 // Unblock the worker thread exactly once.
195 self.block_sender.send(Blocked::Shutdown)?;
196 Ok(())
197 }
198
199 /// Flushes the pre-init buffer.
200 ///
201 /// This function blocks until tasks queued prior to this call are finished.
202 /// Once the initial queue is empty the dispatcher will wait for new tasks to be launched.
203 ///
204 /// Returns an error if called multiple times.
205 fn flush_init(&mut self) -> Result<usize, DispatchError> {
206 // We immediately stop queueing in the pre-init buffer.
207 let old_val = self.queue_preinit.swap(false, Ordering::SeqCst);
208 if !old_val {
209 return Err(DispatchError::AlreadyFlushed);
210 }
211
212 // Unblock the worker thread exactly once.
213 self.block_sender.send(Blocked::Continue)?;
214
215 // Single-use channel to communicate with the worker thread.
216 let (swap_sender, swap_receiver) = bounded(0);
217
218 // Send final command and block until it is sent.
219 self.preinit_sender
220 .send(Command::Swap(swap_sender))
221 .map_err(|_| DispatchError::SendError)?;
222
223 // Now wait for the worker thread to do the swap and inform us.
224 // This blocks until all tasks in the preinit buffer have been processed.
225 swap_receiver.recv()?;
226
227 // We're not queueing anymore.
228 global::QUEUE_TASKS.store(false, Ordering::SeqCst);
229
230 let overflow_count = self.overflow_count.load(Ordering::SeqCst);
231 if overflow_count > 0 {
232 Ok(overflow_count)
233 } else {
234 Ok(0)
235 }
236 }
237 }
238
239 /// A dispatcher.
240 ///
241 /// Run expensive processing tasks sequentially off the main thread.
242 /// Tasks are processed in a single separate thread in the order they are submitted.
243 /// The dispatch queue will enqueue tasks while not flushed, up to the maximum queue size.
244 /// Processing will start after flushing once, processing already enqueued tasks first, then
245 /// waiting for further tasks to be enqueued.
246 pub struct Dispatcher {
247 /// Guard used for communication with the worker thread.
248 guard: DispatchGuard,
249
250 /// Handle to the worker thread, allows to wait for it to finish.
251 worker: Option<JoinHandle<()>>,
252 }
253
254 impl Dispatcher {
255 /// Creates a new dispatcher with a maximum queue size.
256 ///
257 /// Launched tasks won't run until [`flush_init`] is called.
258 ///
259 /// [`flush_init`]: #method.flush_init
260 pub fn new(max_queue_size: usize) -> Self {
261 let (block_sender, block_receiver) = bounded(1);
262 let (preinit_sender, preinit_receiver) = unbounded();
263 let (sender, mut unbounded_receiver) = unbounded();
264
265 let queue_preinit = Arc::new(AtomicBool::new(true));
266 let overflow_count = Arc::new(AtomicUsize::new(0));
267
268 let worker = thread::Builder::new()
269 .name("glean.dispatcher".into())
270 .spawn(move || {
271 match block_receiver.recv() {
272 Err(_) => {
273 // The other side was disconnected.
274 // There's nothing the worker thread can do.
275 log::error!("The task producer was disconnected. Worker thread will exit.");
276 return;
277 }
278 Ok(Blocked::Shutdown) => {
279 // The other side wants us to stop immediately
280 return;
281 }
282 Ok(Blocked::Continue) => {
283 // Queue is unblocked, processing continues as normal.
284 }
285 }
286
287 let mut receiver = preinit_receiver;
288 loop {
289 use Command::*;
290
291 match receiver.recv() {
292 Ok(Shutdown) => {
293 break;
294 }
295
296 Ok(Task(f)) => {
297 (f)();
298 }
299
300 Ok(Swap(swap_done)) => {
301 // A swap should only occur exactly once.
302 // This is upheld by `flush_init`, which errors out if the preinit buffer
303 // was already flushed.
304
305 // We swap the channels we listen on for new tasks.
306 // The next iteration will continue with the unbounded queue.
307 mem::swap(&mut receiver, &mut unbounded_receiver);
308
309 // The swap command MUST be the last one received on the preinit buffer,
310 // so by the time we run this we know all preinit tasks were processed.
311 // We can notify the other side.
312 swap_done
313 .send(())
314 .expect("The caller of `flush_init` has gone missing");
315 }
316
317 // Other side was disconnected.
318 Err(_) => {
319 log::error!(
320 "The task producer was disconnected. Worker thread will exit."
321 );
322 return;
323 }
324 }
325 }
326 })
327 .expect("Failed to spawn Glean's dispatcher thread");
328
329 let guard = DispatchGuard {
330 queue_preinit,
331 overflow_count,
332 max_queue_size,
333 block_sender,
334 preinit_sender,
335 sender,
336 };
337
338 Dispatcher {
339 guard,
340 worker: Some(worker),
341 }
342 }
343
344 fn guard(&self) -> DispatchGuard {
345 self.guard.clone()
346 }
347
348 /// Waits for the worker thread to finish and finishes the dispatch queue.
349 ///
350 /// You need to call `shutdown` to initiate a shutdown of the queue.
351 #[cfg(test)]
352 fn join(mut self) -> Result<(), DispatchError> {
353 if let Some(worker) = self.worker.take() {
354 worker.join().map_err(|_| DispatchError::WorkerPanic)?;
355 }
356 Ok(())
357 }
358 }
359
360 #[cfg(test)]
361 mod test {
362 use super::*;
363 use std::sync::atomic::AtomicU8;
364 use std::sync::Mutex;
365
366 fn enable_test_logging() {
367 // When testing we want all logs to go to stdout/stderr by default,
368 // without requiring each individual test to activate it.
369 let _ = env_logger::builder().is_test(true).try_init();
370 }
371
372 #[test]
373 fn tasks_run_off_the_main_thread() {
374 enable_test_logging();
375
376 let main_thread_id = thread::current().id();
377 let thread_canary = Arc::new(AtomicBool::new(false));
378
379 let dispatcher = Dispatcher::new(100);
380
381 // Force the Dispatcher out of the pre-init queue mode.
382 dispatcher
383 .guard()
384 .flush_init()
385 .expect("Failed to get out of preinit queue mode");
386
387 let canary_clone = thread_canary.clone();
388 dispatcher
389 .guard()
390 .launch(move || {
391 assert!(thread::current().id() != main_thread_id);
392 // Use the canary bool to make sure this is getting called before
393 // the test completes.
394 assert!(!canary_clone.load(Ordering::SeqCst));
395 canary_clone.store(true, Ordering::SeqCst);
396 })
397 .expect("Failed to dispatch the test task");
398
399 dispatcher.guard().block_on_queue();
400 assert!(thread_canary.load(Ordering::SeqCst));
401 assert_eq!(main_thread_id, thread::current().id());
402 }
403
404 #[test]
405 fn launch_correctly_adds_tasks_to_preinit_queue() {
406 enable_test_logging();
407
408 let main_thread_id = thread::current().id();
409 let thread_canary = Arc::new(AtomicU8::new(0));
410
411 let dispatcher = Dispatcher::new(100);
412
413 // Add 3 tasks to queue each one increasing thread_canary by 1 to
414 // signal that the tasks ran.
415 for _ in 0..3 {
416 let canary_clone = thread_canary.clone();
417 dispatcher
418 .guard()
419 .launch(move || {
420 // Make sure the task is flushed off-the-main thread.
421 assert!(thread::current().id() != main_thread_id);
422 canary_clone.fetch_add(1, Ordering::SeqCst);
423 })
424 .expect("Failed to dispatch the test task");
425 }
426
427 // Ensure that no task ran.
428 assert_eq!(0, thread_canary.load(Ordering::SeqCst));
429
430 // Flush the queue and wait for the tasks to complete.
431 dispatcher
432 .guard()
433 .flush_init()
434 .expect("Failed to get out of preinit queue mode");
435 // Validate that we have the expected canary value.
436 assert_eq!(3, thread_canary.load(Ordering::SeqCst));
437 }
438
439 #[test]
440 fn preinit_tasks_are_processed_after_flush() {
441 enable_test_logging();
442
443 let dispatcher = Dispatcher::new(10);
444
445 let result = Arc::new(Mutex::new(vec![]));
446 for i in 1..=5 {
447 let result = Arc::clone(&result);
448 dispatcher
449 .guard()
450 .launch(move || {
451 result.lock().unwrap().push(i);
452 })
453 .unwrap();
454 }
455
456 result.lock().unwrap().push(0);
457 dispatcher.guard().flush_init().unwrap();
458 for i in 6..=10 {
459 let result = Arc::clone(&result);
460 dispatcher
461 .guard()
462 .launch(move || {
463 result.lock().unwrap().push(i);
464 })
465 .unwrap();
466 }
467
468 dispatcher.guard().block_on_queue();
469
470 // This additionally checks that tasks were executed in order.
471 assert_eq!(
472 &*result.lock().unwrap(),
473 &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
474 );
475 }
476
477 #[test]
478 fn tasks_after_shutdown_are_not_processed() {
479 enable_test_logging();
480
481 let dispatcher = Dispatcher::new(10);
482
483 let result = Arc::new(Mutex::new(vec![]));
484
485 dispatcher.guard().flush_init().unwrap();
486
487 dispatcher.guard().shutdown().unwrap();
488 {
489 let result = Arc::clone(&result);
490 // This might fail because the shutdown is quick enough,
491 // or it might succeed and still send the task.
492 // In any case that task should not be executed.
493 let _ = dispatcher.guard().launch(move || {
494 result.lock().unwrap().push(0);
495 });
496 }
497
498 dispatcher.join().unwrap();
499
500 assert!(result.lock().unwrap().is_empty());
501 }
502
503 #[test]
504 fn preinit_buffer_fills_up() {
505 enable_test_logging();
506
507 let dispatcher = Dispatcher::new(5);
508
509 let result = Arc::new(Mutex::new(vec![]));
510
511 for i in 1..=5 {
512 let result = Arc::clone(&result);
513 dispatcher
514 .guard()
515 .launch(move || {
516 result.lock().unwrap().push(i);
517 })
518 .unwrap();
519 }
520
521 {
522 let result = Arc::clone(&result);
523 let err = dispatcher.guard().launch(move || {
524 result.lock().unwrap().push(10);
525 });
526 assert_eq!(Err(DispatchError::QueueFull), err);
527 }
528
529 dispatcher.guard().flush_init().unwrap();
530
531 {
532 let result = Arc::clone(&result);
533 dispatcher
534 .guard()
535 .launch(move || {
536 result.lock().unwrap().push(20);
537 })
538 .unwrap();
539 }
540
541 dispatcher.guard().block_on_queue();
542
543 assert_eq!(&*result.lock().unwrap(), &[1, 2, 3, 4, 5, 20]);
544 }
545
546 #[test]
547 fn normal_queue_is_unbounded() {
548 enable_test_logging();
549
550 // Note: We can't actually test that it's fully unbounded,
551 // but we can quickly queue more slow tasks than the pre-init buffer holds
552 // and then guarantuee they all run.
553
554 let dispatcher = Dispatcher::new(5);
555
556 let result = Arc::new(Mutex::new(vec![]));
557
558 for i in 1..=5 {
559 let result = Arc::clone(&result);
560 dispatcher
561 .guard()
562 .launch(move || {
563 result.lock().unwrap().push(i);
564 })
565 .unwrap();
566 }
567
568 dispatcher.guard().flush_init().unwrap();
569
570 // Queue more than 5 tasks,
571 // Each one is slow to process, so we should be faster in queueing
572 // them up than they are processed.
573 for i in 6..=20 {
574 let result = Arc::clone(&result);
575 dispatcher
576 .guard()
577 .launch(move || {
578 thread::sleep(Duration::from_millis(50));
579 result.lock().unwrap().push(i);
580 })
581 .unwrap();
582 }
583
584 dispatcher.guard().shutdown().unwrap();
585 dispatcher.join().unwrap();
586
587 let expected = (1..=20).collect::<Vec<_>>();
588 assert_eq!(&*result.lock().unwrap(), &expected);
589 }
590 }