| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
use std::future::Future; |
| 23 |
use std::pin::Pin; |
| 24 |
use std::sync::Arc; |
| 25 |
use tokio::sync::{Semaphore, mpsc, watch}; |
| 26 |
use tokio::task::JoinHandle; |
| 27 |
|
| 28 |
|
| 29 |
const CAPACITY: usize = 1024; |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
const PARALLELISM: usize = 8; |
| 34 |
|
| 35 |
type BoxFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>; |
| 36 |
|
| 37 |
#[derive(Clone)] |
| 38 |
pub struct BackgroundTx { |
| 39 |
tx: mpsc::Sender<(&'static str, BoxFuture)>, |
| 40 |
} |
| 41 |
|
| 42 |
impl BackgroundTx { |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
pub fn spawn<F>(&self, name: &'static str, fut: F) |
| 47 |
where |
| 48 |
F: Future<Output = ()> + Send + 'static, |
| 49 |
{ |
| 50 |
if self.tx.try_send((name, Box::pin(fut))).is_err() { |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
metrics::counter!("background_tasks_dropped_total", "task" => name).increment(1); |
| 55 |
tracing::warn!(task = name, "background queue full, task dropped"); |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
pub fn spawn_pool(mut shutdown: watch::Receiver<()>) -> (BackgroundTx, JoinHandle<()>) { |
| 73 |
let (tx, mut rx) = mpsc::channel::<(&'static str, BoxFuture)>(CAPACITY); |
| 74 |
let sem = Arc::new(Semaphore::new(PARALLELISM)); |
| 75 |
let handle = tokio::spawn(async move { |
| 76 |
loop { |
| 77 |
tokio::select! { |
| 78 |
maybe = rx.recv() => match maybe { |
| 79 |
Some((_, task)) => run_task(&sem, task).await, |
| 80 |
None => break, |
| 81 |
}, |
| 82 |
|
| 83 |
|
| 84 |
_ = shutdown.changed() => break, |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
while let Ok((_, task)) = rx.try_recv() { |
| 92 |
run_task(&sem, task).await; |
| 93 |
} |
| 94 |
let _ = sem.acquire_many(PARALLELISM as u32).await; |
| 95 |
tracing::info!("background-task drainer exited"); |
| 96 |
}); |
| 97 |
(BackgroundTx { tx }, handle) |
| 98 |
} |
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
pub fn spawn_pool_detached() -> BackgroundTx { |
| 105 |
let (tx, rx) = watch::channel(()); |
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
std::mem::forget(tx); |
| 110 |
spawn_pool(rx).0 |
| 111 |
} |
| 112 |
|
| 113 |
|
| 114 |
async fn run_task(sem: &Arc<Semaphore>, task: BoxFuture) { |
| 115 |
let Ok(permit) = sem.clone().acquire_owned().await else { |
| 116 |
return; |
| 117 |
}; |
| 118 |
tokio::spawn(async move { |
| 119 |
task.await; |
| 120 |
drop(permit); |
| 121 |
}); |
| 122 |
} |
| 123 |
|
| 124 |
#[cfg(test)] |
| 125 |
mod tests { |
| 126 |
use super::*; |
| 127 |
use std::sync::atomic::{AtomicUsize, Ordering}; |
| 128 |
|
| 129 |
#[tokio::test] |
| 130 |
async fn drains_queued_tasks_on_shutdown() { |
| 131 |
let (shutdown_tx, shutdown_rx) = watch::channel(()); |
| 132 |
let (bg, handle) = spawn_pool(shutdown_rx); |
| 133 |
|
| 134 |
let counter = Arc::new(AtomicUsize::new(0)); |
| 135 |
for _ in 0..50 { |
| 136 |
let c = counter.clone(); |
| 137 |
bg.spawn("test", async move { |
| 138 |
c.fetch_add(1, Ordering::SeqCst); |
| 139 |
}); |
| 140 |
} |
| 141 |
|
| 142 |
|
| 143 |
drop(shutdown_tx); |
| 144 |
handle.await.expect("drainer joins cleanly"); |
| 145 |
|
| 146 |
assert_eq!( |
| 147 |
counter.load(Ordering::SeqCst), |
| 148 |
50, |
| 149 |
"every queued task must run before the drainer exits" |
| 150 |
); |
| 151 |
} |
| 152 |
|
| 153 |
#[tokio::test] |
| 154 |
async fn drainer_exits_when_all_senders_drop() { |
| 155 |
let (_shutdown_tx, shutdown_rx) = watch::channel(()); |
| 156 |
let (bg, handle) = spawn_pool(shutdown_rx); |
| 157 |
|
| 158 |
|
| 159 |
drop(bg); |
| 160 |
handle.await.expect("drainer exits when the queue closes"); |
| 161 |
} |
| 162 |
} |
| 163 |
|