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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Public runtime control handle.
//!
//! The handle owns the command sender side and exposes asynchronous control
//! methods. It keeps command construction separate from runtime execution.
use crate::child_runner::runner::ChildRunReport;
use crate::control::command::{CommandMeta, CommandResult, ControlCommand};
use crate::dashboard::runtime::DashboardIpcRuntimeGuard;
use crate::error::types::SupervisorError;
use crate::id::types::{ChildId, SupervisorPath};
use crate::observe::pipeline::{ObservabilityPipeline, TestRecorder};
use crate::runtime::lifecycle::{RuntimeControlPlane, RuntimeExitReport, RuntimeHealthReport};
use crate::runtime::message::{ControlPlaneMessage, RuntimeLoopMessage};
use std::sync::Arc;
use std::sync::Mutex;
use tokio::sync::{broadcast, mpsc, oneshot};
/// Cloneable handle used to control a running supervisor.
#[derive(Debug, Clone)]
pub struct SupervisorHandle {
/// Sender side used to submit runtime control commands.
command_sender: mpsc::Sender<RuntimeLoopMessage>,
/// Broadcast sender used to create lifecycle event subscriptions.
event_sender: broadcast::Sender<String>,
/// Runtime control plane lifecycle state.
control_plane: RuntimeControlPlane,
/// Shared typed observability pipeline.
observability: Arc<Mutex<ObservabilityPipeline>>,
/// Optional dashboard IPC runtime guard.
dashboard_runtime: Option<Arc<DashboardIpcRuntimeGuard>>,
}
impl SupervisorHandle {
/// Creates a runtime handle from channel senders.
///
/// # Arguments
///
/// - `command_sender`: Sender used to submit runtime commands.
/// - `event_sender`: Sender used to subscribe to lifecycle events.
///
/// # Returns
///
/// Returns a [`SupervisorHandle`].
pub fn new(
command_sender: mpsc::Sender<RuntimeLoopMessage>,
event_sender: broadcast::Sender<String>,
control_plane: RuntimeControlPlane,
) -> Self {
Self::new_with_observability(
command_sender,
event_sender,
control_plane,
Arc::new(Mutex::new(ObservabilityPipeline::new(16, 16))),
)
}
/// Creates a runtime handle with a shared observability pipeline.
///
/// # Arguments
///
/// - `command_sender`: Sender used to submit runtime commands.
/// - `event_sender`: Sender used to subscribe to lifecycle event text.
/// - `control_plane`: Runtime control plane lifecycle state.
/// - `observability`: Shared typed observability pipeline.
///
/// # Returns
///
/// Returns a [`SupervisorHandle`].
pub(crate) fn new_with_observability(
command_sender: mpsc::Sender<RuntimeLoopMessage>,
event_sender: broadcast::Sender<String>,
control_plane: RuntimeControlPlane,
observability: Arc<Mutex<ObservabilityPipeline>>,
) -> Self {
Self {
command_sender,
event_sender,
control_plane,
observability,
dashboard_runtime: None,
}
}
/// Attaches a dashboard IPC runtime guard to this handle.
///
/// # Arguments
///
/// - `dashboard_runtime`: Guard that owns dashboard IPC runtime tasks.
///
/// # Returns
///
/// Returns this handle with dashboard runtime lifecycle attached.
pub(crate) fn with_dashboard_runtime(
mut self,
dashboard_runtime: Arc<DashboardIpcRuntimeGuard>,
) -> Self {
self.dashboard_runtime = Some(dashboard_runtime);
self
}
/// Adds a child manifest under a supervisor path.
///
/// # Arguments
///
/// - `target`: Supervisor path that should receive the child.
/// - `child_manifest`: Child manifest text supplied by the caller.
/// - `requested_by`: Caller that requested the command.
/// - `reason`: Human-readable command reason.
///
/// # Child Manifest Example
///
/// The runtime expects a YAML child declaration. The smallest useful
/// manifest names the child and selects a task kind:
///
/// ```yaml
/// name: worker
/// kind: async_worker
/// ```
///
/// Optional fields can be added when the child needs dependencies,
/// lifecycle policy, resource limits, command permissions, environment
/// variables, or secret references:
///
/// ```yaml
/// name: worker
/// kind: async_worker
/// criticality: optional
/// restart_policy: transient
/// dependencies:
/// - cache
/// health_check:
/// check_interval_secs: 10
/// timeout_secs: 5
/// max_retries: 3
/// readiness:
/// check_interval_secs: 5
/// timeout_secs: 3
/// resource_limits:
/// max_memory_mb: 256
/// max_cpu_percent: 80
/// max_file_descriptors: 1024
/// command_permissions:
/// allow_shutdown: false
/// allow_restart: true
/// allowed_signals:
/// - SIGTERM
/// environment:
/// - name: WORKER_MODE
/// value: queue
/// - name: API_TOKEN
/// secret_ref: ${API_TOKEN}
/// secrets:
/// - name: API_TOKEN
/// key: workers/api_token
/// required: true
/// ```
///
/// # Example
///
/// ```no_run
/// # async fn add_child_example() -> Result<(), rust_supervisor::error::types::SupervisorError> {
/// use rust_supervisor::control::command::CommandResult;
/// use rust_supervisor::id::types::SupervisorPath;
/// use rust_supervisor::runtime::supervisor::Supervisor;
/// use rust_supervisor::spec::supervisor::SupervisorSpec;
///
/// let handle = Supervisor::start(SupervisorSpec::root(Vec::new())).await?;
/// let result = handle
/// .add_child(
/// SupervisorPath::root(),
/// "name: worker\nkind: async_worker\n",
/// "operator",
/// "attach worker during runtime update",
/// )
/// .await?;
///
/// assert!(matches!(result, CommandResult::ChildAdded { .. }));
/// # Ok(())
/// # }
/// ```
///
/// # Returns
///
/// Returns a [`CommandResult`] after the runtime accepts the command.
pub async fn add_child(
&self,
target: SupervisorPath,
child_manifest: impl Into<String>,
requested_by: impl Into<String>,
reason: impl Into<String>,
) -> Result<CommandResult, SupervisorError> {
self.send(ControlCommand::AddChild {
meta: CommandMeta::new(requested_by, reason),
target,
child_manifest: child_manifest.into(),
})
.await
}
/// Removes a child from runtime governance.
///
/// # Arguments
///
/// - `child_id`: Target child identifier.
/// - `requested_by`: Caller that requested the command.
/// - `reason`: Human-readable command reason.
///
/// # Returns
///
/// Returns a [`CommandResult`] after removal or idempotent reuse.
pub async fn remove_child(
&self,
child_id: ChildId,
requested_by: impl Into<String>,
reason: impl Into<String>,
) -> Result<CommandResult, SupervisorError> {
self.child_command(child_id, requested_by, reason, |meta, child_id| {
ControlCommand::RemoveChild { meta, child_id }
})
.await
}
/// Restarts a child explicitly.
///
/// # Arguments
///
/// - `child_id`: Target child identifier.
/// - `requested_by`: Caller that requested the command.
/// - `reason`: Human-readable command reason.
///
/// # Returns
///
/// Returns a [`CommandResult`] after restart dispatch.
pub async fn restart_child(
&self,
child_id: ChildId,
requested_by: impl Into<String>,
reason: impl Into<String>,
) -> Result<CommandResult, SupervisorError> {
self.child_command(child_id, requested_by, reason, |meta, child_id| {
ControlCommand::RestartChild { meta, child_id }
})
.await
}
/// Pauses a child idempotently.
///
/// # Arguments
///
/// - `child_id`: Target child identifier.
/// - `requested_by`: Caller that requested the command.
/// - `reason`: Human-readable command reason.
///
/// # Returns
///
/// Returns the current child state after the command.
pub async fn pause_child(
&self,
child_id: ChildId,
requested_by: impl Into<String>,
reason: impl Into<String>,
) -> Result<CommandResult, SupervisorError> {
self.child_command(child_id, requested_by, reason, |meta, child_id| {
ControlCommand::PauseChild { meta, child_id }
})
.await
}
/// Resumes a child idempotently.
///
/// # Arguments
///
/// - `child_id`: Target child identifier.
/// - `requested_by`: Caller that requested the command.
/// - `reason`: Human-readable command reason.
///
/// # Returns
///
/// Returns the current child state after the command.
pub async fn resume_child(
&self,
child_id: ChildId,
requested_by: impl Into<String>,
reason: impl Into<String>,
) -> Result<CommandResult, SupervisorError> {
self.child_command(child_id, requested_by, reason, |meta, child_id| {
ControlCommand::ResumeChild { meta, child_id }
})
.await
}
/// Quarantines a child idempotently.
///
/// # Arguments
///
/// - `child_id`: Target child identifier.
/// - `requested_by`: Caller that requested the command.
/// - `reason`: Human-readable command reason.
///
/// # Returns
///
/// Returns the current child state after the command.
pub async fn quarantine_child(
&self,
child_id: ChildId,
requested_by: impl Into<String>,
reason: impl Into<String>,
) -> Result<CommandResult, SupervisorError> {
self.child_command(child_id, requested_by, reason, |meta, child_id| {
ControlCommand::QuarantineChild { meta, child_id }
})
.await
}
/// Shuts down the supervisor tree idempotently.
///
/// # Arguments
///
/// - `requested_by`: Caller that requested shutdown.
/// - `reason`: Human-readable shutdown reason.
///
/// # Returns
///
/// Returns the current shutdown result.
pub async fn shutdown_tree(
&self,
requested_by: impl Into<String>,
reason: impl Into<String>,
) -> Result<CommandResult, SupervisorError> {
self.send(ControlCommand::ShutdownTree {
meta: CommandMeta::new(requested_by, reason),
})
.await
}
/// Queries the current runtime state.
///
/// # Arguments
///
/// This function has no arguments.
///
/// # Returns
///
/// Returns a [`CommandResult::CurrentState`] value.
pub async fn current_state(&self) -> Result<CommandResult, SupervisorError> {
self.send(ControlCommand::CurrentState {
meta: CommandMeta::new("system", "current_state"),
})
.await
}
/// Reports whether the runtime control loop is alive.
///
/// # Arguments
///
/// This function has no arguments.
///
/// # Returns
///
/// Returns `true` when ordinary control commands may still be accepted.
pub fn is_alive(&self) -> bool {
self.control_plane.is_alive()
}
/// Returns a runtime control plane health report.
///
/// # Arguments
///
/// This function has no arguments.
///
/// # Returns
///
/// Returns a [`RuntimeHealthReport`] value for the current observation.
pub fn health(&self) -> RuntimeHealthReport {
self.control_plane.health()
}
/// Waits until the runtime control plane reaches a final state.
///
/// # Arguments
///
/// This function has no arguments.
///
/// # Returns
///
/// Returns the cached [`RuntimeExitReport`].
pub async fn join(&self) -> Result<RuntimeExitReport, SupervisorError> {
let report = self.control_plane.join().await;
let _ignored = self.event_sender.send(format!(
"runtime_control_loop_join_completed:{}:{}:{}",
report.state.as_str(),
report.phase,
report.reason
));
Ok(report)
}
/// Requests shutdown for the runtime control plane itself.
///
/// # Arguments
///
/// - `requested_by`: Caller that requested shutdown.
/// - `reason`: Human-readable shutdown reason.
///
/// # Returns
///
/// Returns the final [`RuntimeExitReport`].
pub async fn shutdown(
&self,
requested_by: impl Into<String>,
reason: impl Into<String>,
) -> Result<RuntimeExitReport, SupervisorError> {
let meta = CommandMeta::new(requested_by, reason);
if let Some(report) = self
.control_plane
.mark_shutdown_requested(meta.requested_by.clone(), meta.reason.clone())?
{
return Ok(report);
}
let (reply_sender, reply_receiver) = oneshot::channel();
if self
.command_sender
.send(RuntimeLoopMessage::ControlPlane(
ControlPlaneMessage::Shutdown { meta, reply_sender },
))
.await
.is_err()
{
return Err(self
.closed_runtime_error_after_join("runtime control loop is closed")
.await);
}
match reply_receiver.await {
Ok(result) => {
result?;
}
Err(_) => {
return Err(self
.closed_runtime_error_after_join("runtime control loop dropped shutdown reply")
.await);
}
}
self.join().await
}
/// Subscribes to runtime event text emitted by the control loop.
///
/// # Arguments
///
/// This function has no arguments.
///
/// # Returns
///
/// Returns a broadcast receiver for event text.
pub fn subscribe_events(&self) -> broadcast::Receiver<String> {
let receiver = self.event_sender.subscribe();
if self.control_plane.is_alive() {
let _ignored = self
.event_sender
.send("runtime_control_loop_started:startup".to_owned());
}
receiver
}
/// Returns a copy of the typed observability test recorder.
///
/// # Arguments
///
/// This function has no arguments.
///
/// # Returns
///
/// Returns the currently retained [`TestRecorder`] contents.
pub fn observability_recorder(&self) -> TestRecorder {
self.observability
.lock()
.map(|pipeline| pipeline.test_recorder.clone())
.unwrap_or_default()
}
/// Hidden integration-test hook that feeds a synthetic [`ChildRunReport`] through the mailbox.
///
/// Production callers must not rely on this hook.
#[doc(hidden)]
pub async fn generation_fencing_replay_child_exit_for_test(
&self,
report: ChildRunReport,
) -> Result<(), SupervisorError> {
if let Some(report_final) = self.control_plane.final_report() {
return Err(runtime_exit_error(&report_final));
}
if !self.control_plane.is_alive() {
return Err(SupervisorError::InvalidTransition {
message: format!(
"runtime control loop is not alive: state={}",
self.control_plane.health().state.as_str()
),
});
}
self.command_sender
.send(RuntimeLoopMessage::ControlPlane(
ControlPlaneMessage::ReplayChildExitForTest {
report: Box::new(report),
},
))
.await
.map_err(|_| SupervisorError::InvalidTransition {
message: "runtime control loop is closed".to_owned(),
})
}
/// Sends one control command and waits for the result.
///
/// # Arguments
///
/// - `command`: Command that should be executed by the runtime loop.
///
/// # Returns
///
/// Returns a command result or a supervisor error when the runtime is gone.
async fn send(&self, command: ControlCommand) -> Result<CommandResult, SupervisorError> {
if let Some(report) = self.control_plane.final_report() {
return Err(runtime_exit_error(&report));
}
if !self.control_plane.is_alive() {
return Err(SupervisorError::InvalidTransition {
message: format!(
"runtime control loop is not alive: state={}",
self.control_plane.health().state.as_str()
),
});
}
command.validate_audit_metadata()?;
let (reply_sender, reply_receiver) = oneshot::channel();
if self
.command_sender
.send(RuntimeLoopMessage::Control {
command,
reply_sender,
})
.await
.is_err()
{
return Err(self
.closed_runtime_error_after_join("runtime control loop is closed")
.await);
}
match reply_receiver.await {
Ok(result) => result,
Err(_) => Err(self
.closed_runtime_error_after_join("runtime control loop dropped command reply")
.await),
}
}
/// Builds and sends a child-targeted command.
///
/// # Arguments
///
/// - `child_id`: Target child identifier.
/// - `requested_by`: Caller that requested the command.
/// - `reason`: Human-readable command reason.
/// - `builder`: Command builder for the child operation.
///
/// # Returns
///
/// Returns a command result from the runtime loop.
async fn child_command<F>(
&self,
child_id: ChildId,
requested_by: impl Into<String>,
reason: impl Into<String>,
builder: F,
) -> Result<CommandResult, SupervisorError>
where
F: FnOnce(CommandMeta, ChildId) -> ControlCommand,
{
let meta = CommandMeta::new(requested_by, reason);
self.send(builder(meta, child_id)).await
}
/// Builds an error after waiting for the runtime exit report when possible.
async fn closed_runtime_error_after_join(&self, fallback: &str) -> SupervisorError {
if let Some(report) = self.control_plane.final_report() {
return runtime_exit_error(&report);
}
if self.command_sender.is_closed() {
let report = self.control_plane.join().await;
return runtime_exit_error(&report);
}
SupervisorError::InvalidTransition {
message: fallback.to_owned(),
}
}
}
/// Builds a control command error from a runtime exit report.
fn runtime_exit_error(report: &RuntimeExitReport) -> SupervisorError {
SupervisorError::InvalidTransition {
message: format!(
"runtime control loop already exited: state={}, phase={}, reason={}",
report.state.as_str(),
report.phase,
report.reason
),
}
}