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
//! Node-level configuration loading with environment-aware file fallback.
use super::Context;
use crate::error::{Mecha10Error, Result};
use anyhow::Context as _;
use serde::de::DeserializeOwned;
impl Context {
/// Load node configuration with environment-aware file-level fallback
///
/// This method implements the V2 configuration system with:
/// - Environment-specific configs (dev/staging/production), selected *within* a config
/// file's `{"dev": {...}, "production": {...}}` envelope (see
/// [`Self::load_environment_aware_config`])
/// - File-level fallback (no key-by-key merging)
/// - Automatic project-root discovery via [`crate::fs_utils::find_project_root`]
///
/// **Tier order** (mirrors `mecha10_cli_core::paths::config::node_config_candidates`, the
/// canonical 2-tier resolution order for node configs -- this method can't call that helper
/// directly since `mecha10-core` is a dependency *of* `mecha10-cli-core`, not the reverse,
/// but it must stay in sync with it):
/// 1. `configs/nodes/@mecha10/{node_name}/config.json` - Framework nodes
/// 2. `configs/nodes/{node_name}/config.json` - Project nodes (preferred)
/// 3. `T::default()` - Default implementation, if neither tier has a config file (or no
/// project root could be found)
///
/// **Environment Detection:**
/// - Uses `MECHA10_ENV` env var (default: "dev")
/// - Supported values: "dev", "staging", "production", or custom
///
/// **Semantic Validation:**
/// - Not run here. This method is generic over `T` with only a
/// `DeserializeOwned + Default` bound, and stable Rust has no
/// specialization -- a function generic over `T` can't conditionally
/// call [`crate::config::Validate::validate`] only when `T` happens to
/// implement it. Node types that need semantic validation should call
/// `validate()` explicitly on the config returned here.
///
/// # Type Parameters
///
/// * `T` - Configuration type that implements `DeserializeOwned` + `Default`
///
/// # Arguments
///
/// * `node_name` - Name of the node (e.g., "simulator", "camera-streamer")
///
/// # Returns
///
/// The loaded configuration of type `T`, using the first available source
/// in the fallback chain.
///
/// # Example
///
/// ```rust
/// use mecha10_core::prelude::*;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Clone, Deserialize, Serialize, Default)]
/// struct SimBridgeConfig {
/// camera_width: u32,
/// camera_height: u32,
/// camera_fps: u32,
/// }
///
/// # async fn example(ctx: &Context) -> Result<()> {
/// let config: SimBridgeConfig = ctx.load_node_config("simulator").await?;
/// # Ok(())
/// # }
/// ```
pub async fn load_node_config<T>(&self, node_name: &str) -> Result<T>
where
T: DeserializeOwned + Default,
{
Self::resolve_node_config(node_name).await
}
/// The actual resolution logic behind [`Self::load_node_config`], split out as a
/// `self`-free associated function so it's unit-testable without constructing a full
/// [`Context`] (which requires a live Redis connection).
async fn resolve_node_config<T>(node_name: &str) -> Result<T>
where
T: DeserializeOwned + Default,
{
use std::env;
let environment = env::var("MECHA10_ENV").unwrap_or_else(|_| "dev".to_string());
let current_dir = env::current_dir()
.map_err(|e| Mecha10Error::Configuration(format!("Failed to get current directory: {}", e)))?;
if let Some(project_root) = crate::fs_utils::find_project_root(¤t_dir) {
let flat_config_path = project_root
.join("configs")
.join("nodes")
.join("@mecha10")
.join(node_name)
.join("config.json");
if flat_config_path.exists() {
tracing::debug!(
"Loading node config for '{}' from flat path: {}",
node_name,
flat_config_path.display()
);
return Self::load_environment_aware_config(&flat_config_path, &environment)
.with_context(|| {
format!(
"Failed to load node config for '{}' from '{}'",
node_name,
flat_config_path.display()
)
})
.map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)));
}
let project_config_path = project_root
.join("configs")
.join("nodes")
.join(node_name)
.join("config.json");
if project_config_path.exists() {
tracing::debug!(
"Loading node config for '{}' from project path: {}",
node_name,
project_config_path.display()
);
return Self::load_environment_aware_config(&project_config_path, &environment)
.with_context(|| {
format!(
"Failed to load node config for '{}' from '{}'",
node_name,
project_config_path.display()
)
})
.map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)));
}
}
tracing::debug!(
"No config file found for node '{}', using Default implementation",
node_name
);
let config = T::default();
Ok(config)
}
/// Load a config file in environment-aware format.
///
/// Config files must have the format:
/// ```json
/// {
/// "dev": { ... config ... },
/// "production": { ... config ... }
/// }
/// ```
fn load_environment_aware_config<T>(path: &std::path::Path, environment: &str) -> Result<T>
where
T: DeserializeOwned + Default,
{
let content =
std::fs::read_to_string(path).with_context(|| format!("Failed to read config file: {}", path.display()))?;
let json_value: serde_json::Value =
serde_json::from_str(&content).with_context(|| format!("Failed to parse JSON from: {}", path.display()))?;
let obj = json_value.as_object().ok_or_else(|| {
Mecha10Error::Configuration(format!(
"Config must be a JSON object with 'dev'/'production' keys: {}",
path.display()
))
})?;
let env_key = match environment {
"production" | "prod" => "production",
_ => "dev",
};
let env_section = obj
.get(env_key)
.or_else(|| {
let fallback = if env_key == "dev" { "production" } else { "dev" };
tracing::warn!(
"Environment '{}' not found in config, falling back to '{}': {}",
env_key,
fallback,
path.display()
);
obj.get(fallback)
})
.ok_or_else(|| {
Mecha10Error::Configuration(format!(
"Config must have 'dev' or 'production' section: {}",
path.display()
))
})?;
tracing::debug!("Loading '{}' environment section from: {}", env_key, path.display());
let config: T = serde_json::from_value(env_section.clone())
.with_context(|| format!("Failed to deserialize '{}' section from: {}", env_key, path.display()))
.map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;
Ok(config)
}
}
#[cfg(test)]
mod tests {
use super::Context;
use serde::{Deserialize, Serialize};
use serial_test::serial;
use std::fs;
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
struct TestNodeConfig {
#[serde(default)]
value: String,
}
/// Mirrors the real shape of a node's own config struct (e.g.
/// `mecha10_nodes_behavior_executor::BehaviorExecutorConfig`) - `deny_unknown_fields` plus a
/// flattened `crate::relay_topics::RelayTopicsField`, the pattern every node's config now
/// uses instead of hand-declaring its own `relay_topics` field.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(deny_unknown_fields)]
struct StrictTestNodeConfig {
#[serde(default)]
value: String,
#[serde(flatten)]
relay: crate::relay_topics::RelayTopicsField,
}
fn envelope(dev_value: &str) -> String {
format!(r#"{{"dev": {{"value": "{dev_value}"}}, "production": {{"value": "{dev_value}-prod"}}}}"#)
}
#[tokio::test]
#[serial]
async fn resolve_node_config_loads_from_project_tier_when_only_project_config_exists() {
let original_dir = std::env::current_dir().unwrap();
let project = tempfile::tempdir().unwrap();
fs::write(project.path().join("mecha10.json"), "{}").unwrap();
let node_dir = project.path().join("configs").join("nodes").join("my-node");
fs::create_dir_all(&node_dir).unwrap();
fs::write(node_dir.join("config.json"), envelope("project")).unwrap();
std::env::set_current_dir(project.path()).unwrap();
let result = Context::resolve_node_config::<TestNodeConfig>("my-node").await;
std::env::set_current_dir(original_dir).unwrap();
assert_eq!(result.unwrap().value, "project");
}
#[tokio::test]
#[serial]
async fn resolve_node_config_prefers_framework_tier_over_project_tier() {
let original_dir = std::env::current_dir().unwrap();
let project = tempfile::tempdir().unwrap();
fs::write(project.path().join("mecha10.json"), "{}").unwrap();
let framework_dir = project
.path()
.join("configs")
.join("nodes")
.join("@mecha10")
.join("my-node");
fs::create_dir_all(&framework_dir).unwrap();
fs::write(framework_dir.join("config.json"), envelope("framework")).unwrap();
let project_dir = project.path().join("configs").join("nodes").join("my-node");
fs::create_dir_all(&project_dir).unwrap();
fs::write(project_dir.join("config.json"), envelope("project")).unwrap();
std::env::set_current_dir(project.path()).unwrap();
let result = Context::resolve_node_config::<TestNodeConfig>("my-node").await;
std::env::set_current_dir(original_dir).unwrap();
assert_eq!(result.unwrap().value, "framework");
}
/// Regression test (LAB-2270): a config declaring `relay_topics` must load into a strict
/// (`deny_unknown_fields`) node config that embeds `crate::relay_topics::RelayTopicsField`
/// via `#[serde(flatten)]` - and the value must actually come through typed, not be
/// discarded. (An earlier design had `Context::load_node_config` silently strip the field
/// out of the JSON before deserializing, so no node needed to declare it at all - correct,
/// but opaque: a node's own type gave no hint the field existed, and it could never
/// meaningfully read the value even if it wanted to. Flattening a shared field in is the
/// same "no per-node reimplementation" property, but explicit and typed instead.)
#[tokio::test]
#[serial]
async fn resolve_node_config_populates_flattened_relay_topics_field_on_a_strict_node_config() {
let original_dir = std::env::current_dir().unwrap();
let project = tempfile::tempdir().unwrap();
fs::write(project.path().join("mecha10.json"), "{}").unwrap();
let node_dir = project.path().join("configs").join("nodes").join("my-node");
fs::create_dir_all(&node_dir).unwrap();
fs::write(
node_dir.join("config.json"),
r#"{
"dev": { "value": "project", "relay_topics": ["/my-node/status"] },
"production": { "value": "project-prod", "relay_topics": ["/my-node/status"] }
}"#,
)
.unwrap();
std::env::set_current_dir(project.path()).unwrap();
let result = Context::resolve_node_config::<StrictTestNodeConfig>("my-node").await;
std::env::set_current_dir(original_dir).unwrap();
let config = result.unwrap();
assert_eq!(config.value, "project");
assert_eq!(config.relay.relay_topics, Some(vec!["/my-node/status".to_string()]));
}
#[tokio::test]
#[serial]
async fn resolve_node_config_ignores_dead_v1_and_common_tiers_and_falls_back_to_default() {
let original_dir = std::env::current_dir().unwrap();
let project = tempfile::tempdir().unwrap();
fs::write(project.path().join("mecha10.json"), "{}").unwrap();
let env_tier_dir = project.path().join("configs").join("dev").join("nodes").join("my-node");
fs::create_dir_all(&env_tier_dir).unwrap();
fs::write(env_tier_dir.join("config.json"), r#"{"value": "dead-env-tier"}"#).unwrap();
let common_tier_dir = project
.path()
.join("configs")
.join("common")
.join("nodes")
.join("my-node");
fs::create_dir_all(&common_tier_dir).unwrap();
fs::write(common_tier_dir.join("config.json"), r#"{"value": "dead-common-tier"}"#).unwrap();
std::env::set_current_dir(project.path()).unwrap();
let result = Context::resolve_node_config::<TestNodeConfig>("my-node").await;
std::env::set_current_dir(original_dir).unwrap();
assert_eq!(result.unwrap(), TestNodeConfig::default());
}
#[tokio::test]
#[serial]
async fn resolve_node_config_falls_back_to_default_when_no_project_root_is_found() {
let original_dir = std::env::current_dir().unwrap();
let dir = tempfile::tempdir().unwrap();
std::env::set_current_dir(dir.path()).unwrap();
let result = Context::resolve_node_config::<TestNodeConfig>("my-node").await;
std::env::set_current_dir(original_dir).unwrap();
assert_eq!(result.unwrap(), TestNodeConfig::default());
}
}