wordval-utils 1.0.8

Wordval utilities: string manipulation, date handling, masking, ID generation, validation, crypto, web helpers, collection tools, retry utilities
Documentation
//! 异步任务句柄托管:自动清理已完成任务、统一 abort 收口
//!
//! 插件与后台服务常散落 `tokio::spawn` 的句柄管理:裸 `Vec<JoinHandle>`
//! 会随时间无限增长(已完成任务不被移除),停机时也没有统一的 abort 入口。
//! [`TaskHandles`] 提供:
//!
//! - [`push`](TaskHandles::push):入队时顺带清理已完成句柄,内存有界;
//! - [`abort_all`](TaskHandles::abort_all):停机时一次性中止全部任务;
//! - [`all_finished`](TaskHandles::all_finished):观测全部任务是否自然结束。
//!
//! ```rust
//! use wordval_utils::task_handle::TaskHandles;
//!
//! # async fn demo() {
//! let handles = TaskHandles::default();
//! handles.push(tokio::spawn(async { /* 后台工作 */ }));
//! handles.abort_all();
//! # }
//! ```

use std::sync::Mutex;
use tokio::task::JoinHandle;

/// 异步任务句柄集合(不施加 spawn/join 策略,只管存取与清理)
#[derive(Debug, Default)]
pub struct TaskHandles {
    handles: Mutex<Vec<JoinHandle<()>>>,
}

impl TaskHandles {
    /// 存入句柄;顺带移除已完成的句柄(内存有界)
    pub fn push(&self, handle: JoinHandle<()>) {
        let mut handles = self.handles.lock().unwrap();
        handles.retain(|h| !h.is_finished());
        handles.push(handle);
    }

    /// 取出并 abort 全部句柄
    pub fn abort_all(&self) {
        for handle in self.take_all() {
            handle.abort();
        }
    }

    /// 原地 abort 全部句柄但不移除记录——调用方稍后可用
    /// [`Self::all_finished`] 等待其真正终止
    pub fn abort_all_retained(&self) {
        for handle in self.handles.lock().unwrap().iter() {
            handle.abort();
        }
    }

    /// 取出全部句柄(此后集合为空)
    pub fn take_all(&self) -> Vec<JoinHandle<()>> {
        std::mem::take(&mut *self.handles.lock().unwrap())
    }

    /// 全部已记录任务是否都已结束
    pub fn all_finished(&self) -> bool {
        self.handles
            .lock()
            .unwrap()
            .iter()
            .all(JoinHandle::is_finished)
    }

    /// 当前记录的任务数(含未清理的已完成任务)
    pub fn len(&self) -> usize {
        self.handles.lock().unwrap().len()
    }

    /// 是否没有记录任何任务
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::time::Duration;

    #[tokio::test]
    async fn push_cleans_finished_handles() {
        let handles = TaskHandles::default();
        handles.push(tokio::spawn(async {})); // 立即完成
        // 让出调度,确保任务结束
        tokio::time::sleep(Duration::from_millis(10)).await;
        handles.push(tokio::spawn(async {})); // push 时清理掉前一个
        tokio::time::sleep(Duration::from_millis(10)).await;
        assert_eq!(handles.len(), 1, "已完成句柄应被 push 顺带清理");
    }

    #[tokio::test]
    async fn abort_all_stops_tasks() {
        let handles = TaskHandles::default();
        let guard = Arc::new(tokio::sync::Notify::new());
        let g = guard.clone();
        handles.push(tokio::spawn(async move {
            // 长任务:若不被 abort 则 notify
            tokio::time::sleep(Duration::from_secs(60)).await;
            g.notify_one();
        }));
        handles.abort_all();
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(handles.all_finished());
    }

    #[tokio::test]
    async fn take_all_empties() {
        let handles = TaskHandles::default();
        handles.push(tokio::spawn(async {}));
        assert_eq!(handles.take_all().len(), 1);
        assert!(handles.is_empty());
    }
}