tokio-task-supervisor 0.1.1

Tokio TaskTracker with built-in cancellation token management and coordinated shutdown.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
use std::{future::Future, ops::Deref, time::Duration};

use tokio::runtime::Handle;
use tokio::task::{JoinHandle, LocalSet};
use tokio_util::sync::{CancellationToken, DropGuardRef};

pub use tokio_util::task::task_tracker::{
    TaskTracker, TaskTrackerToken, TaskTrackerWaitFuture, TrackedFuture,
};

/// The outcome of a task that races against cancellation.
///
/// This enum is returned by [`spawn_with_cancel`](TaskManager::spawn_with_cancel) variants
/// to indicate whether the task completed normally or was cancelled.
#[derive(Debug, PartialEq, Eq)]
pub enum CancelOutcome<T> {
    /// The task future completed before cancellation was requested.
    Completed(T),
    /// Cancellation won the race; the task future was dropped.
    Cancelled,
}

impl<T> CancelOutcome<T> {
    /// Creates a `CancelOutcome` from an optional result.
    ///
    /// # Arguments
    ///
    /// * `result` - `Some(value)` indicates completion, `None` indicates cancellation.
    #[inline]
    pub fn outcome(result: Option<T>) -> CancelOutcome<T> {
        match result {
            Some(value) => CancelOutcome::Completed(value),
            None => CancelOutcome::Cancelled,
        }
    }
}

/// Manages a collection of asynchronous tasks and coordinates their shutdown.
///
/// `TaskSupervisor` wraps [`TaskTracker`] to keep count of outstanding tasks while also exposing a
/// process-wide [`CancellationToken`] that can be used to request cooperative shutdown.
///
/// # Examples
///
/// ```rust
/// use tokio_task_supervisor::TaskSupervisor;
/// use tokio::time::{sleep, Duration};
///
/// #[tokio::main]
/// async fn main() {
///     let supervisor = TaskSupervisor::new();
///     
///     // Spawn a task that cooperatively handles cancellation
///     let handle = supervisor.spawn_with_token(|token| async move {
///         loop {
///             if token.is_cancelled() {
///                 break;
///             }
///             // Do work...
///             sleep(Duration::from_millis(100)).await;
///         }
///     });
///     
///     // Later, request shutdown
///     supervisor.shutdown().await;
/// }
/// ```
///
/// # Deref Implementation
///
/// `TaskSupervisor` implements [`Deref`] targeting [`TaskTracker`], allowing you to call
/// `TaskTracker` methods directly on a `TaskSupervisor` instance:
///
/// ```rust
/// use tokio_task_supervisor::TaskSupervisor;
///
/// #[tokio::main]
/// async fn main() {
///     let supervisor = TaskSupervisor::new();
///     
///     // These calls work through deref coercion:
///     let handle = supervisor.spawn(async { 42 });
///     let count = supervisor.len();
///     let is_closed = supervisor.is_closed();
///     
///     // Equivalent to:
///     let handle = supervisor.tracker().spawn(async { 42 });
///     let count = supervisor.tracker().len();
///     let is_closed = supervisor.tracker().is_closed();
/// }
/// ```
#[derive(Clone)]
pub struct TaskSupervisor {
    tracker: TaskTracker,
    shutdown: CancellationToken,
}

impl TaskSupervisor {
    // === Construction ===

    /// Creates a new task manager.
    #[must_use]
    pub fn new() -> Self {
        Self {
            tracker: TaskTracker::new(),
            shutdown: CancellationToken::new(),
        }
    }

    // === Accessors ===

    /// Returns a reference to the underlying [`TaskTracker`].
    #[inline]
    pub fn tracker(&self) -> &TaskTracker {
        &self.tracker
    }

    /// Returns a clone of the shared cancellation token.
    #[inline]
    pub fn token(&self) -> CancellationToken {
        self.shutdown.clone()
    }

    /// Returns a guard that cancels the shutdown token when dropped.
    #[must_use]
    #[inline]
    pub fn cancel_on_drop(&self) -> DropGuardRef<'_> {
        self.shutdown.drop_guard_ref()
    }

    // === State Queries ===

    /// Returns `true` if the shutdown token has been cancelled.
    #[inline]
    pub fn is_cancelled(&self) -> bool {
        self.shutdown.is_cancelled()
    }

    /// Returns `true` if the task tracker is closed.
    #[inline]
    pub fn is_closed(&self) -> bool {
        self.tracker.is_closed()
    }

    /// Returns the number of outstanding tasks.
    #[inline]
    pub fn len(&self) -> usize {
        self.tracker.len()
    }

    /// Returns a future that completes when all tasks finish.
    #[inline]
    pub fn wait(&self) -> TaskTrackerWaitFuture<'_> {
        self.tracker.wait()
    }

    // === Control Operations ===

    /// Cancels the shared shutdown token.
    ///
    /// Tasks spawned through the managed API can observe this and exit cooperatively.
    #[inline]
    pub fn cancel(&self) {
        self.shutdown.cancel();
    }

    /// Initiates graceful shutdown by closing the tracker and cancelling all tasks.
    ///
    /// This method will:
    /// 1. Close the task tracker to prevent new tasks from being spawned
    /// 2. Cancel the shutdown token to signal all existing tasks
    /// 3. Wait for all tasks to complete
    pub async fn shutdown(&self) {
        self.tracker.close();
        self.shutdown.cancel();
        self.tracker.wait().await;
    }

    /// Initiates graceful shutdown with a timeout.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Maximum time to wait for shutdown to complete
    ///
    /// # Returns
    ///
    /// * `Ok(())` if shutdown completed within the timeout
    /// * `Err(Elapsed)` if the timeout was exceeded
    #[inline]
    pub async fn shutdown_with_timeout(
        &self,
        timeout: Duration,
    ) -> Result<(), tokio::time::error::Elapsed> {
        tokio::time::timeout(timeout, self.shutdown()).await
    }

    // === Spawn Methods with Cancellation Race ===

    /// Spawns a task that races against the shared cancellation token.
    ///
    /// The returned future resolves with [`CancelOutcome`], indicating whether the task finished
    /// normally or was cancelled. When cancellation wins the race, the task future is dropped, so it
    /// should not rely on `Drop` for cleanup.
    ///
    /// # Arguments
    ///
    /// * `task` - A closure that returns the future to execute
    ///
    /// # Returns
    ///
    /// A `JoinHandle` that resolves to the task's outcome
    #[must_use]
    pub fn spawn_with_cancel<F, Fut>(&self, task: F) -> JoinHandle<CancelOutcome<Fut::Output>>
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future + Send + 'static,
        Fut::Output: Send + 'static,
    {
        let token = self.token();
        self.tracker
            .spawn(async move { CancelOutcome::outcome(token.run_until_cancelled(task()).await) })
    }

    /// Spawns a task with cancellation handling on a specific runtime handle.
    ///
    /// # Arguments
    ///
    /// * `task` - A closure that returns the future to execute
    /// * `handle` - The runtime handle to spawn the task on
    ///
    /// # Returns
    ///
    /// A `JoinHandle` that resolves to the task's outcome
    #[must_use]
    pub fn spawn_on_with_cancel<F, Fut>(
        &self,
        task: F,
        handle: &Handle,
    ) -> JoinHandle<CancelOutcome<Fut::Output>>
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future + Send + 'static,
        Fut::Output: Send + 'static,
    {
        let token = self.token();
        self.tracker.spawn_on(
            async move { CancelOutcome::outcome(token.run_until_cancelled(task()).await) },
            handle,
        )
    }

    /// Spawns a !Send task that races against the shared cancellation token.
    ///
    /// # Arguments
    ///
    /// * `task` - A closure that returns the future to execute
    ///
    /// # Returns
    ///
    /// A `JoinHandle` that resolves to the task's outcome
    #[must_use]
    pub fn spawn_local_with_cancel<F, Fut>(&self, task: F) -> JoinHandle<CancelOutcome<Fut::Output>>
    where
        F: FnOnce() -> Fut + 'static,
        Fut: Future + 'static,
        Fut::Output: 'static,
    {
        let token = self.token();
        self.tracker.spawn_local(async move {
            CancelOutcome::outcome(token.run_until_cancelled(task()).await)
        })
    }

    /// Spawns a !Send task on a [`LocalSet`] with cancellation handling.
    ///
    /// # Arguments
    ///
    /// * `task` - A closure that returns the future to execute
    /// * `local_set` - The local set to spawn the task on
    ///
    /// # Returns
    ///
    /// A `JoinHandle` that resolves to the task's outcome
    #[must_use]
    pub fn spawn_local_on_with_cancel<F, Fut>(
        &self,
        task: F,
        local_set: &LocalSet,
    ) -> JoinHandle<CancelOutcome<Fut::Output>>
    where
        F: FnOnce() -> Fut + 'static,
        Fut: Future + 'static,
        Fut::Output: 'static,
    {
        let token = self.token();
        self.tracker.spawn_local_on(
            async move { CancelOutcome::outcome(token.run_until_cancelled(task()).await) },
            local_set,
        )
    }

    // === Spawn Methods with Token ===

    /// Spawns a task that receives the shared cancellation token.
    ///
    /// # Arguments
    ///
    /// * `task` - A closure that takes a cancellation token and returns a future
    ///
    /// # Returns
    ///
    /// A `JoinHandle` that resolves to the task's output
    #[must_use]
    pub fn spawn_with_token<F, Fut>(&self, task: F) -> JoinHandle<Fut::Output>
    where
        F: FnOnce(CancellationToken) -> Fut + Send + 'static,
        Fut: Future + Send + 'static,
        Fut::Output: Send + 'static,
    {
        let token = self.shutdown.child_token();
        self.tracker.spawn(async move { task(token).await })
    }

    /// Spawns a task with the shared cancellation token on a specific runtime handle.
    ///
    /// # Arguments
    ///
    /// * `task` - A closure that takes a cancellation token and returns a future
    /// * `handle` - The runtime handle to spawn the task on
    ///
    /// # Returns
    ///
    /// A `JoinHandle` that resolves to the task's output
    #[must_use]
    pub fn spawn_on_with_token<F, Fut>(&self, task: F, handle: &Handle) -> JoinHandle<Fut::Output>
    where
        F: FnOnce(CancellationToken) -> Fut + Send + 'static,
        Fut: Future + Send + 'static,
        Fut::Output: Send + 'static,
    {
        let token = self.shutdown.child_token();
        self.tracker
            .spawn_on(async move { task(token).await }, handle)
    }

    /// Spawns a local task that receives the shared cancellation token.
    ///
    /// # Arguments
    ///
    /// * `task` - A closure that takes a cancellation token and returns a future
    ///
    /// # Returns
    ///
    /// A `JoinHandle` that resolves to the task's output
    #[must_use]
    pub fn spawn_local_with_token<F, Fut>(&self, task: F) -> JoinHandle<Fut::Output>
    where
        F: FnOnce(CancellationToken) -> Fut + 'static,
        Fut: Future + 'static,
        Fut::Output: 'static,
    {
        let token = self.shutdown.child_token();
        self.tracker.spawn_local(async move { task(token).await })
    }

    /// Spawns a local task with a cancellation token on a specific local set.
    ///
    /// # Arguments
    ///
    /// * `task` - A closure that takes a cancellation token and returns a future
    /// * `local_set` - The local set to spawn the task on
    ///
    /// # Returns
    ///
    /// A `JoinHandle` that resolves to the task's output
    #[must_use]
    pub fn spawn_local_on_with_token<F, Fut>(
        &self,
        task: F,
        local_set: &LocalSet,
    ) -> JoinHandle<Fut::Output>
    where
        F: FnOnce(CancellationToken) -> Fut + 'static,
        Fut: Future + 'static,
        Fut::Output: 'static,
    {
        let token = self.shutdown.child_token();
        self.tracker
            .spawn_local_on(async move { task(token).await }, local_set)
    }

    /// Spawns a blocking task that receives a cancellation context.
    ///
    /// # Arguments
    ///
    /// * `task` - A closure that takes a cancellation token and returns a value
    ///
    /// # Returns
    ///
    /// A `JoinHandle` that resolves to the task's output
    #[cfg(not(target_family = "wasm"))]
    #[must_use]
    pub fn spawn_blocking_with_token<F, T>(&self, task: F) -> JoinHandle<T>
    where
        F: FnOnce(CancellationToken) -> T + Send + 'static,
        T: Send + 'static,
    {
        let token = self.shutdown.child_token();
        self.tracker.spawn_blocking(move || task(token))
    }

    /// Spawns a blocking task with context on a specific runtime handle.
    ///
    /// # Arguments
    ///
    /// * `task` - A closure that takes a cancellation token and returns a value
    /// * `handle` - The runtime handle to spawn the task on
    ///
    /// # Returns
    ///
    /// A `JoinHandle` that resolves to the task's output
    #[cfg(not(target_family = "wasm"))]
    #[must_use]
    pub fn spawn_blocking_on_with_token<F, T>(&self, task: F, handle: &Handle) -> JoinHandle<T>
    where
        F: FnOnce(CancellationToken) -> T + Send + 'static,
        T: Send + 'static,
    {
        let token = self.shutdown.child_token();
        self.tracker.spawn_blocking_on(move || task(token), handle)
    }
}

impl Default for TaskSupervisor {
    fn default() -> Self {
        Self::new()
    }
}

impl Deref for TaskSupervisor {
    type Target = TaskTracker;

    fn deref(&self) -> &Self::Target {
        &self.tracker
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::Arc;
    use tokio::time::{sleep, Duration};

    #[tokio::test]
    async fn test_spawn_with_token_provides_token() {
        let supervisor = TaskSupervisor::new();

        let handle = supervisor.spawn_with_token(|token| async move { token.is_cancelled() });

        let result = handle.await.unwrap();
        assert!(!result);
    }

    #[tokio::test]
    #[cfg(feature = "rt")]
    async fn test_spawn_on_with_token_provides_token() {
        let supervisor = TaskSupervisor::new();
        let handle = tokio::runtime::Handle::current();

        let result = supervisor
            .spawn_on_with_token(|token| async move { token.is_cancelled() }, &handle)
            .await
            .unwrap();

        assert!(!result);
    }

    #[tokio::test]
    #[cfg(all(feature = "rt", not(target_family = "wasm")))]
    async fn test_spawn_blocking_with_token_provides_token() {
        let supervisor = TaskSupervisor::new();

        let handle = supervisor.spawn_blocking_with_token(move |token| token.is_cancelled());

        let result = handle.await.unwrap();
        assert!(!result);
    }

    #[tokio::test]
    async fn test_cancel_sets_cancelled_state() {
        let supervisor = TaskSupervisor::new();
        assert!(!supervisor.is_cancelled());

        supervisor.cancel();
        assert!(supervisor.is_cancelled());
    }

    #[tokio::test]
    async fn test_cancel_propagates_to_all_tasks() {
        let supervisor = TaskSupervisor::new();
        let count = Arc::new(AtomicUsize::new(0));

        for _ in 0..3 {
            let count_clone = count.clone();
            let _ = supervisor.spawn_with_token(|token| async move {
                token.cancelled().await;
                count_clone.fetch_add(1, Ordering::SeqCst);
            });
        }

        sleep(Duration::from_millis(50)).await;
        supervisor.cancel();
        sleep(Duration::from_millis(100)).await;

        assert_eq!(count.load(Ordering::SeqCst), 3);
    }

    #[tokio::test]
    async fn test_shutdown_cancels_and_waits() {
        let supervisor = TaskSupervisor::new();
        let task_finished = Arc::new(AtomicBool::new(false));
        let task_finished_clone = task_finished.clone();

        let _ = supervisor.spawn_with_token(|_token| async move {
            sleep(Duration::from_millis(100)).await;
            task_finished_clone.store(true, Ordering::SeqCst);
        });

        assert!(!supervisor.is_cancelled());
        assert!(!supervisor.is_closed());

        supervisor.shutdown().await;

        assert!(supervisor.is_cancelled());
        assert!(supervisor.is_closed());
        assert!(task_finished.load(Ordering::SeqCst));
        assert_eq!(supervisor.len(), 0);
    }

    #[tokio::test]
    async fn test_shutdown_with_timeout_completes_in_time() {
        let supervisor = TaskSupervisor::new();

        let _ = supervisor.spawn_with_token(|_token| async move {
            sleep(Duration::from_millis(50)).await;
        });

        let result = supervisor
            .shutdown_with_timeout(Duration::from_secs(1))
            .await;
        assert!(result.is_ok());
        assert!(supervisor.is_cancelled());
        assert!(supervisor.is_closed());
    }

    #[tokio::test]
    async fn test_shutdown_with_timeout_times_out() {
        let supervisor = TaskSupervisor::new();

        let _ = supervisor.tracker().spawn(async {
            sleep(Duration::from_secs(10)).await;
        });

        let result = supervisor
            .shutdown_with_timeout(Duration::from_millis(50))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_cooperative_cancellation_in_loop() {
        let supervisor = TaskSupervisor::new();
        let iterations = Arc::new(AtomicUsize::new(0));
        let iterations_clone = iterations.clone();

        let _ = supervisor.spawn_with_token(|token| async move {
            loop {
                if token.is_cancelled() {
                    break;
                }
                iterations_clone.fetch_add(1, Ordering::SeqCst);
                sleep(Duration::from_millis(10)).await;
            }
        });

        sleep(Duration::from_millis(55)).await;
        supervisor.cancel();
        sleep(Duration::from_millis(50)).await;

        let count = iterations.load(Ordering::SeqCst);
        assert!(count >= 3 && count < 20);
    }

    #[tokio::test]
    async fn test_spawn_with_cancel_completes() {
        let supervisor = TaskSupervisor::new();

        let handle = supervisor.spawn_with_cancel(|| async move {
            sleep(Duration::from_millis(30)).await;
            42
        });

        match handle.await.unwrap() {
            CancelOutcome::Completed(value) => assert_eq!(value, 42),
            CancelOutcome::Cancelled => panic!("task should have completed"),
        }
    }

    #[tokio::test]
    async fn test_spawn_with_cancel_reports_cancellation() {
        let supervisor = TaskSupervisor::new();

        let handle = supervisor.spawn_with_cancel(|| async move {
            loop {
                sleep(Duration::from_millis(10)).await;
            }
        });

        sleep(Duration::from_millis(35)).await;
        supervisor.cancel();

        match handle.await.unwrap() {
            CancelOutcome::Completed(_) => panic!("task should have been cancelled"),
            CancelOutcome::Cancelled => {}
        }
    }

    #[tokio::test]
    async fn test_deref_allows_direct_tracker_access() {
        let supervisor = TaskSupervisor::new();

        // Test that we can call TaskTracker methods directly on TaskSupervisor
        let handle = supervisor.spawn(async {
            sleep(Duration::from_millis(50)).await;
            42
        });

        // Verify we can access tracker methods through deref
        assert_eq!(supervisor.len(), 1);
        assert!(!supervisor.is_closed());

        let result = handle.await.unwrap();
        assert_eq!(result, 42);
    }
}