rust-tokio-supervisor 0.1.3

A Rust tokio supervisor with declarative task supervision, restart policy, shutdown coordination, and observability.
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
//! Task role defaults for supervised children.
//!
//! This module owns role classification, default policy bundles, effective
//! policy attribution, and semantic conflict diagnostics.

use crate::id::types::ChildId;
use crate::spec::child::{BackoffPolicy, RestartPolicy};
use crate::spec::supervisor::{EscalationPolicy, RestartLimit};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
use std::time::Duration;

/// Task role classification for supervised children.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TaskRole {
    /// Long-running service that should stay online.
    Service,
    /// Background worker with bounded retry semantics.
    Worker,
    /// One-shot job that must not auto-restart on success.
    Job,
    /// Auxiliary sidecar process attached to a primary service.
    Sidecar,
    /// Nested supervisor tree treated as a single unit.
    Supervisor,
}

impl TaskRole {
    /// Returns a stable low-cardinality role label.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// Returns a snake_case static role label.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Service => "service",
            Self::Worker => "worker",
            Self::Job => "job",
            Self::Sidecar => "sidecar",
            Self::Supervisor => "supervisor",
        }
    }
}

impl Display for TaskRole {
    /// Formats the role as a stable label.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Configuration for sidecar attachment to a primary service.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SidecarConfig {
    /// Child ID of the primary service this sidecar attaches to.
    pub primary_child_id: ChildId,
    /// Whether lifecycle events are linked.
    #[serde(default)]
    pub linked_lifecycle: bool,
}

impl SidecarConfig {
    /// Creates a sidecar binding configuration.
    ///
    /// # Arguments
    ///
    /// - `primary_child_id`: Child ID of the primary service.
    /// - `linked_lifecycle`: Whether lifecycle operations are linked.
    ///
    /// # Returns
    ///
    /// Returns a [`SidecarConfig`] value.
    pub fn new(primary_child_id: ChildId, linked_lifecycle: bool) -> Self {
        Self {
            primary_child_id,
            linked_lifecycle,
        }
    }
}

/// Action taken when a child exits successfully.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OnSuccessAction {
    /// Restart the child to keep it online.
    Restart,
    /// Stop the child permanently.
    Stop,
    /// Take no automatic action.
    NoOp,
}

/// Action taken when a child exits with failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OnFailureAction {
    /// Restart with backoff policy applied.
    RestartWithBackoff,
    /// Restart indefinitely.
    RestartPermanent,
    /// Stop and escalate to parent or shutdown tree.
    StopAndEscalate,
}

/// Action taken when a child receives an explicit stop request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OnManualStopAction {
    /// Stop permanently until explicitly restarted.
    StopForever,
    /// Stop but allow a future explicit restart.
    StopUntilExplicitRestart,
}

/// Action taken when a child exceeds its execution timeout.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OnTimeoutAction {
    /// Restart with backoff policy applied.
    RestartWithBackoff,
    /// Stop and escalate to parent or shutdown tree.
    StopAndEscalate,
}

/// Action taken when restart budget is exhausted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OnBudgetExhaustedAction {
    /// Stop and escalate to parent or shutdown tree.
    StopAndEscalate,
    /// Quarantine the child or scope without escalating.
    Quarantine,
}

/// Default policy bundle bound to a specific task role.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct RoleDefaultPolicy {
    /// Action on successful exit.
    pub on_success_exit: OnSuccessAction,
    /// Action on failure exit.
    pub on_failure_exit: OnFailureAction,
    /// Action on explicit manual stop.
    pub on_manual_stop: OnManualStopAction,
    /// Action on execution timeout.
    pub on_timeout: OnTimeoutAction,
    /// Action when restart budget is exhausted.
    pub on_budget_exhausted: OnBudgetExhaustedAction,
    /// Default restart limit.
    pub default_restart_limit: Option<RestartLimit>,
    /// Default escalation policy.
    pub default_escalation_policy: Option<EscalationPolicy>,
    /// Default backoff policy.
    pub default_backoff_policy: Option<BackoffPolicy>,
    /// Exit codes considered successful.
    #[serde(default = "default_success_exit_codes")]
    pub success_exit_codes: Vec<i32>,
}

/// Role-specific differences used to build a default policy.
struct RoleDefaultPolicyDifferences {
    /// Action on successful exit.
    on_success_exit: OnSuccessAction,
    /// Action on execution timeout.
    on_timeout: OnTimeoutAction,
    /// Maximum restart count inside the default restart limit window.
    max_restarts: u32,
}

impl From<RoleDefaultPolicyDifferences> for RoleDefaultPolicy {
    /// Converts role-specific differences into a complete default policy.
    ///
    /// # Arguments
    ///
    /// - `differences`: Role-specific policy fields.
    ///
    /// # Returns
    ///
    /// Returns a complete [`RoleDefaultPolicy`] with shared defaults applied.
    fn from(differences: RoleDefaultPolicyDifferences) -> Self {
        Self {
            on_success_exit: differences.on_success_exit,
            on_failure_exit: OnFailureAction::RestartWithBackoff,
            on_manual_stop: OnManualStopAction::StopForever,
            on_timeout: differences.on_timeout,
            on_budget_exhausted: OnBudgetExhaustedAction::StopAndEscalate,
            default_restart_limit: Some(bounded_restart_limit(differences.max_restarts)),
            default_escalation_policy: Some(EscalationPolicy::EscalateToParent),
            default_backoff_policy: Some(default_backoff_policy()),
            success_exit_codes: default_success_exit_codes(),
        }
    }
}

impl RoleDefaultPolicy {
    /// Returns the default policy pack for a task role.
    ///
    /// # Arguments
    ///
    /// - `role`: Task role used to select defaults.
    ///
    /// # Returns
    ///
    /// Returns a role-specific [`RoleDefaultPolicy`].
    pub fn for_role(role: TaskRole) -> Self {
        match role {
            TaskRole::Service => service_default(),
            TaskRole::Worker => worker_default(),
            TaskRole::Job => job_default(),
            TaskRole::Sidecar => sidecar_default(),
            TaskRole::Supervisor => supervisor_default(),
        }
    }
}

/// Source used to build an effective policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PolicySource {
    /// Policy came from an explicit role default.
    RoleDefault,
    /// Policy contains user overrides.
    UserOverride,
    /// Policy used the conservative fallback role.
    FallbackDefault,
}

impl Display for PolicySource {
    /// Formats the policy source as a stable label.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        let label = match self {
            Self::RoleDefault => "role_default",
            Self::UserOverride => "user_override",
            Self::FallbackDefault => "fallback_default",
        };
        formatter.write_str(label)
    }
}

/// Severity classification for failure escalation bifurcation.
///
/// Ordering: Critical > Standard > Optional (highest to lowest severity).
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
pub enum SeverityClass {
    /// Optional: failure follows noise-reduction path (no alert upgrade).
    Optional,
    /// Standard: follows the default TaskRole behavior.
    Standard,
    /// Critical: failure must trigger escalation path.
    Critical,
}

/// Effective policy selected for one child.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct EffectivePolicy {
    /// Effective task role after fallback handling.
    pub task_role: TaskRole,
    /// Policy pack selected for the effective role.
    pub policy_pack: RoleDefaultPolicy,
    /// Source of the effective policy.
    pub source: PolicySource,
    /// Whether the worker fallback default was used.
    pub used_fallback: bool,
    /// Fields explicitly overridden by the user.
    pub overridden_fields: Vec<String>,
    /// Severity classification for escalation bifurcation.
    pub severity: SeverityClass,
    /// Group name for group isolation (None = not grouped).
    pub group_name: Option<String>,
}

impl EffectivePolicy {
    /// Merges task role defaults with known user override markers.
    ///
    /// # Arguments
    ///
    /// - `role`: Optional declared task role.
    /// - `overridden_fields`: Fields explicitly set by the user.
    ///
    /// # Returns
    ///
    /// Returns an [`EffectivePolicy`] with fallback attribution.
    pub fn merge(role: Option<TaskRole>, overridden_fields: Vec<String>) -> Self {
        let used_fallback = role.is_none();
        let task_role = role.unwrap_or(TaskRole::Worker);
        let source = if used_fallback {
            PolicySource::FallbackDefault
        } else if overridden_fields.is_empty() {
            PolicySource::RoleDefault
        } else {
            PolicySource::UserOverride
        };
        let severity = Self::default_severity(task_role);
        Self {
            task_role,
            policy_pack: RoleDefaultPolicy::for_role(task_role),
            source,
            used_fallback,
            overridden_fields,
            severity,
            group_name: None,
        }
    }

    /// Returns the default [`SeverityClass`] for a given [`TaskRole`].
    fn default_severity(role: TaskRole) -> SeverityClass {
        match role {
            TaskRole::Service => SeverityClass::Critical,
            TaskRole::Supervisor => SeverityClass::Critical,
            TaskRole::Worker => SeverityClass::Standard,
            TaskRole::Job => SeverityClass::Optional,
            TaskRole::Sidecar => SeverityClass::Standard,
        }
    }

    /// Builds an effective policy for a child specification.
    ///
    /// # Arguments
    ///
    /// - `child`: Child specification to inspect.
    ///
    /// # Returns
    ///
    /// Returns the effective role policy for the child.
    pub fn for_child(child: &crate::spec::child::ChildSpec) -> Self {
        let mut overridden = Vec::new();
        if child.restart_policy != RestartPolicy::Transient {
            overridden.push("restart_policy".to_string());
        }
        let effective_policy = Self::merge(child.task_role, overridden);
        if child.task_role.is_none() {
            tracing::warn!(
                child_id = %child.id,
                task_role = %effective_policy.task_role,
                used_fallback_default = effective_policy.used_fallback,
                effective_policy_source = %effective_policy.source,
                "task role missing, falling back to worker default"
            );
        }
        effective_policy
    }
}

/// Describes one role semantic conflict.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RoleSemanticConflict {
    /// Child that owns the conflict.
    pub child_id: ChildId,
    /// Declared task role.
    pub task_role: TaskRole,
    /// Conflicting field name.
    pub conflicting_field: String,
    /// User-provided value.
    pub user_value: String,
    /// Role default expectation.
    pub expected_semantic: String,
    /// Human-readable reason.
    pub reason: String,
}

/// Returns semantic conflicts for one child.
///
/// # Arguments
///
/// - `child`: Child specification to inspect.
///
/// # Returns
///
/// Returns a list of role semantic conflicts.
pub fn semantic_conflicts_for_child(
    child: &crate::spec::child::ChildSpec,
) -> Vec<RoleSemanticConflict> {
    let mut conflicts = Vec::new();
    if child.task_role == Some(TaskRole::Job) && child.restart_policy == RestartPolicy::Permanent {
        conflicts.push(RoleSemanticConflict {
            child_id: child.id.clone(),
            task_role: TaskRole::Job,
            conflicting_field: "restart_policy".to_string(),
            user_value: "permanent".to_string(),
            expected_semantic: "job success should stop".to_string(),
            reason: "Job role must not silently use permanent restart semantics".to_string(),
        });
    }
    conflicts
}

/// Returns default success exit codes.
///
/// # Arguments
///
/// This function has no arguments.
///
/// # Returns
///
/// Returns a vector containing exit code zero.
fn default_success_exit_codes() -> Vec<i32> {
    vec![0]
}

/// Returns a bounded restart limit used by task role defaults.
fn bounded_restart_limit(max_restarts: u32) -> RestartLimit {
    RestartLimit::new(max_restarts, Duration::from_secs(60))
}

/// Returns a default backoff policy used by task role defaults.
fn default_backoff_policy() -> BackoffPolicy {
    BackoffPolicy::new(Duration::from_millis(50), Duration::from_secs(5), 0.2)
}

/// Returns service task role defaults.
fn service_default() -> RoleDefaultPolicy {
    RoleDefaultPolicyDifferences {
        on_success_exit: OnSuccessAction::Restart,
        on_timeout: OnTimeoutAction::RestartWithBackoff,
        max_restarts: 10,
    }
    .into()
}

/// Returns worker task role defaults.
fn worker_default() -> RoleDefaultPolicy {
    RoleDefaultPolicyDifferences {
        on_success_exit: OnSuccessAction::Stop,
        on_timeout: OnTimeoutAction::RestartWithBackoff,
        max_restarts: 3,
    }
    .into()
}

/// Returns job task role defaults.
fn job_default() -> RoleDefaultPolicy {
    RoleDefaultPolicyDifferences {
        on_success_exit: OnSuccessAction::Stop,
        on_timeout: OnTimeoutAction::StopAndEscalate,
        max_restarts: 1,
    }
    .into()
}

/// Returns sidecar task role defaults.
fn sidecar_default() -> RoleDefaultPolicy {
    RoleDefaultPolicyDifferences {
        on_success_exit: OnSuccessAction::Restart,
        on_timeout: OnTimeoutAction::RestartWithBackoff,
        max_restarts: 5,
    }
    .into()
}

/// Returns nested supervisor task role defaults.
fn supervisor_default() -> RoleDefaultPolicy {
    RoleDefaultPolicyDifferences {
        on_success_exit: OnSuccessAction::Restart,
        on_timeout: OnTimeoutAction::RestartWithBackoff,
        max_restarts: 3,
    }
    .into()
}