foxtive-supervisor 0.2.0

Foxtive Supervisor - Advanced task supervision for Rust applications
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
use std::time::Duration;

#[derive(Debug, Clone, PartialEq)]
pub enum SupervisionStatus {
    /// Task completed successfully (expected termination)
    CompletedNormally,
    /// Task failed and won't restart (max attempts reached)
    MaxAttemptsReached,
    /// Task was manually stopped
    ManuallyStopped,
    /// Restart was prevented by should_restart hook
    RestartPrevented,
    /// Setup failed, task never started
    SetupFailed,
    /// A declared dependency failed its setup phase
    DependencyFailed,
}

/// Defines when and how often a task should restart after failure
#[derive(Debug, Clone, PartialEq, Default)]
pub enum RestartPolicy {
    /// Always restart, no matter how many times it fails
    /// Use for: Critical services that must always run
    #[default]
    Always,

    /// Restart up to N times, then give up
    /// Use for: Tasks with a reasonable failure threshold
    MaxAttempts(usize),

    /// Never restart (task runs once)
    /// Use for: One-shot tasks, testing, or explicit manual control
    Never,
}

#[derive(Debug, Clone, PartialEq)]
pub enum TaskState {
    /// Task is running normally
    Running,
    /// Task is paused (not processing)
    Paused,
    /// Task is in error state but will retry
    Retrying,
    /// Task is shutting down
    ShuttingDown,
    /// Task has stopped
    Stopped,
}

/// Health status for monitoring and observability
#[derive(Debug, Clone, PartialEq, Default)]
pub enum HealthStatus {
    /// Task is operating normally
    Healthy,

    /// Task is functioning but with reduced capacity or warnings
    Degraded { reason: String },

    /// Task is not functioning properly
    Unhealthy { reason: String },

    /// Task is in unknown state (initialization, transition)
    #[default]
    Unknown,
}

/// Defines the delay between restart attempts
pub enum BackoffStrategy {
    /// Fixed delay between restarts
    ///
    /// Example: Always wait 5 seconds
    Fixed(Duration),

    /// Exponential backoff: initial * 2^(attempt-1), capped at max
    ///
    /// Example: 2s -> 4s -> 8s -> 16s -> ... -> 60s (max)
    ///
    /// Best for: Network failures, external service issues
    Exponential { initial: Duration, max: Duration },

    /// Linear backoff: initial + (increment * attempt)
    ///
    /// Example: 5s -> 10s -> 15s -> 20s -> ... -> 60s (max)
    ///
    /// Best for: Predictable delay patterns
    Linear {
        initial: Duration,
        increment: Duration,
        max: Duration,
    },

    /// Fibonacci backoff: delays follow Fibonacci sequence
    ///
    /// Example: 1s -> 1s -> 2s -> 3s -> 5s -> 8s -> ... -> max
    ///
    /// Best for: Graceful degradation scenarios
    Fibonacci { initial: Duration, max: Duration },

    /// Custom backoff with user-defined delay calculation
    ///
    /// Receives attempt number, returns delay duration
    Custom(Box<dyn Fn(usize) -> Duration + Send + Sync>),
}

// Manual Debug implementation
impl std::fmt::Debug for BackoffStrategy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Fixed(duration) => f.debug_tuple("Fixed").field(duration).finish(),
            Self::Exponential { initial, max } => f
                .debug_struct("Exponential")
                .field("initial", initial)
                .field("max", max)
                .finish(),
            Self::Linear {
                initial,
                increment,
                max,
            } => f
                .debug_struct("Linear")
                .field("initial", initial)
                .field("increment", increment)
                .field("max", max)
                .finish(),
            Self::Fibonacci { initial, max } => f
                .debug_struct("Fibonacci")
                .field("initial", initial)
                .field("max", max)
                .finish(),
            Self::Custom(_) => f.debug_tuple("Custom").field(&"<function>").finish(),
        }
    }
}

// Manual Clone implementation
impl Clone for BackoffStrategy {
    fn clone(&self) -> Self {
        match self {
            Self::Fixed(duration) => Self::Fixed(*duration),
            Self::Exponential { initial, max } => Self::Exponential {
                initial: *initial,
                max: *max,
            },
            Self::Linear {
                initial,
                increment,
                max,
            } => Self::Linear {
                initial: *initial,
                increment: *increment,
                max: *max,
            },
            Self::Fibonacci { initial, max } => Self::Fibonacci {
                initial: *initial,
                max: *max,
            },
            Self::Custom(_) => {
                // For Custom variant, we clone with default exponential strategy
                // This is a limitation - custom functions can't be cloned
                Self::default()
            }
        }
    }
}

impl Default for BackoffStrategy {
    fn default() -> Self {
        Self::Exponential {
            initial: Duration::from_secs(2),
            max: Duration::from_secs(60),
        }
    }
}

impl BackoffStrategy {
    /// Calculate the delay for a given attempt number (1-indexed)
    pub fn calculate_delay(&self, attempt: usize) -> Duration {
        match self {
            Self::Fixed(duration) => *duration,

            Self::Exponential { initial, max } => {
                // 2^(attempt-1), but cap the exponent to prevent overflow
                let exponent = attempt.saturating_sub(1).min(20);
                let multiplier = 2_u32.saturating_pow(exponent as u32);
                initial.saturating_mul(multiplier).min(*max)
            }

            Self::Linear {
                initial,
                increment,
                max,
            } => {
                let total_increment = increment.saturating_mul(attempt.saturating_sub(1) as u32);
                initial.saturating_add(total_increment).min(*max)
            }

            Self::Fibonacci { initial, max } => {
                let fib_multiplier = Self::fibonacci(attempt);
                initial.saturating_mul(fib_multiplier as u32).min(*max)
            }

            Self::Custom(func) => func(attempt),
        }
    }

    /// Calculate Fibonacci number for backoff
    fn fibonacci(n: usize) -> usize {
        match n {
            0 => 0,
            1 | 2 => 1,
            n => {
                let mut a: usize = 1;
                let mut b = 1;
                for _ in 2..n {
                    let next = a.saturating_add(b);
                    a = b;
                    b = next;
                }
                b
            }
        }
    }

    /// Create a fixed delay strategy
    pub fn fixed(duration: Duration) -> Self {
        Self::Fixed(duration)
    }

    /// Create exponential backoff with defaults (2s -> 60s)
    pub fn exponential() -> Self {
        Self::Exponential {
            initial: Duration::from_secs(2),
            max: Duration::from_secs(60),
        }
    }

    /// Create exponential backoff with custom parameters
    pub fn exponential_custom(initial: Duration, max: Duration) -> Self {
        Self::Exponential { initial, max }
    }

    /// Create linear backoff with defaults (5s increments, max 60s)
    pub fn linear() -> Self {
        Self::Linear {
            initial: Duration::from_secs(5),
            increment: Duration::from_secs(5),
            max: Duration::from_secs(60),
        }
    }

    /// Create linear backoff with custom parameters
    pub fn linear_custom(initial: Duration, increment: Duration, max: Duration) -> Self {
        Self::Linear {
            initial,
            increment,
            max,
        }
    }

    /// Create Fibonacci backoff with defaults (1s -> 60s)
    pub fn fibonacci_with_default() -> Self {
        Self::Fibonacci {
            initial: Duration::from_secs(1),
            max: Duration::from_secs(60),
        }
    }

    /// Create custom backoff with user-defined function
    pub fn custom<F>(func: F) -> Self
    where
        F: Fn(usize) -> Duration + Send + Sync + 'static,
    {
        Self::Custom(Box::new(func))
    }
}

impl HealthStatus {
    /// Check if the status is healthy
    pub fn is_healthy(&self) -> bool {
        matches!(self, Self::Healthy)
    }

    /// Check if the status is unhealthy
    pub fn is_unhealthy(&self) -> bool {
        matches!(self, Self::Unhealthy { .. })
    }

    /// Check if the status is degraded
    pub fn is_degraded(&self) -> bool {
        matches!(self, Self::Degraded { .. })
    }

    /// Get the reason for non-healthy status
    pub fn reason(&self) -> Option<&str> {
        match self {
            Self::Degraded { reason } | Self::Unhealthy { reason } => Some(reason),
            _ => None,
        }
    }

    /// Create a healthy status
    pub fn healthy() -> Self {
        Self::Healthy
    }

    /// Create a degraded status with reason
    pub fn degraded(reason: impl Into<String>) -> Self {
        Self::Degraded {
            reason: reason.into(),
        }
    }

    /// Create an unhealthy status with reason
    pub fn unhealthy(reason: impl Into<String>) -> Self {
        Self::Unhealthy {
            reason: reason.into(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_exponential_backoff() {
        let strategy = BackoffStrategy::exponential();

        assert_eq!(strategy.calculate_delay(1), Duration::from_secs(2));
        assert_eq!(strategy.calculate_delay(2), Duration::from_secs(4));
        assert_eq!(strategy.calculate_delay(3), Duration::from_secs(8));
        assert_eq!(strategy.calculate_delay(4), Duration::from_secs(16));
        assert_eq!(strategy.calculate_delay(5), Duration::from_secs(32));
        assert_eq!(strategy.calculate_delay(6), Duration::from_secs(60)); // capped at max
    }

    #[test]
    fn test_linear_backoff() {
        let strategy = BackoffStrategy::linear();

        assert_eq!(strategy.calculate_delay(1), Duration::from_secs(5));
        assert_eq!(strategy.calculate_delay(2), Duration::from_secs(10));
        assert_eq!(strategy.calculate_delay(3), Duration::from_secs(15));
        assert_eq!(strategy.calculate_delay(4), Duration::from_secs(20));
    }

    #[test]
    fn test_fibonacci_backoff() {
        let strategy = BackoffStrategy::fibonacci_with_default();

        assert_eq!(strategy.calculate_delay(1), Duration::from_secs(1));
        assert_eq!(strategy.calculate_delay(2), Duration::from_secs(1));
        assert_eq!(strategy.calculate_delay(3), Duration::from_secs(2));
        assert_eq!(strategy.calculate_delay(4), Duration::from_secs(3));
        assert_eq!(strategy.calculate_delay(5), Duration::from_secs(5));
        assert_eq!(strategy.calculate_delay(6), Duration::from_secs(8));
    }

    #[test]
    fn test_fixed_backoff() {
        let strategy = BackoffStrategy::fixed(Duration::from_secs(10));

        assert_eq!(strategy.calculate_delay(1), Duration::from_secs(10));
        assert_eq!(strategy.calculate_delay(5), Duration::from_secs(10));
        assert_eq!(strategy.calculate_delay(100), Duration::from_secs(10));
    }

    #[test]
    fn test_custom_backoff() {
        let strategy = BackoffStrategy::custom(|attempt| Duration::from_secs(attempt as u64 * 3));

        assert_eq!(strategy.calculate_delay(1), Duration::from_secs(3));
        assert_eq!(strategy.calculate_delay(2), Duration::from_secs(6));
        assert_eq!(strategy.calculate_delay(5), Duration::from_secs(15));
    }

    #[test]
    fn test_health_status() {
        let healthy = HealthStatus::healthy();
        assert!(healthy.is_healthy());
        assert!(!healthy.is_unhealthy());
        assert_eq!(healthy.reason(), None);

        let degraded = HealthStatus::degraded("High memory usage");
        assert!(degraded.is_degraded());
        assert_eq!(degraded.reason(), Some("High memory usage"));

        let unhealthy = HealthStatus::unhealthy("Connection lost");
        assert!(unhealthy.is_unhealthy());
        assert_eq!(unhealthy.reason(), Some("Connection lost"));
    }

    #[test]
    fn test_backoff_debug() {
        let exponential = BackoffStrategy::exponential();
        let debug_str = format!("{:?}", exponential);
        assert!(debug_str.contains("Exponential"));

        let custom = BackoffStrategy::custom(|n| Duration::from_secs(n as u64));
        let debug_str = format!("{:?}", custom);
        assert!(debug_str.contains("Custom"));
    }

    #[test]
    fn test_backoff_clone() {
        let original = BackoffStrategy::exponential();
        let cloned = original.clone();

        assert_eq!(original.calculate_delay(3), cloned.calculate_delay(3));
    }
}