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
466
467
468
//! Runtime control plane lifecycle state.
//!
//! This module stores health state and final exit reports that a
//! `SupervisorHandle` can read repeatedly. It does not execute runtime control
//! loop commands.

use crate::error::types::SupervisorError;
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::Notify;

/// Stable runtime control plane state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RuntimeControlPlaneState {
    /// Control loop task has been created but is not yet accepting commands.
    Starting,
    /// Control loop can still accept commands.
    Alive,
    /// Control plane has received an explicit shutdown request.
    ShuttingDown,
    /// Control loop completed normally.
    Completed,
    /// Control loop failed.
    Failed,
}

impl RuntimeControlPlaneState {
    /// Returns a low-cardinality state label.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// Returns a stable state label.
    ///
    /// # Examples
    ///
    /// ```
    /// let state = rust_supervisor::runtime::lifecycle::RuntimeControlPlaneState::Alive;
    /// assert_eq!(state.as_str(), "alive");
    /// ```
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Starting => "starting",
            Self::Alive => "alive",
            Self::ShuttingDown => "shutting_down",
            Self::Completed => "completed",
            Self::Failed => "failed",
        }
    }

    /// Returns whether this state is terminal.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// Returns `true` when the state is terminal.
    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::Completed | Self::Failed)
    }
}

/// Runtime control loop failure reason.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RuntimeFailureReason {
    /// Failure phase.
    pub phase: String,
    /// Human-readable failure reason.
    pub reason: String,
    /// Whether the failure came from panic.
    pub panic: bool,
    /// Whether callers can recover by creating a new supervisor.
    pub recoverable: bool,
}

impl RuntimeFailureReason {
    /// Creates a failure reason.
    ///
    /// # Arguments
    ///
    /// - `phase`: Failure phase.
    /// - `reason`: Human-readable reason.
    /// - `panic`: Whether the failure came from panic.
    /// - `recoverable`: Whether a new supervisor can recover.
    ///
    /// # Returns
    ///
    /// Returns a [`RuntimeFailureReason`].
    ///
    /// # Examples
    ///
    /// ```
    /// let failure = rust_supervisor::runtime::lifecycle::RuntimeFailureReason::new(
    ///     "watchdog",
    ///     "runtime control loop panic",
    ///     true,
    ///     true,
    /// );
    /// assert!(failure.panic);
    /// ```
    pub fn new(
        phase: impl Into<String>,
        reason: impl Into<String>,
        panic: bool,
        recoverable: bool,
    ) -> Self {
        Self {
            phase: phase.into(),
            reason: reason.into(),
            panic,
            recoverable,
        }
    }
}

/// Final runtime control loop exit report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RuntimeExitReport {
    /// Final state, which must be completed or failed.
    pub state: RuntimeControlPlaneState,
    /// Exit phase.
    pub phase: String,
    /// Human-readable exit reason.
    pub reason: String,
    /// Whether callers can recover by creating a new supervisor.
    pub recoverable: bool,
    /// Final report timestamp in Unix epoch nanoseconds.
    pub completed_at_unix_nanos: u128,
    /// Whether the report came from panic.
    pub panic: bool,
}

impl RuntimeExitReport {
    /// Creates a completed exit report.
    ///
    /// # Arguments
    ///
    /// - `phase`: Completion phase.
    /// - `reason`: Human-readable reason.
    ///
    /// # Returns
    ///
    /// Returns a completed [`RuntimeExitReport`].
    ///
    /// # Examples
    ///
    /// ```
    /// let report = rust_supervisor::runtime::lifecycle::RuntimeExitReport::completed(
    ///     "shutdown",
    ///     "operator requested shutdown",
    /// );
    /// assert_eq!(report.state.as_str(), "completed");
    /// ```
    pub fn completed(phase: impl Into<String>, reason: impl Into<String>) -> Self {
        Self {
            state: RuntimeControlPlaneState::Completed,
            phase: phase.into(),
            reason: reason.into(),
            recoverable: false,
            completed_at_unix_nanos: unix_nanos_now(),
            panic: false,
        }
    }

    /// Creates a failed exit report.
    ///
    /// # Arguments
    ///
    /// - `phase`: Failure phase.
    /// - `reason`: Human-readable reason.
    /// - `panic`: Whether the failure came from panic.
    /// - `recoverable`: Whether a new supervisor can recover.
    ///
    /// # Returns
    ///
    /// Returns a failed [`RuntimeExitReport`].
    pub fn failed(
        phase: impl Into<String>,
        reason: impl Into<String>,
        panic: bool,
        recoverable: bool,
    ) -> Self {
        Self {
            state: RuntimeControlPlaneState::Failed,
            phase: phase.into(),
            reason: reason.into(),
            recoverable,
            completed_at_unix_nanos: unix_nanos_now(),
            panic,
        }
    }

    /// Converts this report into a health failure reason.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// Returns a failure reason when this report represents failure.
    pub fn failure_reason(&self) -> Option<RuntimeFailureReason> {
        (self.state == RuntimeControlPlaneState::Failed).then(|| {
            RuntimeFailureReason::new(
                self.phase.clone(),
                self.reason.clone(),
                self.panic,
                self.recoverable,
            )
        })
    }
}

/// Health report read by runtime callers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RuntimeHealthReport {
    /// Whether the control loop can still accept commands.
    pub alive: bool,
    /// Current control plane state.
    pub state: RuntimeControlPlaneState,
    /// Control plane startup timestamp in Unix epoch nanoseconds.
    pub started_at_unix_nanos: u128,
    /// Last observation timestamp in Unix epoch nanoseconds.
    pub last_observed_at_unix_nanos: u128,
    /// Structured reason for failed state.
    pub failure: Option<RuntimeFailureReason>,
    /// Final report for completed or failed state.
    pub exit_report: Option<RuntimeExitReport>,
}

/// Runtime control plane with repeatable reads.
#[derive(Debug, Clone)]
pub struct RuntimeControlPlane {
    /// Shared inner state.
    inner: Arc<Mutex<RuntimeControlPlaneInner>>,
    /// Terminal state notifier.
    notify: Arc<Notify>,
}

impl RuntimeControlPlane {
    /// Creates new control plane lifecycle state.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// Returns a [`RuntimeControlPlane`] in starting state.
    ///
    /// # Examples
    ///
    /// ```
    /// let control_plane = rust_supervisor::runtime::lifecycle::RuntimeControlPlane::new();
    /// assert!(!control_plane.is_alive());
    /// ```
    pub fn new() -> Self {
        let now = unix_nanos_now();
        Self {
            inner: Arc::new(Mutex::new(RuntimeControlPlaneInner {
                state: RuntimeControlPlaneState::Starting,
                started_at_unix_nanos: now,
                last_observed_at_unix_nanos: now,
                exit_report: None,
                failure: None,
                shutdown_requested_by: None,
                shutdown_reason: None,
            })),
            notify: Arc::new(Notify::new()),
        }
    }

    /// Marks the control loop as accepting commands.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// This function does not return a value.
    pub fn mark_alive(&self) {
        let mut inner = self.lock_inner();
        if !inner.state.is_terminal() {
            inner.state = RuntimeControlPlaneState::Alive;
            inner.last_observed_at_unix_nanos = unix_nanos_now();
        }
    }

    /// Returns whether the control loop is alive.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// Returns `true` when ordinary control commands may be sent.
    pub fn is_alive(&self) -> bool {
        let mut inner = self.lock_inner();
        inner.last_observed_at_unix_nanos = unix_nanos_now();
        inner.state == RuntimeControlPlaneState::Alive
    }

    /// Reads a health report.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// Returns a [`RuntimeHealthReport`] value for the current observation.
    pub fn health(&self) -> RuntimeHealthReport {
        let mut inner = self.lock_inner();
        inner.last_observed_at_unix_nanos = unix_nanos_now();
        RuntimeHealthReport {
            alive: inner.state == RuntimeControlPlaneState::Alive,
            state: inner.state,
            started_at_unix_nanos: inner.started_at_unix_nanos,
            last_observed_at_unix_nanos: inner.last_observed_at_unix_nanos,
            failure: inner.failure.clone(),
            exit_report: inner.exit_report.clone(),
        }
    }

    /// Marks that shutdown has been requested.
    ///
    /// # Arguments
    ///
    /// - `requested_by`: Actor that requested shutdown.
    /// - `reason`: Human-readable shutdown reason.
    ///
    /// # Returns
    ///
    /// Returns an existing final report when the control plane already ended.
    pub fn mark_shutdown_requested(
        &self,
        requested_by: impl Into<String>,
        reason: impl Into<String>,
    ) -> Result<Option<RuntimeExitReport>, SupervisorError> {
        let requested_by = requested_by.into();
        let reason = reason.into();
        validate_required_text(&requested_by, "requested_by")?;
        validate_required_text(&reason, "reason")?;

        let mut inner = self.lock_inner();
        if let Some(report) = &inner.exit_report {
            return Ok(Some(report.clone()));
        }
        inner.state = RuntimeControlPlaneState::ShuttingDown;
        inner.shutdown_requested_by = Some(requested_by);
        inner.shutdown_reason = Some(reason);
        inner.last_observed_at_unix_nanos = unix_nanos_now();
        Ok(None)
    }

    /// Writes the final exit report.
    ///
    /// # Arguments
    ///
    /// - `report`: Final runtime exit report.
    ///
    /// # Returns
    ///
    /// Returns the cached final report.
    pub fn complete(&self, report: RuntimeExitReport) -> RuntimeExitReport {
        let mut inner = self.lock_inner();
        if let Some(existing) = &inner.exit_report {
            return existing.clone();
        }
        inner.state = report.state;
        inner.failure = report.failure_reason();
        inner.exit_report = Some(report.clone());
        inner.last_observed_at_unix_nanos = report.completed_at_unix_nanos;
        self.notify.notify_waiters();
        report
    }

    /// Returns the cached final exit report.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// Returns the final report when the control plane has ended.
    pub fn final_report(&self) -> Option<RuntimeExitReport> {
        self.lock_inner().exit_report.clone()
    }

    /// Waits for the control plane to reach a terminal state.
    ///
    /// # Arguments
    ///
    /// This function has no arguments.
    ///
    /// # Returns
    ///
    /// Returns the cached final [`RuntimeExitReport`].
    pub async fn join(&self) -> RuntimeExitReport {
        loop {
            let notified = self.notify.notified();
            if let Some(report) = self.final_report() {
                return report;
            }
            notified.await;
        }
    }

    /// Acquires the inner state lock.
    fn lock_inner(&self) -> std::sync::MutexGuard<'_, RuntimeControlPlaneInner> {
        self.inner
            .lock()
            .expect("runtime control plane lock poisoned")
    }
}

impl Default for RuntimeControlPlane {
    /// Creates the default runtime control plane.
    fn default() -> Self {
        Self::new()
    }
}

/// Runtime control plane inner state.
#[derive(Debug)]
struct RuntimeControlPlaneInner {
    /// Current state.
    state: RuntimeControlPlaneState,
    /// Startup timestamp.
    started_at_unix_nanos: u128,
    /// Last observation timestamp.
    last_observed_at_unix_nanos: u128,
    /// Final exit report.
    exit_report: Option<RuntimeExitReport>,
    /// Failure reason.
    failure: Option<RuntimeFailureReason>,
    /// Shutdown requester.
    shutdown_requested_by: Option<String>,
    /// Shutdown reason.
    shutdown_reason: Option<String>,
}

/// Validates required text.
fn validate_required_text(value: &str, field: &str) -> Result<(), SupervisorError> {
    if value.trim().is_empty() {
        return Err(SupervisorError::InvalidTransition {
            message: format!("runtime control plane {field} must not be empty"),
        });
    }
    Ok(())
}

/// Returns current Unix epoch nanoseconds.
fn unix_nanos_now() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or_default()
}