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
//! Mecha10 Framework Macros
//!
//! This module provides convenience macros to reduce boilerplate in node and driver implementations.
/// Run a node with automatic config loading and context creation
///
/// This macro eliminates boilerplate by automatically handling:
/// - Config loading with fallback (from env var, file, or default)
/// - Context creation with node name
/// - Calling run_node with proper types
///
/// # Arguments
///
/// * `$node_type` - The NodeImpl type (e.g., CameraFakeNode)
/// * `$node_name` - The node name string (e.g., "camera_fake")
/// * `$env_var` - Environment variable for config file path (e.g., "CAMERA_CONFIG")
/// * `$config_file` - Default config file path (e.g., "config/drivers/realsense_d435.json")
/// * `$env_prefix` - Environment variable prefix for config overrides (e.g., "CAMERA")
///
/// # Example
///
/// ```rust
/// use mecha10::prelude::*;
///
/// #[derive(Debug)]
/// struct CameraFakeNode {
/// config: CameraConfig,
/// }
///
/// #[derive(Debug, Clone, Deserialize, Serialize, Default)]
/// struct CameraConfig {
/// fps: f32,
/// }
///
/// #[async_trait]
/// impl NodeImpl for CameraFakeNode {
/// type Config = CameraConfig;
///
/// async fn init(config: Self::Config) -> Result<Self> {
/// Ok(Self { config })
/// }
///
/// async fn run(&mut self, ctx: &Context) -> Result<()> {
/// // Node logic here
/// Ok(())
/// }
/// }
///
/// // Instead of 13 lines:
/// // pub async fn run() -> Result<()> {
/// // info!("Starting fake camera driver");
/// // let config = load_config_with_fallback(
/// // "CAMERA_CONFIG",
/// // "config/drivers/realsense_d435.json",
/// // "CAMERA",
/// // Some(CameraConfig::default())
/// // )?;
/// // let ctx = Context::new("camera_fake");
/// // run_node::<CameraFakeNode>(config, ctx).await
/// // }
///
/// // Simply use 1 line:
/// run_node_simple!(
/// CameraFakeNode,
/// "camera_fake",
/// "CAMERA_CONFIG",
/// "config/drivers/realsense_d435.json",
/// "CAMERA"
/// );
/// ```
/// Run a node with instance support for multi-instance deployments
///
/// This macro extends `run_node_simple!` with support for instance names,
/// allowing the same node implementation to run multiple instances with
/// different names and configurations.
///
/// # Arguments
///
/// * `$node_type` - The NodeImpl type (e.g., CameraFakeNode)
/// * `$node_name` - The base node name string (e.g., "camera_fake")
/// * `$instance_env` - Environment variable for instance name (e.g., "CAMERA_INSTANCE")
/// * `$env_var` - Environment variable for config file path (e.g., "CAMERA_CONFIG")
/// * `$config_file` - Default config file path (e.g., "config/drivers/camera/default.json")
/// * `$env_prefix` - Environment variable prefix for config overrides (e.g., "CAMERA")
///
/// # Example
///
/// ```rust
/// use mecha10::prelude::*;
///
/// #[derive(Debug)]
/// struct CameraFakeNode {
/// config: CameraConfig,
/// }
///
/// #[derive(Debug, Clone, Deserialize, Serialize, Default)]
/// struct CameraConfig {
/// fps: f32,
/// }
///
/// #[async_trait]
/// impl NodeImpl for CameraFakeNode {
/// type Config = CameraConfig;
///
/// async fn init(config: Self::Config) -> Result<Self> {
/// Ok(Self { config })
/// }
///
/// async fn run(&mut self, ctx: &Context) -> Result<()> {
/// // Node logic here - publishes to instance-scoped topics
/// Ok(())
/// }
/// }
///
/// run_node_with_instance!(
/// CameraFakeNode,
/// "camera_fake",
/// "CAMERA_INSTANCE", // Set to "left" or "right" etc.
/// "CAMERA_CONFIG",
/// "config/drivers/camera/default.json",
/// "CAMERA"
/// );
/// ```
///
/// # Environment Variables
///
/// - `$instance_env`: Instance name (e.g., "left", "right", "front_left")
/// - `$env_var`: Config file path
/// - `${env_prefix}_*`: Config overrides
///
/// # Instance Naming
///
/// If `$instance_env` is set to "left":
/// - Node ID: "camera_fake/left"
/// - Topics published via `publish_to_scoped()`: "/sensor/camera/rgb/left"
///
/// Generate a fluent builder setter method.
///
/// Eliminates the `pub fn <name>(mut self, <arg>: <ty>) -> Self { self.<field> = <expr>; self }`
/// boilerplate repeated across this workspace's many builder structs (`RuntimeBuilder`,
/// `RecoveryPolicyBuilder`, `LauncherServiceBuilder`, etc). Three shapes are supported,
/// matching every setter pattern actually in use:
///
/// - `assign`: plain assignment, no conversion — `self.field = value; self`
/// - `into`: `Into`-convert into a non-`Option` field — `self.field = value.into(); self`
/// - `into_some`: `Into`-convert, wrapped in `Some` — `self.field = Some(value.into()); self`
/// - `insert`: `Into`-convert a key/value pair and insert into a `HashMap` field —
/// `self.field.insert(key.into(), value.into()); self`
///
/// Many builders in this workspace store their fields on a nested config struct
/// (e.g. `RuntimeBuilder { config: RuntimeConfig }`) rather than directly on the
/// builder. Each shape also accepts a one-level `holder.field` path in that position
/// to target `self.holder.field` instead of `self.field`.
///
/// Doc comments (including doctests) are forwarded onto the generated method, so callers
/// can still document each setter's behavior individually.
///
/// # Examples
///
/// ```rust
/// use mecha10_core::builder_setter;
/// use std::time::Duration;
///
/// #[derive(Default)]
/// struct FooConfig {
/// timeout: Duration,
/// }
///
/// #[derive(Default)]
/// struct FooBuilder {
/// name: String,
/// endpoint: Option<String>,
/// config: FooConfig,
/// metadata: std::collections::HashMap<String, String>,
/// }
///
/// impl FooBuilder {
/// builder_setter!(assign, timeout, config.timeout, Duration);
/// builder_setter!(
/// /// Set the service name.
/// into, with_name, name, impl Into<String>
/// );
/// builder_setter!(into_some, with_endpoint, endpoint, impl Into<String>);
/// builder_setter!(insert, with_metadata, metadata, impl Into<String>, impl Into<String>);
/// }
///
/// let foo = FooBuilder::default()
/// .timeout(Duration::from_secs(5))
/// .with_name("svc")
/// .with_endpoint("https://example.com")
/// .with_metadata("region", "us-east-1");
/// assert_eq!(foo.name, "svc");
/// assert_eq!(foo.endpoint, Some("https://example.com".to_string()));
/// assert_eq!(foo.config.timeout, Duration::from_secs(5));
/// assert_eq!(foo.metadata.get("region"), Some(&"us-east-1".to_string()));
/// ```
/// Generate a str-returning accessor method for a fieldless-variant enum.
///
/// Eliminates the `fn <name>(&self) -> &str { match self { Self::A => "a", ... } }`
/// boilerplate repeated across this workspace's many "kind" enums for methods like
/// `as_str`, `display_name`, `description`, `label`, and `icon`. Each enum typically
/// needs several of these (one per method), so the macro is invoked once per method
/// and expands to its own `impl EnumName { .. }` block — multiple invocations for the
/// same enum simply produce multiple inherent impl blocks, which Rust allows.
///
/// Only fits the plain "one string literal per variant" shape. If a method has extra
/// logic (conditionals, formatting, computed values), leave it hand-written.
///
/// # Examples
///
/// ```rust
/// use mecha10_core::enum_str_method;
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// enum TargetArch {
/// X86_64,
/// Aarch64,
/// }
///
/// enum_str_method!(
/// /// Get string representation for metadata.
/// pub fn as_str(TargetArch) -> &str {
/// X86_64 => "x86_64",
/// Aarch64 => "aarch64",
/// }
/// );
///
/// enum_str_method!(
/// pub fn display_name(TargetArch) -> &str {
/// X86_64 => "x86_64 (Linux)",
/// Aarch64 => "ARM64 (Linux)",
/// }
/// );
///
/// assert_eq!(TargetArch::X86_64.as_str(), "x86_64");
/// assert_eq!(TargetArch::Aarch64.display_name(), "ARM64 (Linux)");
/// ```
) => ;
}
/// Generate a node crate's standard entrypoint: `pub async fn run() -> Result<()>`.
///
/// Eliminates the `Context::new` -> `load_node_config` -> `run_node` boilerplate that is
/// repeated byte-for-byte (module the node name and node type) at the bottom of every
/// node crate's `lib.rs`. Health reporting defaults to `HealthReportingConfig::normal()`;
/// pass the `HealthReportingConfig` constructor to use (e.g. `critical`, `background`) as
/// a third argument when a node needs a different priority.
///
/// # Arguments
///
/// * `$node_type` - The `NodeImpl` type to run (e.g. `CameraNode`)
/// * `$node_name` - The node name string, used for both context creation and config
/// loading (e.g. `"camera"`)
/// * `$health` - Optional `HealthReportingConfig` constructor name; defaults to `normal`
///
/// # Examples
///
/// ```rust
/// use mecha10_core::node_main;
/// use mecha10_core::prelude::*;
///
/// #[derive(Debug, Clone, Deserialize, Serialize, Default)]
/// struct CameraConfig {
/// fps: f32,
/// }
///
/// #[derive(Debug)]
/// struct CameraNode {
/// config: CameraConfig,
/// }
///
/// #[async_trait]
/// impl NodeImpl for CameraNode {
/// type Config = CameraConfig;
///
/// async fn init(config: Self::Config) -> Result<Self> {
/// Ok(Self { config })
/// }
///
/// async fn run(&mut self, ctx: &Context) -> Result<()> {
/// Ok(())
/// }
/// }
///
/// // Instead of:
/// // pub async fn run() -> Result<()> {
/// // let ctx = Context::new("camera").await?;
/// // let config: CameraConfig = ctx.load_node_config("camera").await?;
/// // run_node::<CameraNode>(config, ctx, HealthReportingConfig::normal()).await
/// // }
/// //
/// // Simply use:
/// node_main!(CameraNode, "camera");
///
/// // Or, for a non-default health priority:
/// // node_main!(CameraNode, "camera", critical);
/// ```