rust-tokio-supervisor 0.1.2

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
//! Lifecycle event payloads and event envelopes.
//!
//! This module owns the observable shape of supervisor lifecycle facts. It keeps
//! payloads typed so state, journal, metrics, and tests do not infer behavior
//! from strings.

use crate::error::types::TaskFailure;
use crate::event::time::{CorrelationId, EventSequence, When};
use crate::id::types::{ChildId, SupervisorPath};
use serde::{Deserialize, Serialize};

/// Location data attached to a supervisor event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Where {
    /// Stable supervisor path that owns the fact.
    pub supervisor_path: SupervisorPath,
    /// Parent child identifier when the fact belongs to a nested node.
    pub parent_id: Option<ChildId>,
    /// Child identifier related to the fact.
    pub child_id: Option<ChildId>,
    /// Human-readable child name.
    pub child_name: Option<String>,
    /// Tokio task identifier when it is available.
    pub tokio_task_id: Option<String>,
    /// Host name reported by the runtime.
    pub host: Option<String>,
    /// Process identifier that emitted the event.
    pub pid: u32,
    /// Current thread name when available.
    pub thread_name: Option<String>,
    /// Rust module path that emitted the event.
    pub module_path: Option<String>,
    /// Source file that emitted the event.
    pub source_file: Option<String>,
    /// Source line that emitted the event.
    pub source_line: Option<u32>,
}

impl Where {
    /// Creates a location for a supervisor path.
    ///
    /// # Arguments
    ///
    /// - `supervisor_path`: Path that owns this lifecycle fact.
    ///
    /// # Returns
    ///
    /// Returns a [`Where`] value with process and thread defaults.
    ///
    /// # Examples
    ///
    /// ```
    /// let location = rust_supervisor::event::payload::Where::new(
    ///     rust_supervisor::id::types::SupervisorPath::root(),
    /// );
    /// assert_eq!(location.supervisor_path.to_string(), "/");
    /// ```
    pub fn new(supervisor_path: SupervisorPath) -> Self {
        Self {
            supervisor_path,
            parent_id: None,
            child_id: None,
            child_name: None,
            tokio_task_id: None,
            host: None,
            pid: std::process::id(),
            thread_name: std::thread::current().name().map(ToOwned::to_owned),
            module_path: None,
            source_file: None,
            source_line: None,
        }
    }

    /// Adds child identity to the location.
    ///
    /// # Arguments
    ///
    /// - `child_id`: Stable child identifier.
    /// - `child_name`: Human-readable child name.
    ///
    /// # Returns
    ///
    /// Returns the updated [`Where`] value.
    pub fn with_child(mut self, child_id: ChildId, child_name: impl Into<String>) -> Self {
        self.child_id = Some(child_id);
        self.child_name = Some(child_name.into());
        self
    }
}

/// State transition recorded by an event payload.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StateTransition {
    /// State before the transition.
    pub from: String,
    /// State after the transition.
    pub to: String,
}

impl StateTransition {
    /// Creates a state transition description.
    ///
    /// # Arguments
    ///
    /// - `from`: Previous state name.
    /// - `to`: New state name.
    ///
    /// # Returns
    ///
    /// Returns a [`StateTransition`].
    pub fn new(from: impl Into<String>, to: impl Into<String>) -> Self {
        Self {
            from: from.into(),
            to: to.into(),
        }
    }
}

/// Policy decision data stored with an event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PolicyDecision {
    /// Low-cardinality decision name.
    pub decision: String,
    /// Delay in milliseconds when restart is delayed.
    pub delay_ms: Option<u64>,
    /// Human-readable reason for diagnostics.
    pub reason: Option<String>,
}

impl PolicyDecision {
    /// Creates a policy decision value.
    ///
    /// # Arguments
    ///
    /// - `decision`: Low-cardinality decision name.
    /// - `delay_ms`: Optional delay in milliseconds.
    /// - `reason`: Optional diagnostic reason.
    ///
    /// # Returns
    ///
    /// Returns a [`PolicyDecision`].
    pub fn new(decision: impl Into<String>, delay_ms: Option<u64>, reason: Option<String>) -> Self {
        Self {
            decision: decision.into(),
            delay_ms,
            reason,
        }
    }
}

/// Command audit data attached to command lifecycle events.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandAudit {
    /// Stable command identifier.
    pub command_id: String,
    /// Actor that requested the command.
    pub requested_by: String,
    /// Operator-provided reason.
    pub reason: String,
    /// Target path for the command.
    pub target_path: SupervisorPath,
    /// Accepted time in nanoseconds since the Unix epoch.
    pub accepted_at_unix_nanos: u128,
    /// Command result summary.
    pub result: String,
}

/// Typed payload for supervisor lifecycle events.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum What {
    /// Child is being started.
    ChildStarting {
        /// Optional state transition carried by this event.
        transition: Option<StateTransition>,
    },
    /// Child is running.
    ChildRunning {
        /// Optional state transition carried by this event.
        transition: Option<StateTransition>,
    },
    /// Child is ready.
    ChildReady {
        /// Optional state transition carried by this event.
        transition: Option<StateTransition>,
    },
    /// Child emitted a heartbeat.
    ChildHeartbeat {
        /// Heartbeat age in milliseconds.
        age_ms: u64,
    },
    /// Child failed with a typed failure.
    ChildFailed {
        /// Failure payload reported by the task.
        failure: TaskFailure,
    },
    /// Child panicked.
    ChildPanicked {
        /// Panic category used for metrics.
        category: String,
    },
    /// Restart backoff was scheduled.
    BackoffScheduled {
        /// Backoff delay in milliseconds.
        delay_ms: u64,
    },
    /// Child is restarting.
    ChildRestarting {
        /// Restart generation after the transition.
        generation: u64,
    },
    /// Child restarted.
    ChildRestarted {
        /// Restart count for the child window.
        restart_count: u64,
    },
    /// Child was quarantined.
    ChildQuarantined {
        /// Quarantine reason.
        reason: String,
    },
    /// Child stopped.
    ChildStopped {
        /// Exit reason.
        reason: String,
    },
    /// Child became unhealthy.
    ChildUnhealthy {
        /// Unhealthy reason.
        reason: String,
    },
    /// Meltdown fuse was tripped.
    Meltdown {
        /// Scope that tripped the fuse.
        scope: String,
    },
    /// Shutdown was requested.
    ShutdownRequested {
        /// Shutdown cause.
        cause: String,
    },
    /// Shutdown phase changed.
    ShutdownPhaseChanged {
        /// Previous phase name.
        from: String,
        /// New phase name.
        to: String,
    },
    /// Shutdown completed.
    ShutdownCompleted {
        /// Shutdown result summary.
        result: String,
    },
    /// Control command was accepted.
    CommandAccepted {
        /// Command audit payload.
        audit: CommandAudit,
    },
    /// Control command completed.
    CommandCompleted {
        /// Command audit payload.
        audit: CommandAudit,
    },
    /// Event subscriber lagged.
    SubscriberLagged {
        /// Number of missed events.
        missed: u64,
    },
}

impl What {
    /// Returns a low-cardinality event name.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// Returns the stable event name.
    ///
    /// # Examples
    ///
    /// ```
    /// let event = rust_supervisor::event::payload::What::ChildRunning {
    ///     transition: None,
    /// };
    /// assert_eq!(event.name(), "ChildRunning");
    /// ```
    pub fn name(&self) -> &'static str {
        match self {
            Self::ChildStarting { .. } => "ChildStarting",
            Self::ChildRunning { .. } => "ChildRunning",
            Self::ChildReady { .. } => "ChildReady",
            Self::ChildHeartbeat { .. } => "ChildHeartbeat",
            Self::ChildFailed { .. } => "ChildFailed",
            Self::ChildPanicked { .. } => "ChildPanicked",
            Self::BackoffScheduled { .. } => "BackoffScheduled",
            Self::ChildRestarting { .. } => "ChildRestarting",
            Self::ChildRestarted { .. } => "ChildRestarted",
            Self::ChildQuarantined { .. } => "ChildQuarantined",
            Self::ChildStopped { .. } => "ChildStopped",
            Self::ChildUnhealthy { .. } => "ChildUnhealthy",
            Self::Meltdown { .. } => "Meltdown",
            Self::ShutdownRequested { .. } => "ShutdownRequested",
            Self::ShutdownPhaseChanged { .. } => "ShutdownPhaseChanged",
            Self::ShutdownCompleted { .. } => "ShutdownCompleted",
            Self::CommandAccepted { .. } => "CommandAccepted",
            Self::CommandCompleted { .. } => "CommandCompleted",
            Self::SubscriberLagged { .. } => "SubscriberLagged",
        }
    }
}

/// Complete lifecycle event envelope.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SupervisorEvent {
    /// Time information for the lifecycle fact.
    pub when: When,
    /// Location information for the lifecycle fact.
    pub r#where: Where,
    /// Typed event payload.
    pub what: What,
    /// Optional policy decision related to the event.
    pub policy: Option<PolicyDecision>,
    /// Monotonic event sequence.
    pub sequence: EventSequence,
    /// Correlation identifier shared by related signals.
    pub correlation_id: CorrelationId,
    /// Configuration version that produced this fact.
    pub config_version: u64,
}

impl SupervisorEvent {
    /// Creates a supervisor lifecycle event.
    ///
    /// # Arguments
    ///
    /// - `when`: Event timing.
    /// - `r#where`: Event location.
    /// - `what`: Event payload.
    /// - `sequence`: Monotonic event sequence.
    /// - `correlation_id`: Correlation identifier for related signals.
    /// - `config_version`: Configuration version for this event.
    ///
    /// # Returns
    ///
    /// Returns a [`SupervisorEvent`].
    ///
    /// # Examples
    ///
    /// ```
    /// let event = rust_supervisor::event::payload::SupervisorEvent::new(
    ///     rust_supervisor::event::time::When::new(
    ///         rust_supervisor::event::time::EventTime::deterministic(
    ///             1,
    ///             1,
    ///             0,
    ///             rust_supervisor::id::types::Generation::initial(),
    ///             rust_supervisor::id::types::Attempt::first(),
    ///         ),
    ///     ),
    ///     rust_supervisor::event::payload::Where::new(
    ///         rust_supervisor::id::types::SupervisorPath::root(),
    ///     ),
    ///     rust_supervisor::event::payload::What::ChildRunning { transition: None },
    ///     rust_supervisor::event::time::EventSequence::new(1),
    ///     rust_supervisor::event::time::CorrelationId::from_uuid(uuid::Uuid::nil()),
    ///     1,
    /// );
    /// assert_eq!(event.what.name(), "ChildRunning");
    /// ```
    pub fn new(
        when: When,
        r#where: Where,
        what: What,
        sequence: EventSequence,
        correlation_id: CorrelationId,
        config_version: u64,
    ) -> Self {
        Self {
            when,
            r#where,
            what,
            policy: None,
            sequence,
            correlation_id,
            config_version,
        }
    }

    /// Attaches a policy decision to an event.
    ///
    /// # Arguments
    ///
    /// - `policy`: Policy decision produced for this lifecycle fact.
    ///
    /// # Returns
    ///
    /// Returns the updated [`SupervisorEvent`].
    pub fn with_policy(mut self, policy: PolicyDecision) -> Self {
        self.policy = Some(policy);
        self
    }
}