1use crate::{Context, HealthStatus, NodeState, Result};
2use async_trait::async_trait;
3use schemars::JsonSchema;
4use serde::de::DeserializeOwned;
5use serde::{Deserialize, Serialize};
6use std::fmt::Debug;
7use std::sync::Arc;
8use std::time::Duration;
9use tokio::sync::Mutex;
10use tracing::{debug, error, info, warn};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14pub enum HealthPriority {
15 Critical,
16
17 #[default]
18 Normal,
19
20 Background,
21}
22
23impl HealthPriority {
24 const fn profile(&self) -> (Duration, u64, Duration) {
30 match self {
31 Self::Critical => (Duration::from_secs(1), 5, Duration::from_secs(3)),
32 Self::Normal => (Duration::from_secs(5), 60, Duration::from_secs(15)),
33 Self::Background => (Duration::from_secs(30), 120, Duration::from_secs(90)),
34 }
35 }
36
37 pub const fn interval(&self) -> Duration {
39 self.profile().0
40 }
41
42 pub const fn ttl_seconds(&self) -> u64 {
47 self.profile().1
48 }
49
50 pub const fn timeout(&self) -> Duration {
55 self.profile().2
56 }
57
58 pub const fn timeout_micros(&self) -> u64 {
60 self.timeout().as_micros() as u64
61 }
62}
63
64impl std::fmt::Display for HealthPriority {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 match self {
67 Self::Critical => write!(f, "critical"),
68 Self::Normal => write!(f, "normal"),
69 Self::Background => write!(f, "background"),
70 }
71 }
72}
73
74#[derive(Debug, Clone)]
75pub struct HealthReportingConfig {
76 pub enabled: bool,
77
78 pub priority: HealthPriority,
79
80 pub store_history: bool,
81}
82
83impl Default for HealthReportingConfig {
84 fn default() -> Self {
85 Self {
86 enabled: true,
87 priority: HealthPriority::Normal,
88 store_history: true,
89 }
90 }
91}
92
93impl HealthReportingConfig {
94 fn with_priority(priority: HealthPriority, store_history: bool) -> Self {
97 Self {
98 enabled: true,
99 priority,
100 store_history,
101 }
102 }
103
104 pub fn critical() -> Self {
106 Self::with_priority(HealthPriority::Critical, false)
107 }
108
109 pub fn normal() -> Self {
111 Self::default()
112 }
113
114 pub fn background() -> Self {
116 Self::with_priority(HealthPriority::Background, true)
117 }
118
119 pub fn interval(&self) -> Duration {
121 self.priority.interval()
122 }
123
124 pub fn ttl_seconds(&self) -> u64 {
126 self.priority.ttl_seconds()
127 }
128}
129
130pub trait RateConfig {
131 fn rate_hz(&self) -> f32;
133
134 fn create_interval(&self) -> tokio::time::Interval {
139 let duration = Duration::from_secs_f32(1.0 / self.rate_hz());
140 tokio::time::interval(duration)
141 }
142
143 fn period(&self) -> Duration {
145 Duration::from_secs_f32(1.0 / self.rate_hz())
146 }
147}
148
149pub trait HealthStatusExt {
150 fn healthy(message: impl Into<String>) -> Self;
152 fn unhealthy(message: impl Into<String>) -> Self;
154}
155
156impl HealthStatus {
157 fn with_check(healthy: bool, failure_count: u32, message: impl Into<String>) -> Self {
161 Self {
162 healthy,
163 last_check: crate::prelude::now_micros(),
164 failure_count,
165 message: Some(message.into()),
166 }
167 }
168}
169
170impl HealthStatusExt for HealthStatus {
171 fn healthy(message: impl Into<String>) -> Self {
172 Self::with_check(true, 0, message)
173 }
174
175 fn unhealthy(message: impl Into<String>) -> Self {
176 Self::with_check(false, 1, message)
177 }
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
181#[serde(rename_all = "kebab-case")]
182pub enum NodeType {
183 Imu,
184 Camera,
185 ImageClassifier,
186 ObjectDetector,
187 BehaviorExecutor,
188 LlmCommand,
189 Teleop,
190 Motor,
191 WebsocketBridge,
192 VideoStreamer,
193 Simulator,
194 Speaker,
195 Listener,
196 Rl,
197 InstanceTrack,
198 Diagnostics,
199 Servo,
200 PanTilt,
201}
202
203impl NodeType {
204 pub const ALL: &'static [NodeType] = &[
205 NodeType::Imu,
206 NodeType::Camera,
207 NodeType::ImageClassifier,
208 NodeType::ObjectDetector,
209 NodeType::BehaviorExecutor,
210 NodeType::LlmCommand,
211 NodeType::Teleop,
212 NodeType::Motor,
213 NodeType::WebsocketBridge,
214 NodeType::VideoStreamer,
215 NodeType::Simulator,
216 NodeType::Speaker,
217 NodeType::Listener,
218 NodeType::Rl,
219 NodeType::InstanceTrack,
220 NodeType::Diagnostics,
221 NodeType::Servo,
222 NodeType::PanTilt,
223 ];
224
225 pub fn as_str(&self) -> &'static str {
232 match self {
233 NodeType::Imu => "imu",
234 NodeType::Camera => "camera",
235 NodeType::ImageClassifier => "image-classifier",
236 NodeType::ObjectDetector => "object-detector",
237 NodeType::BehaviorExecutor => "behavior-executor",
238 NodeType::LlmCommand => "llm-command",
239 NodeType::Teleop => "teleop",
240 NodeType::Motor => "motor",
241 NodeType::WebsocketBridge => "websocket-bridge",
242 NodeType::VideoStreamer => "video-streamer",
243 NodeType::Simulator => "simulator",
244 NodeType::Speaker => "speaker",
245 NodeType::Listener => "listener",
246 NodeType::Rl => "rl",
247 NodeType::InstanceTrack => "instance-track",
248 NodeType::Diagnostics => "diagnostics",
249 NodeType::Servo => "servo",
250 NodeType::PanTilt => "pan-tilt",
251 }
252 }
253}
254
255impl std::fmt::Display for NodeType {
256 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257 write!(f, "{}", self.as_str())
258 }
259}
260
261#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
262#[serde(rename_all = "kebab-case")]
263pub enum NodeTag {
264 Sensor,
265 Inertial,
266 Capture,
267 Ai,
268 Classifier,
269 Detector,
270 Vision,
271 Planner,
272 Control,
273 Nlp,
274 Input,
275 Actuator,
276 Motion,
277 Relay,
278 Websocket,
279 Streamer,
280 Video,
281 Simulator,
282 Logger,
283}
284
285#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema)]
288#[serde(rename_all = "kebab-case")]
289pub enum Capability {
290 Locomotion,
291 Joints,
292 Flight,
293 Video,
294 Vision,
295 Audio,
296 Manipulation,
297}
298
299#[async_trait]
300pub trait NodeImpl: Send + Sync + Debug + 'static {
301 type Config: DeserializeOwned + Send + Sync + Debug;
302
303 const NODE_TYPE: Option<NodeType> = None;
304
305 const NODE_TAGS: &'static [NodeTag] = &[];
306
307 const CRATE_NAME: Option<&'static str> = None;
315
316 const DESCRIPTION: &'static str = "";
319
320 const DEFAULT_RUN_TARGET: &'static str = "robot";
323
324 const CATALOG_TAGS: &'static [&'static str] = &[];
328
329 const CAPABILITIES: &'static [Capability] = &[];
333
334 async fn init(config: Self::Config) -> Result<Self>
345 where
346 Self: Sized;
347
348 async fn run(&mut self, ctx: &Context) -> Result<()>;
364
365 async fn shutdown(&mut self) -> Result<()> {
379 Ok(())
380 }
381
382 async fn health_check(&self) -> HealthStatus {
391 HealthStatus {
392 healthy: true,
393 last_check: crate::prelude::now_micros(),
394 failure_count: 0,
395 message: Some("Node is running".to_string()),
396 }
397 }
398
399 fn health_diagnostics(&self) -> Option<std::collections::HashMap<String, String>> {
410 None
411 }
412
413 fn preflight(&self) -> Result<()> {
437 Ok(())
438 }
439}
440
441pub fn fmt_node_with_controller(
448 f: &mut std::fmt::Formatter<'_>,
449 struct_name: &str,
450 config: &impl Debug,
451 controller_name: &str,
452 update_counter: u64,
453) -> std::fmt::Result {
454 f.debug_struct(struct_name)
455 .field("config", config)
456 .field("controller", &controller_name)
457 .field("update_counter", &update_counter)
458 .finish()
459}
460
461#[derive(Clone)]
462pub struct Node<T: NodeImpl> {
463 node: Arc<Mutex<T>>,
464 state: Arc<Mutex<NodeState>>,
465 static_diagnostics: Arc<Option<std::collections::HashMap<String, String>>>,
475}
476
477impl<T: NodeImpl> Node<T> {
478 pub async fn from_config(config: T::Config) -> Result<Self> {
486 info!("Initializing node");
487
488 let node = T::init(config).await?;
489 let static_diagnostics = node.health_diagnostics();
490
491 Ok(Self {
492 node: Arc::new(Mutex::new(node)),
493 state: Arc::new(Mutex::new(NodeState::Starting)),
494 static_diagnostics: Arc::new(static_diagnostics),
495 })
496 }
497
498 pub fn static_diagnostics(&self) -> Option<std::collections::HashMap<String, String>> {
501 (*self.static_diagnostics).clone()
502 }
503
504 pub async fn start(&self, ctx: Context) -> Result<()> {
518 {
519 let node = self.node.lock().await;
520 node.preflight()?;
521 }
522
523 {
524 let mut state = self.state.lock().await;
525 *state = NodeState::Running;
526 info!("Node transitioned to Running state");
527 }
528
529 let result = {
530 let mut node = self.node.lock().await;
531 debug!("Starting node execution");
532 node.run(&ctx).await
533 };
534
535 match result {
536 Ok(()) => {
537 info!("Node completed successfully");
538 self.shutdown().await?;
539 }
540 Err(e) => {
541 error!("Node failed with error: {}", e);
542 {
543 let mut state = self.state.lock().await;
544 *state = NodeState::Crashed;
545 }
546 self.shutdown().await?;
547 return Err(e);
548 }
549 }
550
551 Ok(())
552 }
553
554 pub async fn shutdown(&self) -> Result<()> {
558 info!("Shutting down node");
559
560 {
561 let mut state = self.state.lock().await;
562 *state = NodeState::Stopping;
563 }
564
565 let result = {
566 let mut node = self.node.lock().await;
567 node.shutdown().await
568 };
569
570 {
571 let mut state = self.state.lock().await;
572 *state = NodeState::Stopped;
573 info!("Node stopped");
574 }
575
576 if let Err(e) = result {
577 warn!("Error during shutdown: {}", e);
578 return Err(e);
579 }
580
581 Ok(())
582 }
583
584 pub async fn state(&self) -> NodeState {
586 self.state.lock().await.clone()
587 }
588
589 pub async fn health_check(&self) -> HealthStatus {
591 let node = self.node.lock().await;
592 node.health_check().await
593 }
594
595 pub async fn is_healthy(&self) -> bool {
597 matches!(self.state().await, NodeState::Running | NodeState::Starting)
598 }
599}
600
601pub async fn run_node<T: NodeImpl>(
652 config: T::Config,
653 ctx: Context,
654 health_config: HealthReportingConfig,
655) -> Result<()> {
656 crate::prelude::init_logging();
657
658 #[cfg(feature = "messaging")]
659 crate::log_publisher::attach(ctx.node_id(), ctx.clone());
660
661 let node = Node::<T>::from_config(config).await?;
662
663 #[cfg(feature = "messaging")]
664 {
665 if health_config.enabled {
666 let node_for_health = node.node.clone();
667 let static_diagnostics_for_health = node.static_diagnostics();
668 let ctx_for_health = ctx.clone();
669 let priority = health_config.priority;
670 let report_interval = health_config.interval();
671 let ttl_seconds = health_config.ttl_seconds();
672 let store_history = health_config.store_history;
673
674 tokio::spawn(async move {
675 use crate::health::HealthReporter;
676
677 let reporter = match HealthReporter::with_config_and_type_tags(
678 &ctx_for_health,
679 priority,
680 ttl_seconds,
681 store_history,
682 T::NODE_TYPE,
683 T::NODE_TAGS,
684 None,
685 )
686 .await
687 {
688 Ok(r) => r,
689 Err(e) => {
690 warn!("Health reporting disabled: {}", e);
691 return;
692 }
693 };
694
695 debug!(
696 "Health reporting enabled: priority={}, interval={:?}, ttl={}s, history={}",
697 priority, report_interval, ttl_seconds, store_history
698 );
699
700 let mut interval = tokio::time::interval(report_interval);
701
702 loop {
703 interval.tick().await;
704 debug!("Health tick - checking node health");
705
706 let msg_status = match node_for_health.try_lock() {
707 Ok(node) => {
708 let status = node.health_check().await;
709 let diagnostics = node.health_diagnostics();
710 crate::messages::system::HealthStatus {
711 timestamp: status.last_check,
712 level: if status.healthy {
713 crate::messages::system::HealthLevel::Ok
714 } else {
715 crate::messages::system::HealthLevel::Error
716 },
717 message: status.message.unwrap_or_else(|| "No message".to_string()),
718 diagnostics,
719 }
720 }
721 Err(_) => {
722 debug!("Node busy, reporting as healthy");
733 crate::messages::system::HealthStatus {
734 timestamp: crate::prelude::now_micros(),
735 level: crate::messages::system::HealthLevel::Ok,
736 message: "Node running (busy)".to_string(),
737 diagnostics: static_diagnostics_for_health.clone(),
738 }
739 }
740 };
741
742 if let Err(e) = reporter.report(msg_status).await {
743 warn!("Failed to report health: {}", e);
744 } else {
745 tracing::trace!("Health report sent successfully");
746 }
747 }
748 });
749 } else {
750 info!("Health reporting disabled");
751 }
752 }
753 #[cfg(not(feature = "messaging"))]
754 let _ = &health_config;
755
756 node.start(ctx).await
757}
758
759#[cfg(all(test, not(feature = "messaging")))]
760mod tests {
761 use super::*;
762 use crate::error::Mecha10Error;
763 use std::sync::atomic::{AtomicBool, Ordering};
764 use std::sync::Arc as StdArc;
765
766 #[derive(Debug, Default, serde::Deserialize)]
767 struct FakeConfig;
768
769 #[derive(Debug)]
770 struct OkNode {
771 ran: StdArc<AtomicBool>,
772 }
773
774 #[async_trait]
775 impl NodeImpl for OkNode {
776 type Config = FakeConfig;
777
778 async fn init(_config: Self::Config) -> Result<Self> {
779 Ok(Self {
780 ran: StdArc::new(AtomicBool::new(false)),
781 })
782 }
783
784 async fn run(&mut self, _ctx: &Context) -> Result<()> {
785 self.ran.store(true, Ordering::SeqCst);
786 Ok(())
787 }
788 }
789
790 #[derive(Debug)]
791 struct RejectingPreflightNode {
792 ran: StdArc<AtomicBool>,
793 }
794
795 #[async_trait]
796 impl NodeImpl for RejectingPreflightNode {
797 type Config = FakeConfig;
798
799 async fn init(_config: Self::Config) -> Result<Self> {
800 Ok(Self {
801 ran: StdArc::new(AtomicBool::new(false)),
802 })
803 }
804
805 async fn run(&mut self, _ctx: &Context) -> Result<()> {
806 self.ran.store(true, Ordering::SeqCst);
807 Ok(())
808 }
809
810 fn preflight(&self) -> Result<()> {
811 Err(Mecha10Error::Configuration("boom: bad node content".to_string()))
812 }
813 }
814
815 #[tokio::test]
816 async fn default_preflight_is_a_noop_and_run_still_executes() {
817 let node = Node::<OkNode>::from_config(FakeConfig).await.unwrap();
818 let ctx = Context::new("test-node-ok").await.unwrap();
819
820 let ran_handle = { node.node.lock().await.ran.clone() };
821
822 node.start(ctx).await.unwrap();
823
824 assert!(ran_handle.load(Ordering::SeqCst), "run() should have executed");
825 }
826
827 #[tokio::test]
828 async fn start_fails_fast_when_preflight_rejects_config_and_never_calls_run() {
829 let node = Node::<RejectingPreflightNode>::from_config(FakeConfig).await.unwrap();
830 let ctx = Context::new("test-node-rejecting").await.unwrap();
831
832 let ran_handle = { node.node.lock().await.ran.clone() };
833
834 let result = node.start(ctx).await;
835
836 assert!(result.is_err());
837 assert!(result.unwrap_err().to_string().contains("boom: bad node content"));
838 assert!(
839 !ran_handle.load(Ordering::SeqCst),
840 "run() must not execute when preflight() rejects the node"
841 );
842 }
843
844 #[test]
845 fn node_type_kebab_case_matches_existing_builtin_node_types_strings() {
846 let expected: &[(NodeType, &str)] = &[
847 (NodeType::Imu, "imu"),
848 (NodeType::Camera, "camera"),
849 (NodeType::ImageClassifier, "image-classifier"),
850 (NodeType::ObjectDetector, "object-detector"),
851 (NodeType::BehaviorExecutor, "behavior-executor"),
852 (NodeType::LlmCommand, "llm-command"),
853 (NodeType::Teleop, "teleop"),
854 (NodeType::Motor, "motor"),
855 (NodeType::WebsocketBridge, "websocket-bridge"),
856 (NodeType::VideoStreamer, "video-streamer"),
857 (NodeType::Simulator, "simulator"),
858 (NodeType::Speaker, "speaker"),
859 (NodeType::Listener, "listener"),
860 (NodeType::Rl, "rl"),
861 (NodeType::InstanceTrack, "instance-track"),
862 (NodeType::Diagnostics, "diagnostics"),
863 (NodeType::Servo, "servo"),
864 (NodeType::PanTilt, "pan-tilt"),
865 ];
866
867 assert_eq!(expected.len(), NodeType::ALL.len());
868
869 for (variant, kebab) in expected {
870 let json = serde_json::to_string(variant).unwrap();
871 assert_eq!(json, format!("\"{}\"", kebab));
872 assert_eq!(variant.as_str(), *kebab);
873
874 let round_tripped: NodeType = serde_json::from_str(&json).unwrap();
875 assert_eq!(round_tripped, *variant);
876 }
877 }
878
879 #[test]
880 fn node_tag_kebab_case_matches_expected_strings() {
881 let expected: &[(NodeTag, &str)] = &[
882 (NodeTag::Sensor, "sensor"),
883 (NodeTag::Inertial, "inertial"),
884 (NodeTag::Capture, "capture"),
885 (NodeTag::Ai, "ai"),
886 (NodeTag::Classifier, "classifier"),
887 (NodeTag::Detector, "detector"),
888 (NodeTag::Vision, "vision"),
889 (NodeTag::Planner, "planner"),
890 (NodeTag::Control, "control"),
891 (NodeTag::Nlp, "nlp"),
892 (NodeTag::Input, "input"),
893 (NodeTag::Actuator, "actuator"),
894 (NodeTag::Motion, "motion"),
895 (NodeTag::Relay, "relay"),
896 (NodeTag::Websocket, "websocket"),
897 (NodeTag::Streamer, "streamer"),
898 (NodeTag::Video, "video"),
899 (NodeTag::Simulator, "simulator"),
900 (NodeTag::Logger, "logger"),
901 ];
902
903 for (variant, kebab) in expected {
904 let json = serde_json::to_string(variant).unwrap();
905 assert_eq!(json, format!("\"{}\"", kebab));
906
907 let round_tripped: NodeTag = serde_json::from_str(&json).unwrap();
908 assert_eq!(round_tripped, *variant);
909 }
910 }
911
912 #[test]
913 fn capability_kebab_case_matches_expected_strings() {
914 let expected: &[(Capability, &str)] = &[
915 (Capability::Locomotion, "locomotion"),
916 (Capability::Joints, "joints"),
917 (Capability::Flight, "flight"),
918 (Capability::Video, "video"),
919 (Capability::Vision, "vision"),
920 (Capability::Audio, "audio"),
921 (Capability::Manipulation, "manipulation"),
922 ];
923
924 for (variant, kebab) in expected {
925 let json = serde_json::to_string(variant).unwrap();
926 assert_eq!(json, format!("\"{}\"", kebab));
927
928 let round_tripped: Capability = serde_json::from_str(&json).unwrap();
929 assert_eq!(round_tripped, *variant);
930 }
931 }
932
933 #[test]
934 fn node_impl_defaults_node_type_to_none_and_tags_to_empty() {
935 assert_eq!(OkNode::NODE_TYPE, None);
936 assert!(OkNode::NODE_TAGS.is_empty());
937 }
938
939 #[test]
940 fn node_impl_defaults_capabilities_to_empty() {
941 assert!(OkNode::CAPABILITIES.is_empty());
942 }
943
944 #[test]
945 fn node_impl_defaults_registration_consts() {
946 assert_eq!(OkNode::CRATE_NAME, None);
947 assert_eq!(OkNode::DESCRIPTION, "");
948 assert_eq!(OkNode::DEFAULT_RUN_TARGET, "robot");
949 assert!(OkNode::CATALOG_TAGS.is_empty());
950 }
951}