mecha10-core 0.6.5

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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//! 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_core::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"
/// );
/// ```
#[macro_export]
macro_rules! run_node_simple {
    ($node_type:ty, $node_name:expr, $env_var:expr, $config_file:expr, $env_prefix:expr) => {
        pub async fn run() -> $crate::error::Result<()> {
            let config = $crate::config::load_config_with_fallback(
                $env_var,
                $config_file,
                $env_prefix,
                Some(<$node_type as $crate::node::NodeImpl>::Config::default()),
            )?;

            let ctx = $crate::context::Context::new($node_name);

            $crate::node::run_node::<$node_type>(config, ctx, $crate::node::HealthReportingConfig::default()).await
        }
    };
}

/// 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_core::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()));
/// ```
#[macro_export]
macro_rules! builder_setter {
    ($(#[$meta:meta])* assign, $name:ident, $field:ident, $ty:ty) => {
        $(#[$meta])*
        pub fn $name(mut self, $field: $ty) -> Self {
            self.$field = $field;
            self
        }
    };
    ($(#[$meta:meta])* assign, $name:ident, $holder:ident.$field:ident, $ty:ty) => {
        $(#[$meta])*
        pub fn $name(mut self, $field: $ty) -> Self {
            self.$holder.$field = $field;
            self
        }
    };
    ($(#[$meta:meta])* into, $name:ident, $field:ident, $ty:ty) => {
        $(#[$meta])*
        pub fn $name(mut self, $field: $ty) -> Self {
            self.$field = $field.into();
            self
        }
    };
    ($(#[$meta:meta])* into, $name:ident, $holder:ident.$field:ident, $ty:ty) => {
        $(#[$meta])*
        pub fn $name(mut self, $field: $ty) -> Self {
            self.$holder.$field = $field.into();
            self
        }
    };
    ($(#[$meta:meta])* into_some, $name:ident, $field:ident, $ty:ty) => {
        $(#[$meta])*
        pub fn $name(mut self, $field: $ty) -> Self {
            self.$field = Some($field.into());
            self
        }
    };
    ($(#[$meta:meta])* into_some, $name:ident, $holder:ident.$field:ident, $ty:ty) => {
        $(#[$meta])*
        pub fn $name(mut self, $field: $ty) -> Self {
            self.$holder.$field = Some($field.into());
            self
        }
    };
    ($(#[$meta:meta])* push, $name:ident, $field:ident, $ty:ty) => {
        $(#[$meta])*
        pub fn $name(mut self, value: $ty) -> Self {
            self.$field.push(value.into());
            self
        }
    };
    ($(#[$meta:meta])* insert, $name:ident, $field:ident, $key_ty:ty, $val_ty:ty) => {
        $(#[$meta])*
        pub fn $name(mut self, key: $key_ty, value: $val_ty) -> Self {
            self.$field.insert(key.into(), value.into());
            self
        }
    };
    ($(#[$meta:meta])* insert, $name:ident, $holder:ident.$field:ident, $key_ty:ty, $val_ty:ty) => {
        $(#[$meta])*
        pub fn $name(mut self, key: $key_ty, value: $val_ty) -> Self {
            self.$holder.$field.insert(key.into(), value.into());
            self
        }
    };
    // Boxes a predicate/mapper closure into `Option<Box<dyn $bound>>`. Backs
    // `StreamBuilder::filter`/`map` and `PublishBuilder::when`, which cargo-dupes flagged as an
    // exact duplicate of each other (same "box the closure into an Option field, return self"
    // shape, differing only in the field and the `Fn` bound).
    ($(#[$meta:meta])* predicate, $name:ident, $field:ident, $($bound:tt)+) => {
        $(#[$meta])*
        pub fn $name<F>(mut self, value: F) -> Self
        where
            F: $($bound)+,
        {
            self.$field = Some(Box::new(value));
            self
        }
    };
    // Stores a `Duration` as `Option<u64>` milliseconds. Backs `SubscribeBuilder::throttle` and
    // `PublishBuilder::throttle` (packages/core/src/topics.rs), which cargo-dupes flagged as an
    // exact duplicate of each other.
    ($(#[$meta:meta])* duration_millis, $name:ident, $field:ident) => {
        $(#[$meta])*
        pub fn $name(mut self, duration: std::time::Duration) -> Self {
            self.$field = Some(duration.as_millis() as u64);
            self
        }
    };
    // Clamps an f32 into `[$min, $max]` before storing it. Backs
    // `YoloDetectorBuilder::confidence_threshold`/`iou_threshold`,
    // `DeepSortBuilder::max_iou_distance`/`max_cosine_distance` and
    // `TrackerBuilder::max_iou_distance` (packages/vision/src/{yolo,deepsort,tracker}.rs),
    // which cargo-dupes flagged as an exact duplicate of each other.
    ($(#[$meta:meta])* clamp, $name:ident, $holder:ident.$field:ident, $min:expr, $max:expr) => {
        $(#[$meta])*
        pub fn $name(mut self, $field: f32) -> Self {
            self.$holder.$field = $field.clamp($min, $max);
            self
        }
    };
}

/// Generates the `build(self) -> anyhow::Result<$node>` method shared by this
/// workspace's node builders (`Ok($node::new(self.config))`). Backs
/// `YoloDetectorBuilder::build`, `DeepSortBuilder::build` and
/// `TrackerBuilder::build` (packages/vision/src/{yolo,deepsort,tracker}.rs),
/// which cargo-dupes flagged as an exact duplicate of each other.
#[macro_export]
macro_rules! builder_build {
    ($(#[$meta:meta])* $node:ty) => {
        $(#[$meta])*
        pub fn build(self) -> anyhow::Result<$node> {
            Ok(<$node>::new(self.config))
        }
    };
}

/// 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)");
/// ```
#[macro_export]
macro_rules! enum_str_method {
    (
        $(#[$meta:meta])*
        $vis:vis fn $method:ident($enum:ident) -> $ret:ty {
            $($variant:ident => $lit:literal),+ $(,)?
        }
    ) => {
        impl $enum {
            $(#[$meta])*
            $vis fn $method(&self) -> $ret {
                match self {
                    $(Self::$variant => $lit,)+
                }
            }
        }
    };
}

/// Generate a `std::fmt::Display` impl for a fieldless-variant enum whose textual form is
/// simply "one string literal per variant" - the same shape `enum_str_method!` covers for
/// inherent accessor methods, just wired into the `Display` trait instead.
///
/// Eliminates the `impl std::fmt::Display for $Enum { fn fmt(...) { let s = match self { ... };
/// write!(f, "{s}") } }` boilerplate that was hand-duplicated across this workspace's config
/// enums (`Provider`, `PixelFormat`, `MockPattern`, ...). Only fits the plain
/// match-each-variant-to-a-literal shape; if a variant needs interpolated fields or computed
/// text, leave that impl hand-written.
///
/// # Examples
///
/// ```rust
/// use mecha10_core::enum_display_via_str;
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// enum Pattern {
///     Gradient,
///     Solid,
/// }
///
/// enum_display_via_str!(Pattern {
///     Gradient => "gradient",
///     Solid => "solid",
/// });
///
/// assert_eq!(Pattern::Gradient.to_string(), "gradient");
/// ```
#[macro_export]
macro_rules! enum_display_via_str {
    ($enum:ident { $($variant:ident => $lit:literal),+ $(,)? }) => {
        impl std::fmt::Display for $enum {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                let s = match self {
                    $(Self::$variant => $lit,)+
                };
                write!(f, "{s}")
            }
        }
    };
}

/// Generate a `std::fmt::Debug` impl that reports a fixed set of named fields via
/// [`std::fmt::Formatter::debug_struct`].
///
/// Eliminates the `f.debug_struct("$Struct").field("a", &self.a).field("b", &self.b).finish()`
/// boilerplate hand-duplicated across this workspace's node structs (`TeleopNode`,
/// `SimulatorNode`, `CameraNode`, `VideoStreamerNode`, ...) - each reports a different subset of
/// its fields (sometimes through an accessor expression like `counter.load(Ordering::Relaxed)`
/// rather than a bare field), so the macro takes a `"label" => field[.accessor(...)]` pair per
/// reported field. The `self.` prefix is generated by the macro itself rather than typed by the
/// caller - a `self` token written in the *macro invocation* has no enclosing method at that
/// point (the invocation sits at item scope, expanding into its own `fn fmt(&self, ..)`), so
/// hygiene can never resolve it; only a `self` written inside the macro's own definition (right
/// next to the `&self` it binds to `fmt`) can.
///
/// # Examples
///
/// ```rust
/// use mecha10_core::debug_struct_fields;
///
/// struct Widget {
///     name: String,
///     count: u32,
/// }
///
/// debug_struct_fields!(Widget {
///     "name" => name,
///     "count" => count,
/// });
///
/// let w = Widget { name: "gizmo".into(), count: 3 };
/// assert_eq!(format!("{w:?}"), "Widget { name: \"gizmo\", count: 3 }");
/// ```
#[macro_export]
macro_rules! debug_struct_fields {
    ($struct:ident { $($label:literal => $field:ident $(. $method:ident ( $($arg:expr),* $(,)? ))?),+ $(,)? }) => {
        impl std::fmt::Debug for $struct {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_struct(stringify!($struct))
                    $(.field($label, &self.$field $(. $method ( $($arg),* ))?))+
                    .finish()
            }
        }
    };
}

/// Generate a `Default` impl that builds each field from an expression, verbatim.
///
/// Eliminates the `impl Default for $Struct { fn default() -> Self { Self { $field: $value, .. }
/// } }` boilerplate hand-duplicated across this workspace's config structs - e.g.
/// `ListenerConfig`/`SpeakerConfig` (each field defaulted through its own per-crate
/// `default_*()` helper) and `ModelConfig` in the `rl`/`object-detector` nodes (identical
/// `{name, path, source, version}` shape, differing only in which crate-local
/// `default_model_name`/`default_model_path` the expressions call). Unlike
/// `new_with_defaults!` above (a `new(...)` constructor taking some fields as arguments), every
/// field here comes from an expression, not a parameter - the whole point is that `Default`
/// takes no arguments.
///
/// # Examples
///
/// ```rust
/// use mecha10_core::default_struct_fields;
///
/// #[derive(Debug, PartialEq)]
/// struct Config {
///     retries: u32,
///     label: String,
/// }
///
/// fn default_retries() -> u32 {
///     3
/// }
///
/// default_struct_fields!(Config {
///     retries: default_retries(),
///     label: "default".to_string(),
/// });
///
/// assert_eq!(
///     Config::default(),
///     Config { retries: 3, label: "default".to_string() }
/// );
/// ```
#[macro_export]
macro_rules! default_struct_fields {
    ($struct:ident { $($field:ident: $value:expr),+ $(,)? }) => {
        impl Default for $struct {
            fn default() -> Self {
                Self {
                    $($field: $value,)+
                }
            }
        }
    };
}

/// Generate the body of a `NodeImpl::init` that logs a message, then builds `Self` by zeroing
/// one counter field and moving `config` in verbatim.
///
/// Eliminates the `info!(...); Ok(Self { $count_field: 0, config })` boilerplate duplicated
/// between the example `listener`/`speaker` nodes' `init` methods - they log a different
/// message about a different config field, but both otherwise just zero their one running
/// counter and stash the config. Expands to the function *body* only (not the surrounding `async
/// fn init(...) -> Result<Self> { ... }` signature) so `#[async_trait]` still sees a real `async
/// fn` to rewrite - it operates on the impl block's raw tokens before nested macros expand, so a
/// macro that generated the whole item wouldn't get picked up by the trait's desugaring.
///
/// # Examples
///
/// ```rust
/// use mecha10_core::prelude::*;
/// use mecha10_core::zeroed_count_init_body;
///
/// #[derive(Debug, Clone, Deserialize, Serialize, Default)]
/// struct WidgetConfig {
///     label: String,
/// }
///
/// #[derive(Debug)]
/// struct WidgetNode {
///     count: u64,
///     config: WidgetConfig,
/// }
///
/// #[async_trait]
/// impl NodeImpl for WidgetNode {
///     type Config = WidgetConfig;
///
///     async fn init(config: Self::Config) -> Result<Self> {
///         zeroed_count_init_body!(count, config, "Initializing widget '{}'", config.label)
///     }
///
///     async fn run(&mut self, ctx: &Context) -> Result<()> {
///         Ok(())
///     }
/// }
/// ```
#[macro_export]
macro_rules! zeroed_count_init_body {
    ($count_field:ident, $config:ident, $($log_arg:tt)*) => {{
        $crate::prelude::info!($($log_arg)*);
        Ok(Self {
            $count_field: 0,
            $config,
        })
    }};
}

/// Generate a `NodeImpl::shutdown` that logs a "shutting down" message, then logs a final
/// counters summary before returning `Ok(())`.
///
/// Eliminates the `info!("Shutting down ... node"); info!("Final: {} ..., {} ...", ...); Ok(())`
/// boilerplate duplicated between `camera` and `video-streamer`'s `shutdown` methods - both log
/// a startup-shutdown message plus a final pair of atomically-tracked frame counters, differing
/// only in the log text and which counters they report. Expands to the function *body* only (not
/// the surrounding `async fn shutdown(&mut self) -> Result<()> { ... }` signature) so
/// `#[async_trait]` still sees a real `async fn` to rewrite - it operates on the impl block's raw
/// tokens before nested macros expand, so a macro that generated the whole item wouldn't get
/// picked up by the trait's desugaring.
///
/// # Examples
///
/// ```rust
/// use mecha10_core::log_shutdown_fn_body;
/// use mecha10_core::prelude::*;
///
/// #[derive(Debug, Clone, Deserialize, Serialize, Default)]
/// struct WidgetConfig;
///
/// #[derive(Debug)]
/// struct WidgetNode {
///     config: WidgetConfig,
///     processed: u64,
/// }
///
/// #[async_trait]
/// impl NodeImpl for WidgetNode {
///     type Config = WidgetConfig;
///
///     async fn init(config: Self::Config) -> Result<Self> {
///         Ok(Self { config, processed: 0 })
///     }
///
///     async fn run(&mut self, ctx: &Context) -> Result<()> {
///         Ok(())
///     }
///
///     async fn shutdown(&mut self) -> Result<()> {
///         log_shutdown_fn_body!("Shutting down widget node", "Final: {} processed", self.processed)
///     }
/// }
/// ```
#[macro_export]
macro_rules! log_shutdown_fn_body {
    ($shutdown_msg:literal, $($final_log_arg:tt)*) => {{
        $crate::prelude::info!($shutdown_msg);
        $crate::prelude::info!($($final_log_arg)*);
        Ok(())
    }};
}

/// Call [`crate::error::preflight_model_exists`] against `$model.path`, for a node config's
/// "does this model file exist before we spawn ONNX Runtime" preflight check.
///
/// Eliminates the `preflight_model_exists(Path::new(&self.model.path), $label, &[...])`
/// call-site boilerplate duplicated between the `rl` and `object-detector` nodes' `preflight`
/// methods - they use a different label and different remediation copy, but call into the same
/// shared check with the same shape.
///
/// # Examples
///
/// ```rust
/// use mecha10_core::model_preflight;
///
/// struct Model { path: String, name: String }
/// struct Config { model: Model }
///
/// impl Config {
///     fn preflight(&self) -> mecha10_core::error::Result<()> {
///         model_preflight!(self.model, "Model", [
///             format!("Pull it: mecha10 model pull {}", self.model.name),
///             "Check \"model.path\" points at the downloaded file".to_string(),
///         ])
///     }
/// }
/// ```
#[macro_export]
macro_rules! model_preflight {
    ($model:expr, $label:literal, [$($hint:expr),+ $(,)?]) => {
        $crate::error::preflight_model_exists(
            std::path::Path::new(&$model.path),
            $label,
            &[$($hint),+],
        )
    };
}

/// Generate a camera-frame decode function that delegates to
/// `mecha10_camera_codec::decode_camera_image`.
///
/// Eliminates the `mecha10_camera_codec::decode_camera_image(&msg.format, &msg.image_bytes,
/// msg.width, msg.height, h264_decoder)` one-line delegation duplicated between the
/// `image-classifier` and `object-detector` nodes - both already route through the shared
/// `mecha10_camera_codec` crate documented as the single source of truth for the stateful h264
/// decode path (see its crate doc), so the only thing left per-crate is this wrapper's name and
/// signature (a free fn vs. an inherent static method).
///
/// # Examples
///
/// ```rust,ignore
/// use mecha10_core::camera_image_decode_fn;
///
/// camera_image_decode_fn!(
///     fn decode_camera_image(&CameraImage, &std::sync::Mutex<mecha10_camera_codec::H264DecoderState>) -> Result<DynamicImage>
/// );
/// ```
#[macro_export]
macro_rules! camera_image_decode_fn {
    ($vis:vis fn $name:ident($msg_ty:ty, $decoder_ty:ty) -> $ret:ty) => {
        $vis fn $name(msg: $msg_ty, h264_decoder: $decoder_ty) -> $ret {
            mecha10_camera_codec::decode_camera_image(&msg.format, &msg.image_bytes, msg.width, msg.height, h264_decoder)
        }
    };
}

/// Generate an `async fn publish_odometry(&self, ctx: &Context) -> Result<()>` that builds an
/// odometry message from `self`'s dead-reckoned pose/command fields and publishes it to
/// `$topic`.
///
/// Eliminates the `Odometry { timestamp: now_micros(), x: self.x, y: self.y, theta: self.theta,
/// linear_vel: self.cmd_linear, angular_vel: self.cmd_angular }; ctx.publish_to(...).await?`
/// boilerplate hand-duplicated between `motor_fake` and `motor` - both track the same
/// `x`/`y`/`theta`/`cmd_linear`/`cmd_angular` fields (see [`crate::differential_drive_odometry_impl`]),
/// but publish to their own crate-local `Odometry` type over their own `topics::ODOM` constant,
/// so those stay macro parameters rather than being unified.
///
/// # Examples
///
/// ```rust,ignore
/// use mecha10_core::odometry_publish_fn;
///
/// odometry_publish_fn!(Odometry, topics::ODOM);
/// ```
#[macro_export]
macro_rules! odometry_publish_fn {
    ($odom_ty:ident, $topic:expr) => {
        async fn publish_odometry(&self, ctx: &$crate::context::Context) -> $crate::error::Result<()> {
            let odom = $odom_ty {
                timestamp: $crate::prelude::now_micros(),
                x: self.x,
                y: self.y,
                theta: self.theta,
                linear_vel: self.cmd_linear,
                angular_vel: self.cmd_angular,
            };

            ctx.publish_to($topic, &odom).await?;
            Ok(())
        }
    };
}

/// Generate a `pub fn new(...) -> Self` constructor that assigns its arguments verbatim,
/// optionally defaulting any remaining fields.
///
/// Eliminates the `pub fn new($($field: $ty),+) -> Self { Self { $($field),+ } }` boilerplate
/// (with an optional `, $($default_field: $default_value),+` tail) repeated across this
/// workspace's "wrap these fields, nothing else" structs (`Obstacle`, `Template`,
/// `ProcessServiceController`, `BatchBuilder`) and "wrap a payload plus a bit of optional
/// metadata" structs (`BehaviorExecutor`, `SubsumptionLayer`, `WeightedModel`), which cargo-dupes
/// flagged as an exact duplicate of each other — same "assign these fields as-is[, default the
/// rest]" shape, differing only in field names/types.
///
/// # Examples
///
/// ```rust
/// use mecha10_core::new_with_defaults;
///
/// struct Point {
///     x: f32,
///     y: f32,
/// }
///
/// impl Point {
///     new_with_defaults!(
///         /// Create a new point.
///         pub fn new(x: f32, y: f32) -> Self
///     );
/// }
///
/// let point = Point::new(1.0, 2.0);
/// assert_eq!(point.x, 1.0);
/// assert_eq!(point.y, 2.0);
///
/// struct Layer {
///     priority: u8,
///     name: Option<String>,
/// }
///
/// impl Layer {
///     new_with_defaults!(
///         /// Create a new layer with the given priority.
///         pub fn new(priority: u8) -> Self {
///             name: None
///         }
///     );
/// }
///
/// let layer = Layer::new(5);
/// assert_eq!(layer.priority, 5);
/// assert_eq!(layer.name, None);
/// ```
#[macro_export]
macro_rules! new_with_defaults {
    (
        $(#[$meta:meta])*
        $vis:vis fn new($($field:ident : $ty:ty),+ $(,)?) -> Self
    ) => {
        $(#[$meta])*
        $vis fn new($($field: $ty),+) -> Self {
            Self {
                $($field,)+
            }
        }
    };
    (
        $(#[$meta:meta])*
        $vis:vis fn new($($field:ident : $ty:ty),+ $(,)?) -> Self {
            $($default_field:ident : $default_value:expr),+ $(,)?
        }
    ) => {
        $(#[$meta])*
        $vis fn new($($field: $ty),+) -> Self {
            Self {
                $($field,)+
                $($default_field: $default_value,)+
            }
        }
    };
}

/// 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);
/// ```
#[macro_export]
macro_rules! node_main {
    ($node_type:ty, $node_name:expr) => {
        $crate::node_main!($node_type, $node_name, normal);
    };
    ($node_type:ty, $node_name:expr, $health:ident) => {
        pub async fn run() -> $crate::error::Result<()> {
            let ctx = $crate::context::Context::new($node_name).await?;
            let config: <$node_type as $crate::node::NodeImpl>::Config = ctx.load_node_config($node_name).await?;
            $crate::node::run_node::<$node_type>(config, ctx, $crate::node::HealthReportingConfig::$health()).await
        }
    };
}

#[macro_export]
macro_rules! run_node_with_instance {
    ($node_type:ty, $node_name:expr, $instance_env:expr, $env_var:expr, $config_file:expr, $env_prefix:expr) => {
        pub async fn run() -> $crate::error::Result<()> {
            let config = $crate::config::load_config_with_fallback(
                $env_var,
                $config_file,
                $env_prefix,
                Some(<$node_type as $crate::node::NodeImpl>::Config::default()),
            )?;

            let mut ctx = $crate::context::Context::new($node_name).await?;

            if let Ok(instance) = std::env::var($instance_env) {
                ctx = ctx.with_instance(&instance);
                $crate::prelude::info!("Running node '{}' with instance '{}'", $node_name, instance);
            } else {
                $crate::prelude::info!("Running node '{}' (no instance)", $node_name);
            }

            $crate::node::run_node::<$node_type>(config, ctx, $crate::node::HealthReportingConfig::default()).await
        }
    };
}

/// Generate the `pub async fn run() -> Result<(), Box<dyn Error + Send + Sync>>` entry point
/// used by the generated node registry, for nodes whose top-level type constructs itself with
/// a bare `new().await` (no config loading through `Context`) and then drives itself to
/// completion via `run().await`.
///
/// Eliminates the `let node = $NodeType::new().await?; node.run().await?; Ok(())` boilerplate
/// that was hand-duplicated between `diagnostics` and `websocket-bridge`'s crate roots -
/// distinct from `node_main!`/`run_node_with_instance!` above, which both go through
/// `Context`/`NodeImpl::Config` and `run_node::<T>()`.
///
/// # Examples
///
/// ```rust
/// use mecha10_core::new_then_run_fn;
///
/// struct EchoNode;
///
/// impl EchoNode {
///     async fn new() -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
///         Ok(Self)
///     }
///
///     async fn run(self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
///         Ok(())
///     }
/// }
///
/// new_then_run_fn!(EchoNode);
/// ```
#[macro_export]
macro_rules! new_then_run_fn {
    ($node_type:ty) => {
        /// Run the node.
        ///
        /// This is the entry point used by the generated node registry.
        pub async fn run() -> std::result::Result<(), Box<dyn std::error::Error + Send + Sync>> {
            let node = <$node_type>::new().await?;
            node.run().await?;
            Ok(())
        }
    };
}