mecha10-core 0.8.0

Mecha10 core runtime and foundational types
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
//! Mecha10 Core Runtime
//!
//! This crate provides the foundational runtime for the Mecha10 framework,
//! including node lifecycle management, health monitoring, and orchestration.
//!
//! # Features
//!
//! - Node lifecycle management (start, stop, restart)
//! - Health monitoring and automatic recovery
//! - Process management for node execution
//! - Integration with config and messaging systems
//! - Graceful shutdown handling
//! - Type-safe topics system
//! - Comprehensive error handling
//! - Shared message types
//!
//! # Quick Start
//!
//! ```rust
//! use mecha10_core::prelude::*;
//! use mecha10_core::topics::{perception, sensor};
//!
//! #[derive(Debug)]
//! struct MyNode {
//!     config: MyConfig,
//! }
//!
//! #[derive(Debug, Deserialize)]
//! struct MyConfig {
//!     threshold: f32,
//! }
//!
//! #[async_trait]
//! impl NodeImpl for MyNode {
//!     type Config = MyConfig;
//!
//!     async fn init(config: Self::Config) -> Result<Self> {
//!         Ok(Self { config })
//!     }
//!
//!     async fn run(&mut self, ctx: &Context) -> Result<()> {
//!         let mut images = ctx.subscribe(sensor::CAMERA_RGB).await?;
//!
//!         while let Some(image) = images.recv().await {
//!             // Process image into detections, then publish the result.
//!             let result = Vec::new();
//!             ctx.publish_to(perception::DETECTIONS, &result).await?;
//!         }
//!
//!         Ok(())
//!     }
//! }
//! ```

pub mod types;

pub mod wire_identifier;

pub mod messages;

pub mod sensor;

pub mod actuator;

pub mod teleop;

pub mod topics;

pub mod topic_utils;

pub mod error;

pub mod fs_utils;

pub mod rwlock_collections;

pub mod context;

#[cfg(feature = "messaging")]
pub mod stream;

#[cfg(feature = "messaging")]
pub mod publish;

pub mod node;

pub mod node_registry;

pub mod config;

pub mod config_watcher;

pub mod model;

pub mod macros;

#[cfg(feature = "messaging")]
pub mod rpc;

#[cfg(feature = "messaging")]
pub mod rpc_breaker;

#[cfg(feature = "messaging")]
pub mod rpc_streaming;

pub mod discovery;

pub mod schema;

pub mod auth;

mod redis_list_util;

pub mod secrets;

#[cfg(feature = "messaging")]
pub mod health;

#[cfg(feature = "messaging")]
pub mod log_publisher;

pub mod metrics;

pub mod rate_limit;

pub mod circuit_breaker;

#[cfg(feature = "messaging")]
pub mod dead_letter;

#[cfg(feature = "schema-validation")]
pub mod schema_validation;

#[cfg(feature = "hal-compat")]
pub mod hal_compat;

pub mod dependency;

pub mod kinematics;

pub mod geometry;

#[cfg(feature = "messaging")]
pub mod lifecycle;

pub mod topic_registry;

pub mod state;

pub mod recovery;

#[cfg(feature = "messaging")]
pub mod tracing_otel;

pub mod profiling;

pub mod priority_queue;

pub mod service;
#[cfg(feature = "messaging")]
pub mod service_manager;

pub mod aggregated;

#[cfg(feature = "messaging")]
pub mod recorder;

#[cfg(feature = "messaging")]
pub mod redis_bridge;

#[cfg(feature = "messaging")]
pub mod behavior_interrupt;

#[cfg(feature = "messaging")]
pub mod command_relay;

pub mod relay_topics;

pub mod node_config_base;

pub mod ollama;

pub mod prelude;

pub use context::{Context, Receiver};
pub use error::{Mecha10Error, Result};
pub use messages::Message;
pub use types::*;

// Re-exported so `register_node!`'s `$crate::inventory::submit!` resolves from any crate that
// invokes it (`$crate` in a `#[macro_export]` macro always points back at this crate, regardless
// of where the macro is called from).
pub use inventory;

use std::collections::HashMap;
use std::process::Stdio;
use std::sync::Arc;
use thiserror::Error;
use tokio::process::Child;
use tokio::sync::RwLock;
use tokio::time::{interval, Duration};

use crate::rwlock_collections::RwLockMapExt;

#[derive(Debug, Error)]
pub enum RuntimeError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("Node error: {0}")]
    Node(String),

    #[error("Configuration error: {0}")]
    Config(String),

    #[error("Process error: {0}")]
    Process(String),

    #[error("Health check failed: {0}")]
    HealthCheck(String),
}

pub type RuntimeResult<T> = std::result::Result<T, RuntimeError>;

struct ManagedNode {
    config: NodeConfig,
    state: NodeState,
    process: Option<Child>,
    restart_count: u32,
    last_health_check: std::time::Instant,
}

impl ManagedNode {
    fn new(config: NodeConfig) -> Self {
        Self {
            config,
            state: NodeState::Stopped,
            process: None,
            restart_count: 0,
            last_health_check: std::time::Instant::now(),
        }
    }

    async fn start(&mut self) -> RuntimeResult<()> {
        if self.state == NodeState::Running {
            return Ok(());
        }

        self.state = NodeState::Starting;

        let mut cmd = tokio::process::Command::new(&self.config.executable);
        cmd.args(&self.config.args);
        cmd.envs(&self.config.env);
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        let child = cmd
            .spawn()
            .map_err(|e| RuntimeError::Process(format!("Failed to spawn {}: {}", self.config.id, e)))?;

        self.process = Some(child);
        self.state = NodeState::Running;

        tracing::info!("Started node: {}", self.config.id);

        Ok(())
    }

    async fn stop(&mut self) -> RuntimeResult<()> {
        if let Some(mut child) = self.process.take() {
            self.state = NodeState::Stopping;

            #[cfg(unix)]
            {
                use nix::sys::signal::{self, Signal};
                use nix::unistd::Pid;

                if let Some(pid) = child.id() {
                    let _ = signal::kill(Pid::from_raw(pid as i32), Signal::SIGTERM);
                }
            }

            match tokio::time::timeout(Duration::from_secs(5), child.wait()).await {
                Ok(Ok(status)) => {
                    tracing::info!("Node {} stopped: {:?}", self.config.id, status);
                }
                Ok(Err(e)) => {
                    tracing::error!("Error waiting for node {}: {}", self.config.id, e);
                }
                Err(_) => {
                    tracing::warn!("Node {} did not stop gracefully, killing", self.config.id);
                    let _ = child.kill().await;
                }
            }

            self.state = NodeState::Stopped;
        }

        Ok(())
    }

    async fn check_health(&mut self) -> RuntimeResult<bool> {
        if let Some(child) = &mut self.process {
            match child.try_wait() {
                Ok(Some(status)) => {
                    tracing::warn!("Node {} exited: {:?}", self.config.id, status);
                    self.state = NodeState::Crashed;
                    self.process = None;
                    return Ok(false);
                }
                Ok(None) => {
                    self.last_health_check = std::time::Instant::now();
                    return Ok(true);
                }
                Err(e) => {
                    tracing::error!("Error checking node {}: {}", self.config.id, e);
                    self.state = NodeState::Unhealthy;
                    return Ok(false);
                }
            }
        }

        Ok(false)
    }

    fn should_restart(&self) -> bool {
        self.config.auto_restart
            && (self.state == NodeState::Crashed || self.state == NodeState::Unhealthy)
            && self.restart_count < 3
    }
}

pub struct Runtime {
    #[allow(dead_code)]
    robot_id: String,

    nodes: Arc<RwLock<HashMap<String, ManagedNode>>>,

    running: Arc<RwLock<bool>>,
}

impl Runtime {
    /// Create a new runtime instance
    pub async fn new(robot_id: &str) -> RuntimeResult<Self> {
        Ok(Self {
            robot_id: robot_id.to_string(),
            nodes: Arc::new(RwLock::new(HashMap::new())),
            running: Arc::new(RwLock::new(false)),
        })
    }

    /// Start a node
    pub async fn start_node(&mut self, config: NodeConfig) -> RuntimeResult<()> {
        let node_id = config.id.clone();

        let mut nodes = self.nodes.write().await;

        if nodes.contains_key(&node_id) {
            return Err(RuntimeError::Node(format!("Node {} already exists", node_id)));
        }

        let mut node = ManagedNode::new(config);
        node.start().await?;

        nodes.insert(node_id, node);

        Ok(())
    }

    /// Stop a node
    pub async fn stop_node(&mut self, node_id: &str) -> RuntimeResult<()> {
        let mut nodes = self.nodes.write().await;

        if let Some(node) = nodes.get_mut(node_id) {
            node.stop().await?;
            nodes.remove(node_id);
            Ok(())
        } else {
            Err(RuntimeError::Node(format!("Node {} not found", node_id)))
        }
    }

    /// Get node state
    pub async fn node_state(&self, node_id: &str) -> Option<NodeState> {
        let nodes = self.nodes.read().await;
        nodes.get(node_id).map(|n| n.state.clone())
    }

    /// List all nodes
    pub async fn list_nodes(&self) -> Vec<String> {
        self.nodes.cloned_keys().await
    }

    /// Run the runtime (blocks until shutdown)
    pub async fn run(&mut self) -> RuntimeResult<()> {
        *self.running.write().await = true;

        let nodes = Arc::clone(&self.nodes);
        let running = Arc::clone(&self.running);

        let health_check_task = tokio::spawn(async move {
            let mut interval = interval(Duration::from_secs(5));

            while *running.read().await {
                interval.tick().await;

                let mut nodes = nodes.write().await;
                let node_ids: Vec<String> = nodes.keys().cloned().collect();

                for node_id in node_ids {
                    if let Some(node) = nodes.get_mut(&node_id) {
                        if node.state == NodeState::Running {
                            match node.check_health().await {
                                Ok(true) => {}
                                Ok(false) => {
                                    if node.should_restart() {
                                        tracing::info!("Auto-restarting node: {}", node_id);
                                        let _ = node.start().await;
                                        node.restart_count += 1;
                                    }
                                }
                                Err(e) => {
                                    tracing::error!("Health check error for {}: {}", node_id, e);
                                }
                            }
                        }
                    }
                }
            }
        });

        tokio::signal::ctrl_c()
            .await
            .map_err(|e| RuntimeError::Process(format!("Error waiting for shutdown: {}", e)))?;

        tracing::info!("Shutting down runtime...");
        *self.running.write().await = false;

        health_check_task.abort();

        let mut nodes = self.nodes.write().await;
        for (node_id, node) in nodes.iter_mut() {
            tracing::info!("Stopping node: {}", node_id);
            let _ = node.stop().await;
        }

        Ok(())
    }

    /// Shutdown the runtime gracefully
    pub async fn shutdown(&mut self) -> RuntimeResult<()> {
        *self.running.write().await = false;

        let mut nodes = self.nodes.write().await;
        for (node_id, node) in nodes.iter_mut() {
            tracing::info!("Stopping node: {}", node_id);
            let _ = node.stop().await;
        }

        Ok(())
    }
}