rqbit/crates/librqbit/src/spawn_utils.rs

41 lines
929 B
Rust
Raw Normal View History

2023-11-19 12:50:11 +00:00
use tracing::{debug, error, trace, Instrument};
2023-11-19 12:50:11 +00:00
pub fn spawn(
span: tracing::Span,
fut: impl std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
) {
2023-11-19 12:50:11 +00:00
let fut = async move {
trace!("started");
match fut.await {
Ok(_) => {
2023-11-19 12:50:11 +00:00
debug!("finished");
}
Err(e) => {
2023-11-19 12:50:11 +00:00
error!("{:#}", e)
}
}
2023-11-19 12:50:11 +00:00
}
.instrument(span.or_current());
tokio::spawn(fut);
}
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
}
}