~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
113 lines · 2.9 KB Raw History
//! 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<C, T> {
    tasks: JoinSet<T>,
    contexts: HashMap<tokio::task::Id, C>,
}

impl<C: Send + 'static, T: Send + 'static> Default for WorkSet<C, T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<C: Send + 'static, T: Send + 'static> WorkSet<C, T> {
    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<F>(&mut self, context: C, future: F) -> AbortHandle
    where
        F: Future<Output = T> + 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<T, JoinError>)> {
        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<T> {
    handle: JoinHandle<T>,
}

impl<T: Send + 'static> AbortOnDrop<T> {
    pub fn new(handle: JoinHandle<T>) -> Self {
        Self { handle }
    }

    pub fn spawn<F>(future: F) -> Self
    where
        F: Future<Output = T> + Send + 'static,
    {
        Self::new(tokio::spawn(future))
    }

    pub fn abort(&self) {
        self.handle.abort();
    }
}

impl<T> Drop for AbortOnDrop<T> {
    fn drop(&mut self) {
        self.handle.abort();
    }
}

impl<T> Future for AbortOnDrop<T> {
    type Output = Result<T, JoinError>;

    fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.handle).poll(context)
    }
}