1use anyhow::{Context, Result};
6use serde::{Deserialize, Serialize};
7use std::path::PathBuf;
8
9#[derive(Debug, Serialize, Deserialize)]
10pub struct ProjectConfig {
11 pub name: String,
12 pub version: String,
13 pub robot: RobotConfig,
14 #[serde(default, skip_serializing_if = "Option::is_none")]
15 pub simulation: Option<ProjectSimulationConfig>,
16 #[serde(default, skip_serializing_if = "Option::is_none")]
17 pub lifecycle: Option<LifecycleConfig>,
18 #[serde(default)]
19 pub nodes: NodesConfig,
20 #[serde(default, skip_serializing_if = "Option::is_none")]
21 pub targets: Option<TargetsConfig>,
22 #[serde(default, skip_serializing_if = "Option::is_none")]
23 pub behaviors: Option<BehaviorsConfig>,
24 #[serde(default)]
25 pub services: ServicesConfig,
26 #[serde(default)]
27 pub docker: DockerServicesConfig,
28 #[serde(default)]
29 pub environments: EnvironmentsConfig,
30}
31
32#[derive(Debug, Clone, PartialEq)]
38pub enum NodeSource {
39 Framework,
41 Project,
43 Registry(String),
45}
46
47#[derive(Debug, Clone)]
59pub struct NodeSpec {
60 pub name: String,
62 #[allow(dead_code)] pub identifier: String,
65 pub source: NodeSource,
67}
68
69impl NodeSpec {
70 pub fn parse(identifier: &str) -> Result<Self> {
89 let identifier = identifier.trim();
90
91 if !identifier.starts_with('@') {
93 if identifier.is_empty() {
94 anyhow::bail!("Empty node identifier");
95 }
96 return Ok(Self {
97 name: identifier.to_string(),
98 identifier: identifier.to_string(),
99 source: NodeSource::Project,
100 });
101 }
102
103 let without_at = identifier.strip_prefix('@').unwrap();
104 let parts: Vec<&str> = without_at.splitn(2, '/').collect();
105
106 if parts.len() != 2 {
107 anyhow::bail!(
108 "Invalid node identifier '{}'. Expected @<scope>/<name> format",
109 identifier
110 );
111 }
112
113 let scope = parts[0];
114 let name = parts[1].to_string();
115
116 if scope.is_empty() || name.is_empty() {
117 anyhow::bail!("Empty scope or name in identifier: {}", identifier);
118 }
119
120 let source = match scope {
121 "mecha10" => NodeSource::Framework,
122 "local" => NodeSource::Project,
123 org => NodeSource::Registry(org.to_string()),
124 };
125
126 Ok(Self {
127 name,
128 identifier: identifier.to_string(),
129 source,
130 })
131 }
132
133 pub fn is_framework(&self) -> bool {
135 matches!(self.source, NodeSource::Framework)
136 }
137
138 #[allow(dead_code)] pub fn is_project(&self) -> bool {
141 matches!(self.source, NodeSource::Project)
142 }
143
144 pub fn package_path(&self) -> String {
150 match &self.source {
151 NodeSource::Framework => format!("mecha10-nodes-{}", self.name),
152 NodeSource::Project => format!("nodes/{}", self.name),
153 NodeSource::Registry(org) => format!("node_modules/@{}/{}", org, self.name),
154 }
155 }
156
157 #[allow(dead_code)] pub fn config_dir(&self) -> String {
166 match &self.source {
167 NodeSource::Framework => format!("configs/nodes/{}", self.identifier),
168 NodeSource::Project => format!("configs/nodes/{}", self.name),
169 NodeSource::Registry(_) => format!("configs/nodes/{}", self.identifier),
170 }
171 }
172}
173
174#[derive(Debug, Serialize, Deserialize, Default, Clone)]
192#[serde(transparent)]
193pub struct NodesConfig(pub Vec<String>);
194
195impl NodesConfig {
196 #[allow(dead_code)] pub fn new() -> Self {
199 Self(Vec::new())
200 }
201
202 pub fn get_node_specs(&self) -> Vec<NodeSpec> {
204 self.0.iter().filter_map(|id| NodeSpec::parse(id).ok()).collect()
205 }
206
207 pub fn get_node_names(&self) -> Vec<String> {
209 self.get_node_specs().iter().map(|s| s.name.clone()).collect()
210 }
211
212 pub fn find_by_name(&self, name: &str) -> Option<NodeSpec> {
214 self.get_node_specs().into_iter().find(|s| s.name == name)
215 }
216
217 pub fn contains(&self, name: &str) -> bool {
219 self.find_by_name(name).is_some()
220 }
221
222 pub fn add_node(&mut self, identifier: &str) {
224 if !self.0.contains(&identifier.to_string()) {
225 self.0.push(identifier.to_string());
226 }
227 }
228
229 #[allow(dead_code)] pub fn remove_node(&mut self, name: &str) {
232 self.0
233 .retain(|id| NodeSpec::parse(id).map(|s| s.name != name).unwrap_or(true));
234 }
235
236 #[allow(dead_code)] pub fn identifiers(&self) -> &[String] {
239 &self.0
240 }
241
242 #[allow(dead_code)] pub fn is_empty(&self) -> bool {
245 self.0.is_empty()
246 }
247
248 #[allow(dead_code)] pub fn len(&self) -> usize {
251 self.0.len()
252 }
253}
254
255#[derive(Debug, Serialize, Deserialize, Clone, Default)]
275pub struct TargetsConfig {
276 #[serde(default)]
279 pub robot: Vec<String>,
280
281 #[serde(default)]
284 pub remote: Vec<String>,
285}
286
287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289#[allow(dead_code)] pub enum NodeTarget {
291 Robot,
293 Remote,
295 Default,
297}
298
299#[allow(dead_code)] impl TargetsConfig {
301 pub fn get_target(&self, node_id: &str) -> NodeTarget {
311 if self.robot.iter().any(|n| n == node_id) {
312 NodeTarget::Robot
313 } else if self.remote.iter().any(|n| n == node_id) {
314 NodeTarget::Remote
315 } else {
316 NodeTarget::Default
317 }
318 }
319
320 pub fn is_remote(&self, node_id: &str) -> bool {
322 self.remote.iter().any(|n| n == node_id)
323 }
324
325 pub fn is_robot(&self, node_id: &str) -> bool {
327 self.robot.iter().any(|n| n == node_id)
328 }
329
330 pub fn remote_nodes(&self) -> &[String] {
332 &self.remote
333 }
334
335 #[allow(dead_code)]
337 pub fn robot_nodes(&self) -> &[String] {
338 &self.robot
339 }
340
341 pub fn has_remote_nodes(&self) -> bool {
343 !self.remote.is_empty()
344 }
345
346 pub fn has_custom_remote_nodes(&self) -> bool {
348 self.remote.iter().any(|n| n.starts_with("@local/") || !n.starts_with('@'))
349 }
350
351 pub fn framework_remote_nodes(&self) -> Vec<&str> {
353 self.remote
354 .iter()
355 .filter(|n| n.starts_with("@mecha10/"))
356 .map(|s| s.as_str())
357 .collect()
358 }
359
360 pub fn sorted_remote_nodes(&self) -> Vec<String> {
362 let mut nodes = self.remote.clone();
363 nodes.sort();
364 nodes
365 }
366}
367
368#[derive(Debug, Serialize, Deserialize, Clone)]
372pub struct BehaviorsConfig {
373 pub active: String,
375}
376
377#[derive(Debug, Serialize, Deserialize, Default)]
378pub struct ServicesConfig {
379 #[serde(default)]
380 pub http_api: Option<HttpApiServiceConfig>,
381 #[serde(default)]
382 pub database: Option<DatabaseServiceConfig>,
383 #[serde(default)]
384 pub job_processor: Option<JobProcessorServiceConfig>,
385 #[serde(default)]
386 pub scheduler: Option<SchedulerServiceConfig>,
387}
388
389#[derive(Debug, Serialize, Deserialize, Clone)]
390pub struct HttpApiServiceConfig {
391 pub host: String,
392 pub port: u16,
393 #[serde(default = "default_enable_cors")]
394 pub _enable_cors: bool,
395}
396
397#[derive(Debug, Serialize, Deserialize, Clone)]
398pub struct DatabaseServiceConfig {
399 pub url: String,
400 #[serde(default = "default_max_connections")]
401 pub max_connections: u32,
402 #[serde(default = "default_timeout_seconds")]
403 pub timeout_seconds: u64,
404}
405
406#[derive(Debug, Serialize, Deserialize, Clone)]
407pub struct JobProcessorServiceConfig {
408 #[serde(default = "default_worker_count")]
409 pub worker_count: usize,
410 #[serde(default = "default_max_queue_size")]
411 pub max_queue_size: usize,
412}
413
414#[derive(Debug, Serialize, Deserialize, Clone)]
415pub struct SchedulerServiceConfig {
416 pub tasks: Vec<ScheduledTaskConfig>,
417}
418
419#[derive(Debug, Serialize, Deserialize, Clone)]
420#[allow(dead_code)]
421pub struct ScheduledTaskConfig {
422 pub name: String,
423 pub cron: String,
424 pub topic: String,
425 pub payload: String,
426}
427
428#[derive(Debug, Serialize, Deserialize)]
429pub struct RobotConfig {
430 pub id: String,
431 #[serde(default)]
432 pub platform: Option<String>,
433 #[serde(default)]
434 pub description: Option<String>,
435}
436
437#[derive(Debug, Serialize, Deserialize, Clone)]
442pub struct ProjectSimulationConfig {
443 #[serde(default, skip_serializing_if = "Option::is_none")]
446 pub scenario: Option<String>,
447
448 #[serde(default, skip_serializing_if = "Option::is_none")]
449 pub model: Option<String>,
450 #[serde(default, skip_serializing_if = "Option::is_none")]
451 pub model_config: Option<String>,
452 #[serde(default, skip_serializing_if = "Option::is_none")]
453 pub environment: Option<String>,
454 #[serde(default, skip_serializing_if = "Option::is_none")]
455 pub environment_config: Option<String>,
456}
457
458#[derive(Debug, Serialize, Deserialize, Clone)]
463pub struct LifecycleConfig {
464 pub modes: std::collections::HashMap<String, ModeConfig>,
466
467 #[serde(default = "default_lifecycle_mode")]
469 pub default_mode: String,
470}
471
472#[derive(Debug, Serialize, Deserialize, Clone)]
476pub struct ModeConfig {
477 pub nodes: Vec<String>,
479}
480
481fn default_lifecycle_mode() -> String {
482 "startup".to_string()
483}
484
485impl LifecycleConfig {
487 #[allow(dead_code)] pub fn validate(&self, available_nodes: &[String]) -> Result<()> {
500 if !self.modes.contains_key(&self.default_mode) {
502 return Err(anyhow::anyhow!(
503 "Default mode '{}' not found in modes. Available modes: {}",
504 self.default_mode,
505 self.modes.keys().map(|k| k.as_str()).collect::<Vec<_>>().join(", ")
506 ));
507 }
508
509 for (mode_name, mode_config) in &self.modes {
511 mode_config.validate(mode_name, available_nodes)?;
512 }
513
514 Ok(())
515 }
516}
517
518impl ModeConfig {
519 #[allow(dead_code)] pub fn validate(&self, mode_name: &str, available_nodes: &[String]) -> Result<()> {
531 for node in &self.nodes {
533 if !available_nodes.contains(node) {
534 return Err(anyhow::anyhow!(
535 "Mode '{}': node '{}' not found in project configuration. Available nodes: {}",
536 mode_name,
537 node,
538 available_nodes.join(", ")
539 ));
540 }
541 }
542
543 Ok(())
544 }
545}
546
547#[derive(Debug, Serialize, Deserialize, Default, Clone)]
549pub struct DockerServicesConfig {
550 #[serde(default)]
552 pub robot: Vec<String>,
553
554 #[serde(default)]
556 pub edge: Vec<String>,
557
558 #[serde(default = "default_compose_file")]
560 pub compose_file: String,
561
562 #[serde(default = "default_auto_start")]
564 pub auto_start: bool,
565}
566
567#[derive(Debug, Serialize, Deserialize, Clone)]
575pub struct EnvironmentsConfig {
576 #[serde(default = "default_dev_environment")]
578 pub dev: EnvironmentConfig,
579
580 #[serde(default, skip_serializing_if = "Option::is_none")]
582 pub staging: Option<EnvironmentConfig>,
583
584 #[serde(default = "default_prod_environment")]
586 pub prod: EnvironmentConfig,
587}
588
589impl Default for EnvironmentsConfig {
590 fn default() -> Self {
591 Self {
592 dev: default_dev_environment(),
593 staging: None,
594 prod: default_prod_environment(),
595 }
596 }
597}
598
599impl EnvironmentsConfig {
600 pub fn get(&self, env: &str) -> Option<&EnvironmentConfig> {
602 match env {
603 "dev" | "development" => Some(&self.dev),
604 "staging" => self.staging.as_ref(),
605 "prod" | "production" => Some(&self.prod),
606 _ => None,
607 }
608 }
609
610 pub fn current(&self) -> &EnvironmentConfig {
612 let env = std::env::var("MECHA10_ENV").unwrap_or_else(|_| "dev".to_string());
613 self.get(&env).unwrap_or(&self.dev)
614 }
615
616 pub fn control_plane_url(&self) -> String {
618 std::env::var("MECHA10_CONTROL_PLANE_URL").unwrap_or_else(|_| self.current().control_plane.clone())
619 }
620
621 #[allow(dead_code)]
624 pub fn api_url(&self) -> String {
625 format!("{}/api", self.control_plane_url())
626 }
627
628 pub fn dashboard_url(&self) -> String {
631 std::env::var("MECHA10_DASHBOARD_URL").unwrap_or_else(|_| format!("{}/dashboard", self.control_plane_url()))
632 }
633
634 pub fn relay_url(&self) -> String {
637 if let Ok(url) = std::env::var("WEBRTC_RELAY_URL") {
638 return url;
639 }
640
641 let control_plane = self.control_plane_url();
642 let ws_url = if control_plane.starts_with("https://") {
644 control_plane.replace("https://", "wss://")
645 } else if control_plane.starts_with("http://") {
646 control_plane.replace("http://", "ws://")
647 } else {
648 control_plane
649 };
650 format!("{}/webrtc-relay", ws_url)
651 }
652
653 pub fn redis_url(&self) -> String {
655 std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://localhost:6380".to_string())
656 }
657}
658
659#[derive(Debug, Serialize, Deserialize, Clone)]
661pub struct EnvironmentConfig {
662 pub control_plane: String,
664}
665
666fn default_dev_environment() -> EnvironmentConfig {
667 EnvironmentConfig {
668 control_plane: "http://localhost:8100".to_string(),
669 }
670}
671
672fn default_prod_environment() -> EnvironmentConfig {
673 EnvironmentConfig {
674 control_plane: "https://mecha.industries".to_string(),
675 }
676}
677
678fn default_enable_cors() -> bool {
680 true
681}
682
683fn default_max_connections() -> u32 {
684 10
685}
686
687fn default_timeout_seconds() -> u64 {
688 30
689}
690
691fn default_worker_count() -> usize {
692 4
693}
694
695fn default_max_queue_size() -> usize {
696 100
697}
698
699fn default_compose_file() -> String {
700 "docker/docker-compose.yml".to_string()
701}
702
703fn default_auto_start() -> bool {
704 true
705}
706
707#[allow(dead_code)]
709pub async fn load_robot_id(config_path: &PathBuf) -> Result<String> {
710 let content = tokio::fs::read_to_string(config_path)
711 .await
712 .context("Failed to read mecha10.json")?;
713
714 let config: ProjectConfig = serde_json::from_str(&content).context("Failed to parse mecha10.json")?;
715
716 Ok(config.robot.id)
717}
718
719pub async fn load_project_config(config_path: &PathBuf) -> Result<ProjectConfig> {
721 let content = tokio::fs::read_to_string(config_path)
722 .await
723 .context("Failed to read mecha10.json")?;
724
725 let config: ProjectConfig = serde_json::from_str(&content).context("Failed to parse mecha10.json")?;
726
727 Ok(config)
728}