taskvisor 0.6.0

Task supervisor for Tokio: restarts background tasks on failure with exponential backoff and jitter, graceful shutdown, and lifecycle events
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
//! Per-task execution settings and default resolution.

use std::num::NonZeroU32;
use std::time::Duration;

use crate::{
    core::{ConfigError, TaskDefaults},
    policies::BackoffPolicy,
    policies::RestartPolicy,
    tasks::task::TaskRef,
};

/// Converts `Some(Duration::ZERO)` to `None`.
#[inline]
fn normalize_timeout(timeout: Option<Duration>) -> Option<Duration> {
    timeout.filter(|d| !d.is_zero())
}

/// A task and the rules used to run it.
///
/// A spec can set a value or inherit it from [`TaskDefaults`].
/// The supervisor resolves all inherited values when it accepts the task.
/// A `with_*` method always sets an explicit value and wins over the default.
///
/// ```text
/// TaskSpec                    TaskDefaults
///   restart = OnFailure        restart = OnFailure
///   timeout = inherit    +      timeout = 30s
///             |
///             v
/// resolved at admission: restart = OnFailure, timeout = 30s
/// ```
///
/// | Constructor                            | Restart setting | Other settings                  |
/// |----------------------------------------|-----------------|---------------------------------|
/// | [`once`](Self::once)                   | Never           | Inherited                       |
/// | [`restartable`](Self::restartable)     | On failure      | Inherited                       |
/// | [`periodic`](Self::periodic)           | Always          | Inherited                       |
/// | [`from_defaults`](Self::from_defaults) | Inherited       | Inherited                       |
/// | [`new`](Self::new)                     | Explicit        | Explicit; retries are unlimited |
///
/// ## Example
///
/// ```rust
/// use std::num::NonZeroU32;
/// use std::time::Duration;
/// use taskvisor::{TaskFn, TaskRef, TaskSpec};
///
/// let task: TaskRef = TaskFn::arc("worker", |_ctx| async { Ok(()) });
///
/// let spec = TaskSpec::restartable(task)
///     .with_timeout(Duration::from_secs(30))
///     .with_max_retries(NonZeroU32::new(5).unwrap());
/// ```
///
/// `max_retries = 5` allows the first failed attempt plus five retries.
/// A successful attempt resets this count; an `Always` task may still have more than six attempts over its full lifetime.
///
/// ## See Also
///
/// - See [`Task`](crate::Task) for the execution contract and cancellation semantics.
/// - For the closure-based implementation see [`TaskFn`](crate::TaskFn).
#[derive(Clone)]
#[must_use]
pub struct TaskSpec {
    restart: Override<RestartPolicy>,
    backoff: Override<BackoffPolicy>,
    timeout: Override<Option<Duration>>,
    max_retries: Override<Option<NonZeroU32>>,

    task: TaskRef,
}

#[derive(Clone, Copy, Debug)]
enum Override<T> {
    Inherit,
    Set(T),
}

impl<T: Copy> Override<T> {
    #[inline]
    fn value(self) -> Option<T> {
        match self {
            Self::Inherit => None,
            Self::Set(value) => Some(value),
        }
    }

    #[inline]
    fn resolve(self, default: T) -> T {
        match self {
            Self::Inherit => default,
            Self::Set(value) => value,
        }
    }
}

/// A task specification after default resolution.
#[derive(Clone)]
#[must_use]
pub(crate) struct ResolvedTaskSpec {
    restart: RestartPolicy,
    backoff: BackoffPolicy,
    timeout: Option<Duration>,
    max_retries: Option<NonZeroU32>,
    task: TaskRef,
}

impl std::fmt::Debug for TaskSpec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TaskSpec")
            .field("restart", &self.restart)
            .field("backoff", &self.backoff)
            .field("timeout", &self.timeout)
            .field("task", &self.task.name())
            .field("max_retries", &self.max_retries)
            .finish()
    }
}

impl std::fmt::Debug for ResolvedTaskSpec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ResolvedTaskSpec")
            .field("restart", &self.restart)
            .field("backoff", &self.backoff)
            .field("timeout", &self.timeout)
            .field("task", &self.task.name())
            .field("max_retries", &self.max_retries)
            .finish()
    }
}

impl TaskSpec {
    /// Creates a spec that inherits every execution setting.
    ///
    /// The supervisor resolves restart, backoff, timeout, and retry limit from its [`TaskDefaults`] when it accepts the task.
    /// A later `with_*` call sets that one field explicitly.
    pub fn from_defaults(task: TaskRef) -> Self {
        Self {
            restart: Override::Inherit,
            backoff: Override::Inherit,
            timeout: Override::Inherit,
            max_retries: Override::Inherit,
            task,
        }
    }

    /// Creates a spec with explicit main settings.
    ///
    /// Prefer the named constructors for common cases:
    /// [`once`](Self::once), [`restartable`](Self::restartable), [`periodic`](Self::periodic).
    ///
    /// `timeout` accepts a [`Duration`] or `Option<Duration>`.
    /// `None` and zero disable the attempt timeout.
    /// The retry limit is set to unlimited; change it with [`with_max_retries`](Self::with_max_retries).
    pub fn new(
        task: TaskRef,
        restart: RestartPolicy,
        backoff: BackoffPolicy,
        timeout: impl Into<Option<Duration>>,
    ) -> Self {
        Self {
            restart: Override::Set(restart),
            backoff: Override::Set(backoff),
            timeout: Override::Set(normalize_timeout(timeout.into())),
            max_retries: Override::Set(None),
            task,
        }
    }

    /// Creates a one-shot task that never restarts.
    ///
    /// Backoff, timeout, and retry limit are inherited from [`TaskDefaults`].
    /// Override them with the matching `with_*` methods.
    pub fn once(task: TaskRef) -> Self {
        Self {
            restart: Override::Set(RestartPolicy::Never),
            backoff: Override::Inherit,
            timeout: Override::Inherit,
            max_retries: Override::Inherit,
            task,
        }
    }

    /// Creates a task that restarts after retryable failures.
    ///
    /// Success, fatal failure, and cancellation stop the task.
    /// Backoff, timeout, and retry limit are inherited from [`TaskDefaults`].
    pub fn restartable(task: TaskRef) -> Self {
        Self {
            restart: Override::Set(RestartPolicy::OnFailure),
            backoff: Override::Inherit,
            timeout: Override::Inherit,
            max_retries: Override::Inherit,
            task,
        }
    }

    /// Creates a task that runs again after each success.
    ///
    /// After success, the supervisor waits `every` before the next attempt.
    /// A zero value means no configured interval; a small internal guard still prevents an instant task from creating a hot loop.
    ///
    /// Retryable failures use the backoff policy, not `every`.
    /// A retry limit can stop the task after repeated failures.
    /// Fatal failure and cancellation always stop it.
    ///
    /// The interval starts after an attempt completes.
    /// This is not a wall-clock schedule such as "daily at 03:00".
    ///
    /// ```rust
    /// use std::time::Duration;
    /// use taskvisor::{TaskFn, TaskRef, TaskSpec};
    ///
    /// let tick: TaskRef = TaskFn::arc("tick", |_ctx| async move {
    ///     println!("tick");
    ///     Ok(())
    /// });
    ///
    /// // Starts the next successful cycle 30 seconds after this one ends.
    /// let spec = TaskSpec::periodic(tick, Duration::from_secs(30));
    /// ```
    #[doc(alias = "interval")]
    #[doc(alias = "fixed delay")]
    pub fn periodic(task: TaskRef, every: Duration) -> Self {
        Self {
            restart: Override::Set(RestartPolicy::Always {
                interval: Some(every).filter(|d| !d.is_zero()),
            }),
            backoff: Override::Inherit,
            timeout: Override::Inherit,
            max_retries: Override::Inherit,
            task,
        }
    }

    /// Returns the task handle.
    #[must_use]
    pub fn task(&self) -> &TaskRef {
        &self.task
    }

    /// Returns the task name.
    #[must_use]
    pub fn name(&self) -> &str {
        self.task.name()
    }

    /// Returns the explicit restart policy, or `None` if it is inherited.
    #[must_use]
    pub fn restart_override(&self) -> Option<RestartPolicy> {
        self.restart.value()
    }

    /// Returns the explicit backoff policy, or `None` if it is inherited.
    #[must_use]
    pub fn backoff_override(&self) -> Option<BackoffPolicy> {
        self.backoff.value()
    }

    /// Returns how this spec overrides the attempt timeout.
    ///
    /// - `None` means inherit the default.
    /// - `Some(None)` means explicitly disable the timeout.
    /// - `Some(Some(duration))` means use that timeout.
    #[must_use]
    pub fn timeout_override(&self) -> Option<Option<Duration>> {
        self.timeout.value()
    }

    /// Returns how this spec overrides the retry limit.
    ///
    /// - `None` means inherit the default.
    /// - `Some(None)` means explicitly allow unlimited retries.
    /// - `Some(Some(limit))` means use that retry limit.
    #[must_use]
    pub fn max_retries_override(&self) -> Option<Option<NonZeroU32>> {
        self.max_retries.value()
    }

    /// Sets the timeout for each attempt.
    ///
    /// Pass a `Duration` to enable it.
    /// Pass `None` or zero to disable it, including a timeout inherited from [`TaskDefaults`].
    #[doc(alias = "watchdog")]
    #[doc(alias = "attempt deadline")]
    pub fn with_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
        self.timeout = Override::Set(normalize_timeout(timeout.into()));
        self
    }

    /// Sets the delay policy for retryable failures.
    ///
    /// This value overrides the supervisor default.
    pub fn with_backoff(mut self, backoff: BackoffPolicy) -> Self {
        self.backoff = Override::Set(backoff);
        self
    }

    /// Sets when the task may run another attempt.
    ///
    /// This value overrides the supervisor default.
    pub fn with_restart(mut self, restart: RestartPolicy) -> Self {
        self.restart = Override::Set(restart);
        self
    }

    /// Sets the number of retries after the first failed attempt in a failure streak.
    ///
    /// Pass a [`NonZeroU32`] to set a limit.
    /// Pass `None` for unlimited retries, including when [`TaskDefaults`] has a limit.
    /// A success resets the count.
    #[doc(alias = "retry limit")]
    #[doc(alias = "retry budget")]
    pub fn with_max_retries(mut self, max_retries: impl Into<Option<NonZeroU32>>) -> Self {
        self.max_retries = Override::Set(max_retries.into());
        self
    }

    /// Sets a retry limit from a raw integer.
    ///
    /// # Errors
    /// Returns [`ConfigError::Zero`] when `max_retries` is zero.
    /// Use [`with_max_retries`](Self::with_max_retries) with `None` for unlimited retries.
    pub fn try_with_max_retries(self, max_retries: u32) -> Result<Self, ConfigError> {
        let max_retries = NonZeroU32::new(max_retries).ok_or(ConfigError::Zero {
            field: "max_retries",
        })?;
        Ok(self.with_max_retries(max_retries))
    }

    /// Applies inherited defaults at registry admission.
    pub(crate) fn resolve(self, defaults: &TaskDefaults) -> ResolvedTaskSpec {
        ResolvedTaskSpec {
            restart: self.restart.resolve(defaults.restart()),
            backoff: self.backoff.resolve(defaults.backoff()),
            timeout: self.timeout.resolve(defaults.timeout()),
            max_retries: self.max_retries.resolve(defaults.max_retries()),
            task: self.task,
        }
    }
}

impl ResolvedTaskSpec {
    /// Returns the task handle.
    pub(crate) fn task(&self) -> &TaskRef {
        &self.task
    }

    /// Returns the task name.
    #[cfg(test)]
    pub(crate) fn name(&self) -> &str {
        self.task.name()
    }

    /// Returns the resolved restart policy.
    pub(crate) fn restart(&self) -> RestartPolicy {
        self.restart
    }

    /// Returns the resolved backoff policy.
    pub(crate) fn backoff(&self) -> BackoffPolicy {
        self.backoff
    }

    /// Returns the resolved attempt timeout.
    pub(crate) fn timeout(&self) -> Option<Duration> {
        self.timeout
    }

    /// Returns the resolved failure-retry limit.
    pub(crate) fn max_retries(&self) -> Option<NonZeroU32> {
        self.max_retries
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{JitterPolicy, TaskContext, TaskFn};

    fn task(name: &str) -> TaskRef {
        TaskFn::arc(name, |_ctx: TaskContext| async { Ok(()) })
    }

    fn assert_inherits_non_restart_settings(spec: &TaskSpec) {
        assert!(spec.backoff_override().is_none());
        assert!(spec.timeout_override().is_none());
        assert!(spec.max_retries_override().is_none());
    }

    fn assert_explicit_timeout(spec: TaskSpec, expected: Option<Duration>, case: &str) {
        assert_eq!(spec.timeout_override(), Some(expected), "{case}");
    }

    #[test]
    fn named_constructors_set_restart_and_inherit_other_settings() {
        let inherited = TaskSpec::from_defaults(task("inherited"));
        assert!(inherited.restart_override().is_none());
        assert_inherits_non_restart_settings(&inherited);

        let once = TaskSpec::once(task("once"));
        assert!(matches!(
            once.restart_override(),
            Some(RestartPolicy::Never)
        ));
        assert_inherits_non_restart_settings(&once);

        let restartable = TaskSpec::restartable(task("restartable"));
        assert!(matches!(
            restartable.restart_override(),
            Some(RestartPolicy::OnFailure)
        ));
        assert_inherits_non_restart_settings(&restartable);

        let every = Duration::from_secs(30);
        let spec = TaskSpec::periodic(task("tick"), every);
        assert!(
            matches!(spec.restart_override(), Some(RestartPolicy::Always { interval: Some(d) }) if d == every),
            "periodic must set RestartPolicy::Always with the given interval, got {:?}",
            spec.restart_override()
        );
        assert_inherits_non_restart_settings(&spec);

        let immediate = TaskSpec::periodic(task("immediate"), Duration::ZERO);
        assert!(
            matches!(
                immediate.restart_override(),
                Some(RestartPolicy::Always { interval: None })
            ),
            "a zero interval must normalize to None (immediate restart), got {:?}",
            immediate.restart_override()
        );
    }

    #[test]
    fn new_marks_every_setting_as_explicit() {
        let backoff = BackoffPolicy::constant(Duration::from_secs(2));
        let timeout = Duration::from_secs(7);
        let spec = TaskSpec::new(task("explicit"), RestartPolicy::Never, backoff, timeout);

        assert!(matches!(
            spec.restart_override(),
            Some(RestartPolicy::Never)
        ));
        assert_eq!(
            spec.backoff_override().map(|policy| policy.first()),
            Some(Duration::from_secs(2))
        );
        assert_eq!(spec.timeout_override(), Some(Some(timeout)));
        assert_eq!(spec.max_retries_override(), Some(None));
    }

    #[test]
    fn explicit_none_disables_inherited_optional_settings() {
        let retries = NonZeroU32::new(4).unwrap();
        let defaults = TaskDefaults::default()
            .with_timeout(Duration::from_secs(9))
            .with_max_retries(retries);
        let spec = TaskSpec::restartable(task("disabled"))
            .with_timeout(None)
            .with_max_retries(None);

        assert_eq!(spec.timeout_override(), Some(None));
        assert_eq!(spec.max_retries_override(), Some(None));

        let resolved = spec.resolve(&defaults);
        assert_eq!(resolved.timeout(), None);
        assert_eq!(resolved.max_retries(), None);
    }

    #[test]
    fn resolve_applies_defaults_only_to_inherited_settings() {
        let retries = NonZeroU32::new(6).unwrap();
        let defaults = TaskDefaults::default()
            .with_restart(RestartPolicy::Never)
            .with_backoff(BackoffPolicy::constant(Duration::from_secs(3)))
            .with_timeout(Duration::from_secs(12))
            .with_max_retries(retries);
        let spec = TaskSpec::restartable(task("worker"));

        let resolved = spec.resolve(&defaults);

        assert_eq!(resolved.name(), "worker");
        assert_eq!(resolved.task().name(), "worker");
        assert!(matches!(resolved.restart(), RestartPolicy::OnFailure));
        assert_eq!(resolved.backoff().first(), Duration::from_secs(3));
        assert_eq!(resolved.backoff().jitter(), JitterPolicy::None);
        assert_eq!(resolved.timeout(), Some(Duration::from_secs(12)));
        assert_eq!(resolved.max_retries(), Some(retries));
    }

    #[test]
    fn new_does_not_inherit_task_defaults() {
        let defaults = TaskDefaults::default()
            .with_restart(RestartPolicy::OnFailure)
            .with_backoff(BackoffPolicy::constant(Duration::from_secs(8)))
            .with_timeout(Duration::from_secs(9))
            .with_max_retries(NonZeroU32::new(3).unwrap());
        let spec = TaskSpec::new(
            task("explicit"),
            RestartPolicy::Never,
            BackoffPolicy::constant(Duration::from_secs(1)),
            None,
        );

        let resolved = spec.resolve(&defaults);

        assert!(matches!(resolved.restart(), RestartPolicy::Never));
        assert_eq!(resolved.backoff().first(), Duration::from_secs(1));
        assert_eq!(resolved.timeout(), None);
        assert_eq!(resolved.max_retries(), None);
    }

    #[test]
    fn with_timeout_accepts_duration_or_option_and_normalizes_zero() {
        assert_explicit_timeout(
            TaskSpec::once(task("zero-duration")).with_timeout(Duration::ZERO),
            None,
            "with_timeout(ZERO) must normalize to None",
        );
        assert_explicit_timeout(
            TaskSpec::once(task("zero-option")).with_timeout(Some(Duration::ZERO)),
            None,
            "with_timeout(Some(ZERO)) must normalize to None",
        );
        assert_explicit_timeout(
            TaskSpec::new(
                task("z"),
                RestartPolicy::Never,
                BackoffPolicy::default(),
                Some(Duration::ZERO),
            ),
            None,
            "new(.., Some(ZERO)) must normalize to None",
        );

        let duration = Duration::from_secs(1);
        assert_explicit_timeout(
            TaskSpec::once(task("positive-duration")).with_timeout(duration),
            Some(duration),
            "a positive Duration must be preserved",
        );
        assert_explicit_timeout(
            TaskSpec::once(task("positive-option")).with_timeout(Some(duration)),
            Some(duration),
            "a positive Some(Duration) must be preserved",
        );
        assert_explicit_timeout(
            TaskSpec::once(task("none-inference")).with_timeout(None),
            None,
            "None must infer Option<Duration> and explicitly disable the timeout",
        );
    }

    #[test]
    fn raw_retry_limit_is_validated_like_task_defaults() {
        let spec = TaskSpec::once(task("limited"))
            .try_with_max_retries(3)
            .expect("a positive retry limit must be accepted");
        assert_eq!(
            spec.max_retries_override().flatten().map(NonZeroU32::get),
            Some(3)
        );

        assert_eq!(
            TaskSpec::once(task("zero"))
                .try_with_max_retries(0)
                .unwrap_err(),
            ConfigError::Zero {
                field: "max_retries"
            }
        );
    }
}