| 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::{mpsc, Semaphore}; |
| 26 |
|
| 27 |
|
| 28 |
const CAPACITY: usize = 1024; |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
const PARALLELISM: usize = 8; |
| 33 |
|
| 34 |
type BoxFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>; |
| 35 |
|
| 36 |
#[derive(Clone)] |
| 37 |
pub struct BackgroundTx { |
| 38 |
tx: mpsc::Sender<(&'static str, BoxFuture)>, |
| 39 |
} |
| 40 |
|
| 41 |
impl BackgroundTx { |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
pub fn spawn<F>(&self, name: &'static str, fut: F) |
| 46 |
where |
| 47 |
F: Future<Output = ()> + Send + 'static, |
| 48 |
{ |
| 49 |
if self.tx.try_send((name, Box::pin(fut))).is_err() { |
| 50 |
tracing::warn!(task = name, "background queue full, task dropped"); |
| 51 |
} |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
pub fn spawn_pool() -> BackgroundTx { |
| 59 |
let (tx, mut rx) = mpsc::channel::<(&'static str, BoxFuture)>(CAPACITY); |
| 60 |
let sem = Arc::new(Semaphore::new(PARALLELISM)); |
| 61 |
tokio::spawn(async move { |
| 62 |
while let Some((_, task)) = rx.recv().await { |
| 63 |
let permit = match sem.clone().acquire_owned().await { |
| 64 |
Ok(p) => p, |
| 65 |
Err(_) => break, |
| 66 |
}; |
| 67 |
tokio::spawn(async move { |
| 68 |
task.await; |
| 69 |
drop(permit); |
| 70 |
}); |
| 71 |
} |
| 72 |
tracing::info!("background-task drainer exited"); |
| 73 |
}); |
| 74 |
BackgroundTx { tx } |
| 75 |
} |
| 76 |
|