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
//! Node supervision and lifecycle management
use crate::config::RestartPolicy;
use crate::health::{HealthChecker, HealthStatus};
use crate::node::NodeRunner;
use crate::shutdown::ShutdownHandle;
use anyhow::Result;
use mecha10_core::rwlock_collections::RwLockMapExt;
use std::sync::Arc;
use tokio::task::JoinHandle;
/// Status of a supervised node
#[derive(Clone, Debug, PartialEq)]
pub enum NodeStatus {
/// Node is starting up
Starting,
/// Node is running normally
Running,
/// Node is shutting down
ShuttingDown,
/// Node has stopped
Stopped,
/// Node failed with error
Failed { reason: String },
/// Node is restarting
Restarting { attempt: usize },
}
/// Handle to a supervised node
pub struct NodeHandle {
name: String,
task: JoinHandle<()>,
}
impl NodeHandle {
/// Get the node name
pub fn name(&self) -> &str {
&self.name
}
/// Check if the node task is finished
pub fn is_finished(&self) -> bool {
self.task.is_finished()
}
/// Abort the node task
pub fn abort(&self) {
self.task.abort();
}
/// Wait for the node to finish
pub async fn wait(self) -> Result<()> {
self.task.await?;
Ok(())
}
}
/// Supervisor for managing node lifecycle
pub struct Supervisor {
health_checker: Arc<HealthChecker>,
shutdown: ShutdownHandle,
restart_policy: RestartPolicy,
/// Tracked node handles by name
nodes: Arc<tokio::sync::RwLock<std::collections::HashMap<String, NodeHandle>>>,
}
impl Supervisor {
/// Create a new supervisor
pub fn new(health_checker: Arc<HealthChecker>, shutdown: ShutdownHandle, restart_policy: RestartPolicy) -> Self {
Self {
health_checker,
shutdown,
restart_policy,
nodes: Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new())),
}
}
/// Launch and supervise a node
pub fn launch_node(&self, mut node: Box<dyn NodeRunner>) -> NodeHandle {
let name = node.name().to_string();
let health_checker = self.health_checker.clone();
let shutdown = self.shutdown.clone();
let restart_policy = self.restart_policy.clone();
tracing::info!("Launching node: {}", name);
let task = tokio::spawn(async move {
let node_name = node.name().to_string();
let mut attempt = 0;
health_checker.register(node_name.clone(), HealthStatus::Healthy).await;
loop {
tracing::debug!("Starting node: {} (attempt {})", node_name, attempt);
let mut shutdown_rx = shutdown.subscribe();
let run_future = node.run();
tokio::select! {
result = run_future => {
match result {
Ok(()) => {
tracing::info!("Node {} completed successfully", node_name);
health_checker
.update(&node_name, HealthStatus::Healthy)
.await;
break;
}
Err(e) => {
tracing::error!("Node {} failed: {}", node_name, e);
health_checker
.update(
&node_name,
HealthStatus::Unhealthy {
reason: e.to_string(),
},
)
.await;
if restart_policy.should_restart(attempt) {
let backoff = restart_policy.backoff_duration(attempt);
tracing::info!(
"Restarting node {} in {:?} (attempt {})",
node_name,
backoff,
attempt + 1
);
tokio::time::sleep(backoff).await;
attempt += 1;
continue;
} else {
tracing::error!(
"Node {} exhausted restart attempts, giving up",
node_name
);
break;
}
}
}
}
_ = shutdown_rx.recv() => {
tracing::info!("Shutdown signal received, stopping node: {}", node_name);
if let Err(e) = node.shutdown().await {
tracing::error!("Error during node {} shutdown: {}", node_name, e);
}
health_checker
.update(&node_name, HealthStatus::Healthy)
.await;
break;
}
}
}
health_checker.unregister(&node_name).await;
tracing::debug!("Node {} supervision ended", node_name);
});
NodeHandle { name, task }
}
// duplicate: false positive — matches `ThroughputTracker::get_all_stats`
// (packages/core/src/profiling.rs) on AST shape only (map each item through a per-item
// method, collect); unrelated domains (spawning node supervision tasks vs computing
// per-topic throughput stats), nothing to share beyond the `map`/`collect` idiom itself.
/// Launch multiple nodes
pub fn launch_nodes(&self, nodes: Vec<Box<dyn NodeRunner>>) -> Vec<NodeHandle> {
nodes.into_iter().map(|node| self.launch_node(node)).collect()
}
/// Get the health checker
pub fn health_checker(&self) -> &Arc<HealthChecker> {
&self.health_checker
}
/// Get the shutdown handle
pub fn shutdown(&self) -> &ShutdownHandle {
&self.shutdown
}
/// Start a node by name (for lifecycle management)
///
/// Note: This is a stub implementation for the lifecycle system.
/// Full implementation requires node registry or factory pattern.
///
/// # Arguments
///
/// * `name` - Name of the node to start
///
/// # Errors
///
/// Returns error if node cannot be found or started
#[allow(dead_code)]
pub async fn start_node(&self, name: &str) -> Result<()> {
tracing::info!("Starting node: {}", name);
// TODO: Implement node registry/factory to create nodes by name
self.health_checker
.register(name.to_string(), HealthStatus::Healthy)
.await;
tracing::debug!("Node {} registered (stub)", name);
Ok(())
}
/// Stop a node by name (for lifecycle management)
///
/// # Arguments
///
/// * `name` - Name of the node to stop
///
/// # Errors
///
/// Returns error if node cannot be found or stopped
#[allow(dead_code)]
pub async fn stop_node(&self, name: &str) -> Result<()> {
tracing::info!("Stopping node: {}", name);
let mut nodes = self.nodes.write().await;
if let Some(handle) = nodes.remove(name) {
handle.abort();
self.health_checker.unregister(name).await;
tracing::info!("Node {} stopped", name);
Ok(())
} else {
self.health_checker.unregister(name).await;
tracing::warn!(
"Node {} not found in tracked nodes, unregistered from health checker",
name
);
Ok(())
}
}
/// Get list of currently running nodes
///
/// Returns the names of all nodes being supervised
#[allow(dead_code)]
pub async fn get_running_nodes(&self) -> Vec<String> {
self.nodes.cloned_keys().await
}
}
/// Implement the SupervisorTrait for Supervisor
#[async_trait::async_trait]
impl crate::lifecycle::SupervisorTrait for Supervisor {
async fn start_node(&self, name: &str) -> Result<()> {
self.start_node(name).await
}
async fn stop_node(&self, name: &str) -> Result<()> {
self.stop_node(name).await
}
fn get_running_nodes(&self) -> Vec<String> {
vec![]
}
}