mecha10-core 0.6.2

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
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
// Mecha10 Node Trait and Lifecycle Management
//
// This module defines the core Node trait and lifecycle management for Mecha10 nodes.
// Every Mecha10 node implements the NodeImpl trait to define its behavior.

use crate::{Context, HealthStatus, NodeState, Result};
use async_trait::async_trait;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tracing::{debug, error, info, warn};

// ============================================================================
// Health Priority
// ============================================================================

/// Node health reporting priority
///
/// Determines heartbeat frequency and timeout thresholds based on
/// node criticality. Safety-critical nodes report more frequently.
///
/// # Priority Levels
///
/// | Priority | Interval | TTL | Timeout | Use Case |
/// |----------|----------|-----|---------|----------|
/// | Critical | 1s | 5s | 3s | motor-controller, estop |
/// | Normal | 5s | 60s | 15s | sensors, AI nodes |
/// | Background | 30s | 120s | 90s | logging, diagnostics |
///
/// # Example
///
/// ```rust
/// use mecha10::prelude::*;
///
/// // Create config with critical priority
/// let config = HealthReportingConfig::critical();
///
/// // Or specify priority explicitly
/// let config = HealthReportingConfig {
///     priority: HealthPriority::Critical,
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HealthPriority {
    /// Safety-critical nodes that require immediate failure detection.
    ///
    /// Examples: motor-controller, estop, safety-monitor
    ///
    /// - Interval: 1 second
    /// - TTL: 5 seconds
    /// - Timeout: 3 seconds
    Critical,

    /// Standard operational nodes (default).
    ///
    /// Examples: camera, sensors, mujoco-sim
    ///
    /// - Interval: 5 seconds
    /// - TTL: 60 seconds
    /// - Timeout: 15 seconds
    #[default]
    Normal,

    /// Background/auxiliary nodes where delayed detection is acceptable.
    ///
    /// Examples: logging, telemetry, diagnostics
    ///
    /// - Interval: 30 seconds
    /// - TTL: 120 seconds
    /// - Timeout: 90 seconds
    Background,
}

impl HealthPriority {
    /// Get the heartbeat interval for this priority level
    pub const fn interval(&self) -> Duration {
        match self {
            Self::Critical => Duration::from_secs(1),
            Self::Normal => Duration::from_secs(5),
            Self::Background => Duration::from_secs(30),
        }
    }

    /// Get the Redis TTL (time-to-live) in seconds for this priority level
    ///
    /// The TTL should be longer than the interval to allow for some jitter,
    /// but short enough that stale data expires quickly.
    pub const fn ttl_seconds(&self) -> u64 {
        match self {
            Self::Critical => 5,
            Self::Normal => 60,
            Self::Background => 120,
        }
    }

    /// Get the timeout threshold for monitoring
    ///
    /// A node is considered unresponsive if no health report is received
    /// within this duration.
    pub const fn timeout(&self) -> Duration {
        match self {
            Self::Critical => Duration::from_secs(3),
            Self::Normal => Duration::from_secs(15),
            Self::Background => Duration::from_secs(90),
        }
    }

    /// Get the timeout in microseconds (for comparison with timestamps)
    pub const fn timeout_micros(&self) -> u64 {
        match self {
            Self::Critical => 3_000_000,
            Self::Normal => 15_000_000,
            Self::Background => 90_000_000,
        }
    }
}

impl std::fmt::Display for HealthPriority {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Critical => write!(f, "critical"),
            Self::Normal => write!(f, "normal"),
            Self::Background => write!(f, "background"),
        }
    }
}

// ============================================================================
// Configuration
// ============================================================================

/// Configuration for node health reporting
///
/// # Example
///
/// ```rust
/// use mecha10::prelude::*;
///
/// // Default config (Normal priority, 5s interval)
/// let config = HealthReportingConfig::default();
///
/// // Critical priority (1s interval)
/// let config = HealthReportingConfig::critical();
///
/// // Background priority (30s interval)
/// let config = HealthReportingConfig::background();
///
/// // Custom config
/// let config = HealthReportingConfig {
///     enabled: true,
///     priority: HealthPriority::Normal,
///     store_history: false, // Disable history for high-frequency nodes
/// };
/// ```
#[derive(Debug, Clone)]
pub struct HealthReportingConfig {
    /// Whether health reporting is enabled (default: true)
    pub enabled: bool,

    /// Priority level determines interval and timeout (default: Normal)
    pub priority: HealthPriority,

    /// Whether to store health history in Redis (default: true)
    ///
    /// Disable for high-frequency critical nodes to reduce Redis load.
    /// History is stored as a sorted set with 24-hour retention.
    pub store_history: bool,
}

impl Default for HealthReportingConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            priority: HealthPriority::Normal,
            store_history: true,
        }
    }
}

impl HealthReportingConfig {
    /// Create config for critical priority nodes (1s interval)
    pub fn critical() -> Self {
        Self {
            enabled: true,
            priority: HealthPriority::Critical,
            store_history: false, // Disable history for critical nodes to reduce load
        }
    }

    /// Create config for normal priority nodes (5s interval)
    pub fn normal() -> Self {
        Self::default()
    }

    /// Create config for background priority nodes (30s interval)
    pub fn background() -> Self {
        Self {
            enabled: true,
            priority: HealthPriority::Background,
            store_history: true,
        }
    }

    /// Get the effective interval based on priority
    pub fn interval(&self) -> Duration {
        self.priority.interval()
    }

    /// Get the effective TTL based on priority
    pub fn ttl_seconds(&self) -> u64 {
        self.priority.ttl_seconds()
    }
}

/// Trait for node configurations that specify an update rate
///
/// This trait provides a standard interface for nodes that publish at a fixed rate.
/// Implement this trait on your node's config struct to enable convenient rate-based
/// interval creation.
///
/// # Example
///
/// ```rust
/// use mecha10::prelude::*;
///
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// pub struct CameraConfig {
///     pub fps: f32,
///     pub width: u32,
///     pub height: u32,
/// }
///
/// impl RateConfig for CameraConfig {
///     fn rate_hz(&self) -> f32 {
///         self.fps
///     }
/// }
///
/// // Now you can use the config to create intervals easily:
/// # async fn example(config: CameraConfig) {
/// let mut interval = config.create_interval();
/// loop {
///     interval.tick().await;
///     // Publish at configured rate
/// }
/// # }
/// ```
pub trait RateConfig {
    /// Get the update rate in Hertz (cycles per second)
    fn rate_hz(&self) -> f32;

    /// Create a tokio interval from the configured rate
    ///
    /// This is a convenience method that converts the rate to a Duration
    /// and creates a tokio::time::Interval.
    fn create_interval(&self) -> tokio::time::Interval {
        let duration = Duration::from_secs_f32(1.0 / self.rate_hz());
        tokio::time::interval(duration)
    }

    /// Get the period (time between updates) as a Duration
    fn period(&self) -> Duration {
        Duration::from_secs_f32(1.0 / self.rate_hz())
    }
}

// ============================================================================
// Health Status Helper
// ============================================================================

/// Helper methods for creating HealthStatus instances
pub trait HealthStatusExt {
    /// Create a healthy status
    fn healthy(message: impl Into<String>) -> Self;
    /// Create an unhealthy status
    fn unhealthy(message: impl Into<String>) -> Self;
}

impl HealthStatusExt for HealthStatus {
    fn healthy(message: impl Into<String>) -> Self {
        Self {
            healthy: true,
            last_check: crate::prelude::now_micros(),
            failure_count: 0,
            message: Some(message.into()),
        }
    }

    fn unhealthy(message: impl Into<String>) -> Self {
        Self {
            healthy: false,
            last_check: crate::prelude::now_micros(),
            failure_count: 1,
            message: Some(message.into()),
        }
    }
}

// ============================================================================
// NodeImpl Trait
// ============================================================================

/// Core trait that all Mecha10 nodes must implement.
///
/// This trait defines the lifecycle of a node:
/// 1. `init()` - Initialize the node with configuration
/// 2. `run()` - Main execution loop
/// 3. `shutdown()` - Graceful shutdown
/// 4. `health_check()` - Report health status
///
/// # Example
///
/// ```rust
/// use mecha10::prelude::*;
///
/// #[derive(Debug)]
/// struct MyNode {
///     config: MyConfig,
/// }
///
/// #[derive(Debug, Deserialize)]
/// struct MyConfig {
///     rate: f32,
/// }
///
/// #[async_trait]
/// impl NodeImpl for MyNode {
///     type Config = MyConfig;
///
///     async fn init(config: Self::Config) -> Result<Self> {
///         info!("Initializing node with rate: {}", config.rate);
///         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
///             info!("Received image: {}x{}", image.width, image.height);
///         }
///
///         Ok(())
///     }
/// }
/// ```
#[async_trait]
pub trait NodeImpl: Send + Sync + Debug + 'static {
    /// Configuration type for this node
    type Config: DeserializeOwned + Send + Sync + Debug;

    /// Initialize the node with the given configuration.
    ///
    /// This is called once when the node starts. Use this to:
    /// - Load configuration
    /// - Initialize resources (models, connections, etc.)
    /// - Validate prerequisites
    ///
    /// # Errors
    ///
    /// Return an error if initialization fails. The node will not start.
    async fn init(config: Self::Config) -> Result<Self>
    where
        Self: Sized;

    /// Main execution loop for the node.
    ///
    /// This is where your node's business logic lives. Typical patterns:
    /// - Subscribe to topics and process messages
    /// - Run periodic tasks
    /// - Publish results
    ///
    /// This method should run indefinitely until:
    /// - The context is cancelled (shutdown requested)
    /// - An unrecoverable error occurs
    ///
    /// # Errors
    ///
    /// Return an error if the node encounters an unrecoverable error.
    /// The node will transition to Error state and shutdown.
    async fn run(&mut self, ctx: &Context) -> Result<()>;

    /// Graceful shutdown hook.
    ///
    /// Called when the node is shutting down. Use this to:
    /// - Close connections
    /// - Flush buffers
    /// - Save state
    /// - Release resources
    ///
    /// The default implementation does nothing.
    ///
    /// # Errors
    ///
    /// Errors during shutdown are logged but don't prevent shutdown.
    async fn shutdown(&mut self) -> Result<()> {
        Ok(())
    }

    /// Health check for monitoring.
    ///
    /// Called periodically to check node health. Use this to:
    /// - Report current state
    /// - Check resource usage
    /// - Validate connections
    ///
    /// The default implementation returns healthy status.
    async fn health_check(&self) -> HealthStatus {
        HealthStatus {
            healthy: true,
            last_check: crate::prelude::now_micros(),
            failure_count: 0,
            message: Some("Node is running".to_string()),
        }
    }
}

// ============================================================================
// Node Runner
// ============================================================================

/// Wrapper that manages the lifecycle of a NodeImpl.
///
/// This provides:
/// - State management
/// - Lifecycle orchestration
/// - Error handling
/// - Health monitoring
#[derive(Clone)]
pub struct Node<T: NodeImpl> {
    node: Arc<Mutex<T>>,
    state: Arc<Mutex<NodeState>>,
}

impl<T: NodeImpl> Node<T> {
    /// Create a new node from a configuration.
    ///
    /// This calls `NodeImpl::init()` and wraps the result in a Node.
    ///
    /// # Errors
    ///
    /// Returns an error if initialization fails.
    pub async fn from_config(config: T::Config) -> Result<Self> {
        info!("Initializing node");

        let node = T::init(config).await?;

        Ok(Self {
            node: Arc::new(Mutex::new(node)),
            state: Arc::new(Mutex::new(NodeState::Starting)),
        })
    }

    /// Start the node with the given context.
    ///
    /// This orchestrates the full lifecycle:
    /// 1. Transition to Running state
    /// 2. Call `run()`
    /// 3. Call `shutdown()` on completion or error
    /// 4. Transition to final state
    ///
    /// # Errors
    ///
    /// Returns an error if the node fails during execution.
    pub async fn start(&self, ctx: Context) -> Result<()> {
        // Transition to running
        {
            let mut state = self.state.lock().await;
            *state = NodeState::Running;
            info!("Node transitioned to Running state");
        }

        // Run the node
        let result = {
            let mut node = self.node.lock().await;
            debug!("Starting node execution");
            node.run(&ctx).await
        };

        // Handle result
        match result {
            Ok(()) => {
                info!("Node completed successfully");
                self.shutdown().await?;
            }
            Err(e) => {
                error!("Node failed with error: {}", e);
                {
                    let mut state = self.state.lock().await;
                    *state = NodeState::Crashed;
                }
                self.shutdown().await?;
                return Err(e);
            }
        }

        Ok(())
    }

    /// Gracefully shutdown the node.
    ///
    /// This calls `shutdown()` and transitions to Stopped state.
    pub async fn shutdown(&self) -> Result<()> {
        info!("Shutting down node");

        // Transition to shutting down
        {
            let mut state = self.state.lock().await;
            *state = NodeState::Stopping;
        }

        // Call shutdown hook
        let result = {
            let mut node = self.node.lock().await;
            node.shutdown().await
        };

        // Transition to stopped
        {
            let mut state = self.state.lock().await;
            *state = NodeState::Stopped;
            info!("Node stopped");
        }

        if let Err(e) = result {
            warn!("Error during shutdown: {}", e);
            return Err(e);
        }

        Ok(())
    }

    /// Get the current state of the node.
    pub async fn state(&self) -> NodeState {
        self.state.lock().await.clone()
    }

    /// Perform a health check on the node.
    pub async fn health_check(&self) -> HealthStatus {
        let node = self.node.lock().await;
        node.health_check().await
    }

    /// Check if the node is healthy.
    pub async fn is_healthy(&self) -> bool {
        matches!(self.state().await, NodeState::Running | NodeState::Starting)
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Run a node with the given configuration and context.
///
/// This is a convenience function that:
/// 1. Initializes the node from config
/// 2. Starts the node with the context
/// 3. Handles errors
///
/// # Arguments
///
/// * `config` - Node-specific configuration
/// * `ctx` - Execution context
/// * `health_config` - Health reporting configuration
///
/// # Example
///
/// ```rust
/// use mecha10::prelude::*;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///     let config = MyConfig { rate: 10.0 };
///     let ctx = Context::new("my_node");
///
///     // Use default health reporting (Normal priority, 5s interval)
///     run_node::<MyNode>(config, ctx, HealthReportingConfig::default()).await?;
///
///     // Critical priority for safety-critical nodes (1s interval)
///     run_node::<MyNode>(config, ctx, HealthReportingConfig::critical()).await?;
///
///     // Background priority for auxiliary nodes (30s interval)
///     run_node::<MyNode>(config, ctx, HealthReportingConfig::background()).await?;
///
///     Ok(())
/// }
/// ```
pub async fn run_node<T: NodeImpl>(
    config: T::Config,
    ctx: Context,
    health_config: HealthReportingConfig,
) -> Result<()> {
    // Initialize logging (safe to call multiple times)
    crate::prelude::init_logging();

    let node = Node::<T>::from_config(config).await?;

    // Start automatic health reporting (requires messaging feature)
    #[cfg(feature = "messaging")]
    {
        if health_config.enabled {
            // Create clones for the health reporting task
            let node_for_health = node.node.clone();
            let ctx_for_health = ctx.clone();
            let priority = health_config.priority;
            let report_interval = health_config.interval();
            let ttl_seconds = health_config.ttl_seconds();
            let store_history = health_config.store_history;

            tokio::spawn(async move {
                use crate::health::HealthReporter;

                // Try to create health reporter with priority config
                let reporter =
                    match HealthReporter::with_config(&ctx_for_health, priority, ttl_seconds, store_history).await {
                        Ok(r) => r,
                        Err(e) => {
                            warn!("Health reporting disabled: {}", e);
                            return;
                        }
                    };

                info!(
                    "Health reporting enabled: priority={}, interval={:?}, ttl={}s, history={}",
                    priority, report_interval, ttl_seconds, store_history
                );

                let mut interval = tokio::time::interval(report_interval);
                info!("Health reporting loop starting");

                loop {
                    interval.tick().await;
                    debug!("Health tick - checking node health");

                    // Try to get health status from node without blocking
                    // If the node is busy (lock held by run()), report as healthy but busy
                    let msg_status = match node_for_health.try_lock() {
                        Ok(node) => {
                            let status = node.health_check().await;
                            crate::messages::system::HealthStatus {
                                timestamp: status.last_check,
                                level: if status.healthy {
                                    crate::messages::system::HealthLevel::Ok
                                } else {
                                    crate::messages::system::HealthLevel::Error
                                },
                                message: status.message.unwrap_or_else(|| "No message".to_string()),
                                diagnostics: None,
                            }
                        }
                        Err(_) => {
                            // Node is busy (lock held by run()) - report as healthy
                            // This is normal for long-running nodes
                            debug!("Node busy, reporting as healthy");
                            crate::messages::system::HealthStatus {
                                timestamp: crate::prelude::now_micros(),
                                level: crate::messages::system::HealthLevel::Ok,
                                message: "Node running (busy)".to_string(),
                                diagnostics: None,
                            }
                        }
                    };

                    // Report to centralized monitoring
                    if let Err(e) = reporter.report(msg_status).await {
                        warn!("Failed to report health: {}", e);
                    } else {
                        tracing::trace!("Health report sent successfully");
                    }
                }
            });
        } else {
            info!("Health reporting disabled");
        }
    }
    #[cfg(not(feature = "messaging"))]
    let _ = &health_config;

    node.start(ctx).await
}