//! Context-tagged task set and abort-on-drop guard. use std::collections::HashMap; use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; use tokio::task::{AbortHandle, JoinError, JoinHandle, JoinSet}; /// A `JoinSet` whose tasks carry a caller-supplied context label. /// /// Dropping the set aborts every remaining task. pub struct WorkSet { tasks: JoinSet, contexts: HashMap, } impl Default for WorkSet { fn default() -> Self { Self::new() } } impl WorkSet { pub fn new() -> Self { Self { tasks: JoinSet::new(), contexts: HashMap::new(), } } /// Spawn a task tagged with `context`; the returned handle aborts it. pub fn spawn(&mut self, context: C, future: F) -> AbortHandle where F: Future + Send + 'static, { let handle = self.tasks.spawn(future); self.contexts.insert(handle.id(), context); handle } /// Await the next finished task together with its context. /// /// Cancel safe: dropping this future does not lose tasks. pub async fn next(&mut self) -> Option<(C, Result)> { let joined = self.tasks.join_next_with_id().await?; match joined { Ok((id, value)) => Some(( self.contexts.remove(&id).expect("workset context"), Ok(value), )), Err(error) => { let id = error.id(); Some(( self.contexts.remove(&id).expect("workset context"), Err(error), )) } } } pub fn len(&self) -> usize { self.tasks.len() } pub fn is_empty(&self) -> bool { self.tasks.is_empty() } pub fn abort_all(&mut self) { self.tasks.abort_all(); } } // No custom `Drop`: `JoinSet` already aborts every remaining task when the set // is dropped, and a custom Drop impl would force `C`/`T: 'static` bounds on the // struct itself. /// A task handle that aborts its task when dropped. pub struct AbortOnDrop { handle: JoinHandle, } impl AbortOnDrop { pub fn new(handle: JoinHandle) -> Self { Self { handle } } pub fn spawn(future: F) -> Self where F: Future + Send + 'static, { Self::new(tokio::spawn(future)) } pub fn abort(&self) { self.handle.abort(); } } impl Drop for AbortOnDrop { fn drop(&mut self) { self.handle.abort(); } } impl Future for AbortOnDrop { type Output = Result; fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll { Pin::new(&mut self.handle).poll(context) } }