rust-tokio-supervisor 0.1.4

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
//! Child declaration model for YAML loading and add_child RPC.
//!
//! This module owns the declarative representation of child declarations as
//! they appear in YAML configuration files or runtime add_child payloads. It
//! also defines the transaction phase enum, pending child state, and
//! compensating records used by the add_child transaction pipeline.

use crate::id::types::ChildId;
use crate::policy::task_role_defaults::{SeverityClass, SidecarConfig, TaskRole};
use crate::readiness::signal::ReadinessPolicy;
use crate::spec::child::{
    BackoffPolicy, ChildSpec, CommandPermissions, Criticality, EnvVar, HealthCheckConfig,
    HealthPolicy, RestartPolicy, SecretRef, TaskKind,
};
use crate::spec::shutdown::ShutdownBudget;
use confique::Config;
use schemars::{JsonSchema, Schema, SchemaGenerator};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::HashSet;
use uuid::Uuid;

/// Valid characters for child names and secret names: alphanumeric, underscore, hyphen.
fn is_valid_identifier(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    let first = s.chars().next().unwrap();
    if !first.is_ascii_alphabetic() && first != '_' {
        return false;
    }
    s.chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

/// Validates a `${SECRET_NAME}` placeholder syntax.
fn is_valid_secret_placeholder(s: &str) -> bool {
    if !s.starts_with("${") || !s.ends_with('}') || s.len() < 4 {
        return false;
    }
    let inner = &s[2..s.len() - 1];
    if inner.is_empty() {
        return false;
    }
    let first = inner.chars().next().unwrap();
    if !first.is_ascii_alphabetic() && first != '_' {
        return false;
    }
    inner.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// Declarative child specification loaded from YAML or received via add_child RPC.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Config, JsonSchema)]
pub struct ChildDeclaration {
    /// Unique child name used for ChildId generation.
    pub name: String,
    /// Task kind.
    #[config(default = "async_worker")]
    #[serde(default)]
    pub kind: TaskKind,
    /// Child criticality.
    #[config(default = "optional")]
    #[serde(default)]
    pub criticality: Criticality,
    /// Low-cardinality tags used for grouping and diagnostics.
    #[config(default = [])]
    #[serde(default)]
    pub tags: Vec<String>,
    /// Optional task role that selects default lifecycle semantics.
    ///
    /// Defaults to `worker` when omitted.
    #[serde(default)]
    #[schemars(default = "default_task_role_for_schema")]
    pub task_role: Option<TaskRole>,
    /// Optional task factory registry key used for worker children.
    #[schemars(!default)]
    #[serde(default)]
    pub factory_key: Option<String>,
    /// Optional sidecar binding used when the role is `sidecar`.
    #[schemars(!default)]
    #[serde(default)]
    pub sidecar_config: Option<SidecarConfig>,
    /// Optional severity classification that overrides the role default.
    #[schemars(!default)]
    #[serde(default)]
    pub severity: Option<SeverityClass>,
    /// Optional group name for group-level isolation and budget tracking.
    #[schemars(!default)]
    #[serde(default)]
    pub group: Option<String>,
    /// Restart policy.
    #[config(default = "permanent")]
    #[serde(default)]
    pub restart_policy: RestartPolicy,
    /// Child dependencies by name.
    #[config(default = [])]
    #[serde(default)]
    pub dependencies: Vec<String>,
    /// Optional health check configuration.
    #[schemars(!default)]
    #[serde(default)]
    pub health_check: Option<HealthCheckConfig>,
    /// Optional readiness policy; defaults to immediate readiness.
    #[schemars(!default)]
    #[serde(default)]
    pub readiness: Option<ReadinessPolicy>,
    /// Optional command permissions.
    #[schemars(!default)]
    #[serde(default)]
    pub command_permissions: Option<CommandPermissions>,
    /// Environment variables.
    #[config(default = [])]
    #[serde(default)]
    pub environment: Vec<EnvVar>,
    /// Secret references.
    #[config(default = [])]
    #[serde(default)]
    pub secrets: Vec<SecretRef>,
}

/// Returns the schema default shown for omitted child `task_role` values.
fn default_task_role_for_schema() -> Option<TaskRole> {
    Some(TaskRole::Worker)
}

/// Split-friendly nested section for child declarations.
///
/// Single-file configs use `children: [...]`. Split `children.yaml` files contain
/// only the child declaration sequence for this section.
#[derive(Debug, Clone, PartialEq, Config)]
pub struct ChildrenConfigSection {
    /// Child declarations loaded from the `children` configuration section.
    #[config(default = [{ "name": "worker" }])]
    pub items: Vec<ChildDeclaration>,
}

impl Default for ChildrenConfigSection {
    /// Returns an empty child declaration section.
    fn default() -> Self {
        Self { items: Vec::new() }
    }
}

impl JsonSchema for ChildrenConfigSection {
    /// Returns the schema name used for split child sections.
    fn schema_name() -> Cow<'static, str> {
        Cow::Borrowed("ChildrenConfigSection")
    }

    /// Returns the transparent array schema for child declarations.
    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
        Vec::<ChildDeclaration>::json_schema(generator)
    }
}

impl Serialize for ChildrenConfigSection {
    /// Serializes child declarations as a transparent array.
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: confique::serde::Serializer,
    {
        self.items.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for ChildrenConfigSection {
    /// Deserializes child declarations from a transparent array.
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: confique::serde::Deserializer<'de>,
    {
        Ok(Self {
            items: Vec::<ChildDeclaration>::deserialize(deserializer)?,
        })
    }
}

impl ChildrenConfigSection {
    /// Returns child declarations as a slice.
    pub fn as_slice(&self) -> &[ChildDeclaration] {
        &self.items
    }

    /// Returns the number of child declarations.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Returns whether this section contains no child declarations.
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }
}

impl From<ChildrenConfigSection> for Vec<ChildDeclaration> {
    /// Converts a child section into its transparent declaration vector.
    fn from(section: ChildrenConfigSection) -> Self {
        section.items
    }
}

/// Phase of an add_child transaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Phase {
    /// Parsing completed.
    Parsed,
    /// Validation passed.
    Validated,
    /// Registered in the topology.
    Registered,
    /// Child has been started.
    Started,
    /// Audit has been persisted.
    Audited,
    /// Transaction committed successfully.
    Committed,
    /// Transaction failed, compensation in progress.
    Compensating,
    /// Compensation completed.
    Compensated,
}

/// Pending child entry in the add_child transaction staging area.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingChild {
    /// Unique transaction identifier.
    pub transaction_id: Uuid,
    /// Original child declaration.
    pub declaration: ChildDeclaration,
    /// Converted runtime child specification.
    pub child_spec: Box<ChildSpec>,
    /// Current transaction phase.
    pub phase: Phase,
    /// Creation timestamp in Unix nanoseconds.
    pub created_at_unix_nanos: u128,
}

// Manual PartialEq — skips child_spec because ChildSpec contains
// Arc<dyn TaskFactory> which does not implement PartialEq.
impl PartialEq for PendingChild {
    /// Compares two PendingChild values, skipping `child_spec`.
    fn eq(&self, other: &Self) -> bool {
        self.transaction_id == other.transaction_id
            && self.declaration == other.declaration
            && self.phase == other.phase
            && self.created_at_unix_nanos == other.created_at_unix_nanos
    }
}

/// Compensating record stored in the audit channel.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CompensatingRecord {
    /// Unique transaction identifier.
    pub transaction_id: Uuid,
    /// Operation type (e.g. "add_child").
    pub operation: String,
    /// Compensation state: "pending", "committed", or "compensated".
    pub state: String,
    /// Child name.
    pub child_name: String,
    /// SHA-256 hash of the ChildDeclaration.
    pub declaration_hash: String,
    /// Optional error reason.
    pub error: Option<String>,
    /// Optional correlation id for linking to 006-5 event chains.
    pub correlation_id: Option<String>,
    /// Optional runtime ChildId, if assigned.
    pub child_id: Option<String>,
    /// Creation timestamp in Unix nanoseconds.
    pub created_at_unix_nanos: u128,
}

/// Validation error for a child declaration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ValidationError {
    /// JSON Pointer field path.
    pub field_path: String,
    /// Human-readable failure reason.
    pub reason: String,
    /// Optional actionable hint.
    pub hint: Option<String>,
}

/// Converts a ChildDeclaration into a ChildSpec.
impl TryFrom<ChildDeclaration> for ChildSpec {
    type Error = ValidationError;

    /// Converts a child declaration into a runtime child specification.
    ///
    /// # Arguments
    ///
    /// - `decl`: The child declaration to convert.
    ///
    /// # Returns
    ///
    /// Returns a [`ChildSpec`] with mapped fields.
    ///
    /// # Errors
    ///
    /// Returns a [`ValidationError`] when the declaration cannot be converted.
    fn try_from(decl: ChildDeclaration) -> Result<Self, Self::Error> {
        let child_id = ChildId::new(&decl.name);
        let kind = decl.kind;
        let criticality = decl.criticality;
        let restart_policy = decl.restart_policy;

        // Convert dependency names to ChildIds.
        let dependencies: Vec<ChildId> = decl.dependencies.iter().map(ChildId::new).collect();

        // Map health_check to health_policy.
        let health_policy = match &decl.health_check {
            Some(hc) => HealthPolicy::new(
                std::time::Duration::from_secs(hc.check_interval_secs),
                std::time::Duration::from_secs(hc.timeout_secs),
            ),
            None => HealthPolicy::new(
                std::time::Duration::from_secs(10),
                std::time::Duration::from_secs(5),
            ),
        };

        let readiness_policy = decl.readiness.unwrap_or(ReadinessPolicy::Immediate);

        let command_permissions = decl.command_permissions.unwrap_or_default();

        Ok(Self {
            id: child_id,
            name: decl.name,
            kind,
            factory: None,
            factory_key: decl.factory_key,
            restart_policy,
            shutdown_budget: ShutdownBudget::new(
                std::time::Duration::from_secs(5),
                std::time::Duration::from_secs(1),
            ),
            health_policy,
            readiness_policy,
            backoff_policy: BackoffPolicy::new(
                std::time::Duration::from_millis(10),
                std::time::Duration::from_secs(1),
                0.0,
            ),
            dependencies,
            tags: decl.tags,
            criticality,
            task_role: decl.task_role,
            sidecar_config: decl.sidecar_config,
            severity: decl.severity,
            group: decl.group,
            health_check: decl.health_check,
            command_permissions,
            environment: decl.environment,
            secrets: decl.secrets,
            isolation: crate::spec::child::Isolation::AsyncWorker,
            cleanup_paths: Vec::new(),
        })
    }
}

/// Validates a child declaration against the given set of existing child names.
///
/// # Arguments
///
/// - `declaration`: The child declaration to validate.
/// - `all_names`: Set of existing child names for dependency existence checks.
///
/// # Returns
///
/// Returns `Ok(())` when all validation rules pass.
///
/// # Errors
///
/// Returns a [`ValidationError`] describing the first rule violation found.
pub fn validate_child_declaration(
    declaration: &ChildDeclaration,
    all_names: &HashSet<String>,
) -> Result<(), ValidationError> {
    // Rule 1: name is non-empty and matches identifier pattern.
    if !is_valid_identifier(&declaration.name) {
        return Err(ValidationError {
            field_path: "name".to_string(),
            reason: format!(
                "Child name '{}' contains invalid characters",
                declaration.name
            ),
            hint: Some("Names must match ^[a-zA-Z_][a-zA-Z0-9_-]*$".to_string()),
        });
    }

    // Rule 1b: factory_key uses the same stable identifier surface as child names.
    if let Some(factory_key) = declaration.factory_key.as_deref()
        && !is_valid_identifier(factory_key)
    {
        return Err(ValidationError {
            field_path: "factory_key".to_string(),
            reason: format!("Factory key '{factory_key}' contains invalid characters"),
            hint: Some("Factory keys must match ^[a-zA-Z_][a-zA-Z0-9_-]*$".to_string()),
        });
    }

    // Rule 2: dependencies exist in all_names.
    for dep in &declaration.dependencies {
        if !all_names.contains(dep) {
            return Err(ValidationError {
                field_path: format!("dependencies[{dep}]"),
                reason: format!("Dependency '{dep}' does not exist in the children list"),
                hint: Some(format!(
                    "Add a child named '{dep}' or remove the dependency"
                )),
            });
        }
    }

    // Rule 4: secret placeholder syntax validation.
    for secret in &declaration.secrets {
        let placeholder = format!("${{{}}}", secret.name);
        if !is_valid_secret_placeholder(&placeholder) {
            return Err(ValidationError {
                field_path: format!("secrets[{}].name", secret.name),
                reason: format!(
                    "Secret name '{}' contains invalid characters for placeholder",
                    secret.name
                ),
                hint: Some("Secret names must match ^[A-Za-z_][A-Za-z0-9_]*$".to_string()),
            });
        }
    }
    for env in &declaration.environment {
        if let Some(ref secret_ref) = env.secret_ref
            && !is_valid_secret_placeholder(secret_ref)
        {
            return Err(ValidationError {
                field_path: format!("environment[{}].secret_ref", env.name),
                reason: format!("Secret reference '{secret_ref}' has invalid syntax"),
                hint: Some(
                    "Secret references must match ^\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}$".to_string(),
                ),
            });
        }
    }

    // Rule 5: value and secret_ref are mutually exclusive.
    for env in &declaration.environment {
        if env.value.is_some() && env.secret_ref.is_some() {
            return Err(ValidationError {
                field_path: format!("environment[{}]", env.name),
                reason: format!(
                    "Environment variable '{}' has both value and secret_ref set",
                    env.name
                ),
                hint: Some("Set either 'value' or 'secret_ref', not both".to_string()),
            });
        }
    }

    Ok(())
}