2023-11-24 18:28:46 +00:00
|
|
|
use tracing::{debug, trace, Instrument};
|
2021-06-28 12:30:23 +01:00
|
|
|
|
2023-11-19 12:50:11 +00:00
|
|
|
pub fn spawn(
|
|
|
|
|
span: tracing::Span,
|
2021-06-28 12:30:23 +01:00
|
|
|
fut: impl std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
|
2023-11-24 18:28:46 +00:00
|
|
|
) -> tokio::task::JoinHandle<()> {
|
2023-11-19 12:50:11 +00:00
|
|
|
let fut = async move {
|
|
|
|
|
trace!("started");
|
2021-06-28 12:30:23 +01:00
|
|
|
match fut.await {
|
|
|
|
|
Ok(_) => {
|
2023-11-19 12:50:11 +00:00
|
|
|
debug!("finished");
|
2021-06-28 12:30:23 +01:00
|
|
|
}
|
|
|
|
|
Err(e) => {
|
2023-11-24 18:28:46 +00:00
|
|
|
debug!("finished with error: {:#}", e)
|
2021-06-28 12:30:23 +01:00
|
|
|
}
|
|
|
|
|
}
|
2023-11-19 12:50:11 +00:00
|
|
|
}
|
|
|
|
|
.instrument(span.or_current());
|
2023-11-24 18:28:46 +00:00
|
|
|
tokio::spawn(fut)
|
2021-06-28 12:30:23 +01:00
|
|
|
}
|
2021-06-28 20:40:13 +01:00
|
|
|
|
2021-07-01 19:17:44 +01:00
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
|
|
|
pub struct BlockingSpawner {
|
|
|
|
|
allow_tokio_block_in_place: bool,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl BlockingSpawner {
|
|
|
|
|
pub fn new(allow_tokio_block_in_place: bool) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
allow_tokio_block_in_place,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
pub fn spawn_block_in_place<F: FnOnce() -> R, R>(&self, f: F) -> R {
|
|
|
|
|
if self.allow_tokio_block_in_place {
|
|
|
|
|
return tokio::task::block_in_place(f);
|
|
|
|
|
}
|
|
|
|
|
|
2021-07-02 10:21:19 +01:00
|
|
|
f()
|
2021-07-01 19:17:44 +01:00
|
|
|
}
|
2021-06-28 20:40:13 +01:00
|
|
|
}
|
2023-11-19 22:48:19 +00:00
|
|
|
|
|
|
|
|
impl Default for BlockingSpawner {
|
|
|
|
|
fn default() -> Self {
|
|
|
|
|
let allow_block_in_place = match tokio::runtime::Handle::current().runtime_flavor() {
|
|
|
|
|
tokio::runtime::RuntimeFlavor::CurrentThread => false,
|
|
|
|
|
tokio::runtime::RuntimeFlavor::MultiThread => true,
|
|
|
|
|
_ => true,
|
|
|
|
|
};
|
|
|
|
|
Self::new(allow_block_in_place)
|
|
|
|
|
}
|
|
|
|
|
}
|