Skip to content

Commit

Permalink
feat: add tokio::NamedTask util
Browse files Browse the repository at this point in the history
  • Loading branch information
OliverNChalk committed Nov 25, 2024
1 parent 0627957 commit 7e70a49
Show file tree
Hide file tree
Showing 4 changed files with 185 additions and 0 deletions.
141 changes: 141 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ disallowed_methods = "warn"

[features]
default = []
tokio = ["dep:tokio"]
tracing = ["dep:const_format", "dep:tracing", "dep:tracing-appender", "dep:tracing-subscriber"]
version = ["dep:const_format"]

[dependencies]
const_format = { version = "0.2.32", optional = true }
tokio = { version = "1.0", features = ["rt"], optional = true }
tracing = { version = "0.1.40", optional = true }
tracing-appender = { version = "0.2.3", optional = true }
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "json"], optional = true }
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
pub mod fs;
#[cfg(feature = "tracing")]
pub mod tokio;
#[cfg(feature = "tracing")]
pub mod tracing;
#[cfg(feature = "version")]
pub mod version;
40 changes: 40 additions & 0 deletions src/tokio.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use std::future::Future;
use std::pin::Pin;

use tokio::task::JoinError;

/// A wrapper around a [tokio::task::JoinHandle] that attaches a name.
///
/// This enables a parent task to await all children simultaneously but still
/// determine what child has exited for logging/diagnosis purposes.
#[derive(Debug)]
pub struct NamedTask<Ret = (), Id = String>
where
Id: Clone + Unpin,
{
task: Pin<Box<tokio::task::JoinHandle<Ret>>>,
id: Id,
}

impl<R, I> NamedTask<R, I>
where
I: Clone + Unpin,
{
pub fn new(task: tokio::task::JoinHandle<R>, id: I) -> Self {
NamedTask { task: Box::pin(task), id }
}
}

impl<R, I> Future for NamedTask<R, I>
where
I: Clone + Unpin,
{
type Output = (I, Result<R, JoinError>);

fn poll(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
self.task.as_mut().poll(cx).map(|v| (self.id.clone(), v))
}
}

0 comments on commit 7e70a49

Please sign in to comment.