| 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 |
use once_cell::sync::Lazy; |
| 6 |
use std::sync::atomic::{AtomicBool, Ordering}; |
| 7 |
use std::sync::RwLock; |
| 8 |
use std::thread; |
| 9 |
use std::time::Duration; |
| 10 |
|
| 11 |
use super::{DispatchError, DispatchGuard, Dispatcher}; |
| 12 |
use crossbeam_channel::RecvTimeoutError; |
| 13 |
|
| 14 |
pub const GLOBAL_DISPATCHER_LIMIT: usize = 1000000; |
| 15 |
|
| 16 |
static GLOBAL_DISPATCHER: Lazy<RwLock<Option<Dispatcher>>> = |
| 17 |
Lazy::new(|| RwLock::new(Some(Dispatcher::new(GLOBAL_DISPATCHER_LIMIT)))); |
| 18 |
pub static TESTING_MODE: AtomicBool = AtomicBool::new(false); |
| 19 |
pub static QUEUE_TASKS: AtomicBool = AtomicBool::new(true); |
| 20 |
|
| 21 |
pub fn is_test_mode() -> bool { |
| 22 |
TESTING_MODE.load(Ordering::SeqCst) |
| 23 |
} |
| 24 |
|
| 25 |
/// Get a dispatcher for the global queue. |
| 26 |
/// |
| 27 |
/// A dispatcher is cheap to create, so we create one on every access instead of caching it. |
| 28 |
/// This avoids troubles for tests where the global dispatcher _can_ change. |
| 29 |
fn guard() -> DispatchGuard { |
| 30 |
GLOBAL_DISPATCHER |
| 31 |
.read() |
| 32 |
.unwrap() |
| 33 |
.as_ref() |
| 34 |
.map(|dispatcher| dispatcher.guard()) |
| 35 |
.unwrap() |
| 36 |
} |
| 37 |
|
| 38 |
/// Launches a new task on the global dispatch queue. |
| 39 |
/// |
| 40 |
/// The new task will be enqueued immediately. |
| 41 |
/// If the pre-init queue was already flushed, |
| 42 |
/// the background thread will process tasks in the queue (see [`flush_init`]). |
| 43 |
/// |
| 44 |
/// This will not block. |
| 45 |
/// |
| 46 |
/// [`flush_init`]: fn.flush_init.html |
| 47 |
pub fn launch(task: impl FnOnce() + Send + 'static) { |
| 48 |
let current_thread = thread::current(); |
| 49 |
if let Some("glean.shutdown") = current_thread.name() { |
| 50 |
log::error!("Tried to launch a task from the shutdown thread. That is forbidden."); |
| 51 |
} |
| 52 |
|
| 53 |
let guard = guard(); |
| 54 |
match guard.launch(task) { |
| 55 |
Ok(_) => {} |
| 56 |
Err(DispatchError::QueueFull) => { |
| 57 |
log::info!("Exceeded maximum queue size, discarding task"); |
| 58 |
// TODO: Record this as an error. |
| 59 |
} |
| 60 |
Err(_) => { |
| 61 |
log::info!("Failed to launch a task on the queue. Discarding task."); |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
// In test mode wait for the execution, unless we're still queueing tasks. |
| 66 |
let is_queueing = QUEUE_TASKS.load(Ordering::SeqCst); |
| 67 |
let is_test = TESTING_MODE.load(Ordering::SeqCst); |
| 68 |
if !is_queueing && is_test { |
| 69 |
guard.block_on_queue(); |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
/// Block until all tasks prior to this call are processed. |
| 74 |
pub fn block_on_queue() { |
| 75 |
guard().block_on_queue(); |
| 76 |
} |
| 77 |
|
| 78 |
/// Block until all tasks prior to this call are processed, with a timeout. |
| 79 |
pub fn block_on_queue_timeout(timeout: Duration) -> Result<(), RecvTimeoutError> { |
| 80 |
guard().block_on_queue_timeout(timeout) |
| 81 |
} |
| 82 |
|
| 83 |
/// Starts processing queued tasks in the global dispatch queue. |
| 84 |
/// |
| 85 |
/// This function blocks until queued tasks prior to this call are finished. |
| 86 |
/// Once the initial queue is empty the dispatcher will wait for new tasks to be launched. |
| 87 |
/// |
| 88 |
/// # Returns |
| 89 |
/// |
| 90 |
/// Returns the total number of items that were added to the queue before being flushed, |
| 91 |
/// or an error if the queue couldn't be flushed. |
| 92 |
pub fn flush_init() -> Result<usize, DispatchError> { |
| 93 |
guard().flush_init() |
| 94 |
} |
| 95 |
|
| 96 |
fn join_dispatcher_thread() -> Result<(), DispatchError> { |
| 97 |
// After we issue the shutdown command, make sure to wait for the |
| 98 |
// worker thread to join. |
| 99 |
let mut lock = GLOBAL_DISPATCHER.write().unwrap(); |
| 100 |
let dispatcher = lock.as_mut().expect("Global dispatcher has gone missing"); |
| 101 |
|
| 102 |
if let Some(worker) = dispatcher.worker.take() { |
| 103 |
return worker.join().map_err(|_| DispatchError::WorkerPanic); |
| 104 |
} |
| 105 |
|
| 106 |
Ok(()) |
| 107 |
} |
| 108 |
|
| 109 |
/// Kill the blocked dispatcher without processing the queue. |
| 110 |
/// |
| 111 |
/// This will immediately shutdown the worker thread |
| 112 |
/// and no other tasks will be processed. |
| 113 |
/// This only has an effect when the queue is still blocked. |
| 114 |
pub fn kill() -> Result<(), DispatchError> { |
| 115 |
guard().kill()?; |
| 116 |
join_dispatcher_thread() |
| 117 |
} |
| 118 |
|
| 119 |
/// Shuts down the dispatch queue. |
| 120 |
/// |
| 121 |
/// This will initiate a shutdown of the worker thread |
| 122 |
/// and no new tasks will be processed after this. |
| 123 |
pub fn shutdown() -> Result<(), DispatchError> { |
| 124 |
guard().shutdown()?; |
| 125 |
join_dispatcher_thread() |
| 126 |
} |
| 127 |
|
| 128 |
/// TEST ONLY FUNCTION. |
| 129 |
/// Resets the Glean state and triggers init again. |
| 130 |
pub(crate) fn reset_dispatcher() { |
| 131 |
// We don't care about shutdown errors, since they will |
| 132 |
// definitely happen if this is run concurrently. |
| 133 |
// We will still replace the global dispatcher. |
| 134 |
let _ = shutdown(); |
| 135 |
|
| 136 |
// New dispatcher = we're queuing again. |
| 137 |
QUEUE_TASKS.store(true, Ordering::SeqCst); |
| 138 |
|
| 139 |
// Now that the dispatcher is shut down, replace it. |
| 140 |
// For that we |
| 141 |
// 1. Create a new |
| 142 |
// 2. Replace the global one |
| 143 |
// 3. Only then return (and thus release the lock) |
| 144 |
let mut lock = GLOBAL_DISPATCHER.write().unwrap(); |
| 145 |
let new_dispatcher = Some(Dispatcher::new(GLOBAL_DISPATCHER_LIMIT)); |
| 146 |
*lock = new_dispatcher; |
| 147 |
} |
| 148 |
|
| 149 |
#[cfg(test)] |
| 150 |
mod test { |
| 151 |
use std::sync::{Arc, Mutex}; |
| 152 |
|
| 153 |
use super::*; |
| 154 |
|
| 155 |
#[test] |
| 156 |
#[ignore] // We can't reset the queue at the moment, so filling it up breaks other tests. |
| 157 |
fn global_fills_up_in_order_and_works() { |
| 158 |
let _ = env_logger::builder().is_test(true).try_init(); |
| 159 |
|
| 160 |
let result = Arc::new(Mutex::new(vec![])); |
| 161 |
|
| 162 |
for i in 1..=GLOBAL_DISPATCHER_LIMIT { |
| 163 |
let result = Arc::clone(&result); |
| 164 |
launch(move || { |
| 165 |
result.lock().unwrap().push(i); |
| 166 |
}); |
| 167 |
} |
| 168 |
|
| 169 |
{ |
| 170 |
let result = Arc::clone(&result); |
| 171 |
launch(move || { |
| 172 |
result.lock().unwrap().push(150); |
| 173 |
}); |
| 174 |
} |
| 175 |
|
| 176 |
flush_init().unwrap(); |
| 177 |
|
| 178 |
{ |
| 179 |
let result = Arc::clone(&result); |
| 180 |
launch(move || { |
| 181 |
result.lock().unwrap().push(200); |
| 182 |
}); |
| 183 |
} |
| 184 |
|
| 185 |
block_on_queue(); |
| 186 |
|
| 187 |
let mut expected = (1..=GLOBAL_DISPATCHER_LIMIT).collect::<Vec<_>>(); |
| 188 |
expected.push(200); |
| 189 |
assert_eq!(&*result.lock().unwrap(), &expected); |
| 190 |
} |
| 191 |
|
| 192 |
#[test] |
| 193 |
#[ignore] // We can't reset the queue at the moment, so flushing it breaks other tests. |
| 194 |
fn global_nested_calls() { |
| 195 |
let _ = env_logger::builder().is_test(true).try_init(); |
| 196 |
|
| 197 |
let result = Arc::new(Mutex::new(vec![])); |
| 198 |
|
| 199 |
{ |
| 200 |
let result = Arc::clone(&result); |
| 201 |
launch(move || { |
| 202 |
result.lock().unwrap().push(1); |
| 203 |
}); |
| 204 |
} |
| 205 |
|
| 206 |
flush_init().unwrap(); |
| 207 |
|
| 208 |
{ |
| 209 |
let result = Arc::clone(&result); |
| 210 |
launch(move || { |
| 211 |
result.lock().unwrap().push(21); |
| 212 |
|
| 213 |
{ |
| 214 |
let result = Arc::clone(&result); |
| 215 |
launch(move || { |
| 216 |
result.lock().unwrap().push(3); |
| 217 |
}); |
| 218 |
} |
| 219 |
|
| 220 |
result.lock().unwrap().push(22); |
| 221 |
}); |
| 222 |
} |
| 223 |
|
| 224 |
block_on_queue(); |
| 225 |
|
| 226 |
let expected = vec![1, 21, 22, 3]; |
| 227 |
assert_eq!(&*result.lock().unwrap(), &expected); |
| 228 |
} |
| 229 |
} |