net-mesh 0.23.0

High-performance, schema-agnostic, backend-agnostic event bus
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
//! Hierarchical subnet identifier.
//!
//! Encodes a 4-level hierarchy (region/fleet/vehicle/subsystem) into a `u32`.
//! Each level gets 8 bits (256 values). Parent/child/sibling relationships
//! are resolved with bitwise operations at wire speed.
//!
//! ```text
//! subnet_id (u32):
//!   [level_0: 8 bits] [level_1: 8 bits] [level_2: 8 bits] [level_3: 8 bits]
//!    ^region (256)     ^fleet (256)       ^vehicle (256)     ^subsystem (256)
//! ```

/// Maximum number of hierarchy levels.
pub const MAX_DEPTH: u8 = 4;

/// Hierarchical subnet identifier.
///
/// Zero (`0x00000000`) means global / no subnet. Trailing zeros mean
/// "no sub-level specified" — `SubnetId::new(&[3, 7])` represents
/// region=3, fleet=7, with no vehicle or subsystem restriction.
///
/// `Ord` is derived on the inner `u32` representation. The order
/// has no semantic meaning for the hierarchy (it does NOT match
/// ancestor/descendant relationships); it exists purely as a
/// deterministic tiebreaker for callers that need a total order
/// over `SubnetId`s — e.g. `correlation.rs::analyze_subnet_correlation`
/// needs ties at the same depth to resolve consistently across runs
/// rather than depending on `HashMap` iteration order.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    Default,
    PartialOrd,
    Ord,
    serde::Serialize,
    serde::Deserialize,
)]
pub struct SubnetId(u32);

impl SubnetId {
    /// Global / no subnet.
    pub const GLOBAL: Self = Self(0);

    /// Maximum hierarchy depth supported by the encoding — same
    /// value as the module-level `MAX_DEPTH` constant, exposed
    /// as an associated const so operator tooling and the SDK can
    /// reach it through the type without an extra `use`.
    pub const MAX_DEPTH: u8 = MAX_DEPTH;

    /// Create a subnet ID from hierarchy levels (up to 4).
    ///
    /// Levels are packed MSB-first: `&[3, 7]` becomes `0x03_07_00_00`.
    ///
    /// # Panics
    /// Panics if more than 4 levels are provided. For untrusted
    /// input (config / FFI / JSON) prefer [`Self::try_new`].
    #[expect(
        clippy::expect_used,
        reason = "documented panicking variant; try_new is the fallible alternative for untrusted input"
    )]
    pub fn new(levels: &[u8]) -> Self {
        Self::try_new(levels).expect("SubnetId::new: too many levels (use try_new for fallible)")
    }

    /// Fallible variant of [`Self::new`].
    ///
    /// Pre-existing `new` panics on `levels.len() >
    /// MAX_DEPTH`. Returns [`super::SubnetError::TooManyLevels`]
    /// instead so a malformed config doesn't crash the daemon
    /// loader.
    pub fn try_new(levels: &[u8]) -> Result<Self, super::SubnetError> {
        if levels.len() > MAX_DEPTH as usize {
            return Err(super::SubnetError::TooManyLevels {
                got: levels.len(),
                max: MAX_DEPTH,
            });
        }
        let mut val = 0u32;
        for (i, &level) in levels.iter().enumerate() {
            val |= (level as u32) << (24 - i * 8);
        }
        Ok(Self(val))
    }

    /// Create from raw u32 value.
    #[inline]
    pub const fn from_raw(raw: u32) -> Self {
        Self(raw)
    }

    /// Get the raw u32 value.
    #[inline]
    pub const fn raw(self) -> u32 {
        self.0
    }

    /// Extract a specific level (0-3). Returns 0 for unset levels.
    #[inline]
    pub const fn level(self, n: u8) -> u8 {
        if n >= MAX_DEPTH {
            return 0;
        }
        ((self.0 >> (24 - n * 8)) & 0xFF) as u8
    }

    /// Number of non-zero hierarchy levels.
    ///
    /// `SubnetId::new(&[3, 7, 0, 0])` has depth 2.
    pub fn depth(self) -> u8 {
        for d in (0..MAX_DEPTH).rev() {
            if self.level(d) != 0 {
                return d + 1;
            }
        }
        0
    }

    /// Check if this is the global (zero) subnet.
    #[inline]
    pub const fn is_global(self) -> bool {
        self.0 == 0
    }

    /// Get the parent subnet (zero out the deepest non-zero level).
    ///
    /// `SubnetId::new(&[3, 7, 2])` → `SubnetId::new(&[3, 7])`.
    /// `SubnetId::GLOBAL` → `SubnetId::GLOBAL`.
    pub fn parent(self) -> Self {
        let d = self.depth();
        if d == 0 {
            return Self::GLOBAL;
        }
        let mask = Self::mask_for_depth(d - 1);
        Self(self.0 & mask)
    }

    /// Check if `self` is an ancestor of `other` (prefix match).
    ///
    /// Global is ancestor of everything. A subnet is its own ancestor.
    #[inline]
    pub fn is_ancestor_of(self, other: Self) -> bool {
        if self.is_global() {
            return true;
        }
        let d = self.depth();
        let mask = Self::mask_for_depth(d);
        (self.0 & mask) == (other.0 & mask)
    }

    /// Check if two IDs are in the same subnet (identical values).
    #[inline]
    pub const fn is_same_subnet(self, other: Self) -> bool {
        self.0 == other.0
    }

    /// Check if two IDs share the same parent.
    pub fn is_sibling(self, other: Self) -> bool {
        let d1 = self.depth();
        let d2 = other.depth();
        if d1 != d2 || d1 == 0 {
            return false;
        }
        let mask = Self::mask_for_depth(d1 - 1);
        (self.0 & mask) == (other.0 & mask) && self.0 != other.0
    }

    /// Get the bitmask for a given depth.
    ///
    /// depth=0 → 0x00000000 (global)
    /// depth=1 → 0xFF000000
    /// depth=2 → 0xFFFF0000
    /// depth=3 → 0xFFFFFF00
    /// depth=4 → 0xFFFFFFFF
    #[inline]
    pub const fn mask_for_depth(depth: u8) -> u32 {
        match depth {
            0 => 0x00000000,
            1 => 0xFF000000,
            2 => 0xFFFF0000,
            3 => 0xFFFFFF00,
            _ => 0xFFFFFFFF,
        }
    }
}

impl std::fmt::Display for SubnetId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.is_global() {
            write!(f, "global")
        } else {
            let d = self.depth();
            for i in 0..d {
                if i > 0 {
                    write!(f, ".")?;
                }
                write!(f, "{}", self.level(i))?;
            }
            Ok(())
        }
    }
}

/// Inverse of [`std::fmt::Display`]: parses `"global"`
/// (case-insensitive) or a dotted decimal form like `"3.7.2"`
/// (each level a `u8`).
impl std::str::FromStr for SubnetId {
    type Err = super::SubnetError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let trimmed = s.trim();
        if trimmed.eq_ignore_ascii_case("global") {
            return Ok(Self::GLOBAL);
        }
        if trimmed.is_empty() {
            return Err(super::SubnetError::ParseFailed {
                input: s.to_string(),
                reason: "empty".into(),
            });
        }
        let parts: Vec<&str> = trimmed.split('.').collect();
        if parts.len() > MAX_DEPTH as usize {
            return Err(super::SubnetError::TooManyLevels {
                got: parts.len(),
                max: MAX_DEPTH,
            });
        }
        let mut levels: Vec<u8> = Vec::with_capacity(parts.len());
        for p in parts {
            match p.parse::<u8>() {
                Ok(level) => levels.push(level),
                Err(e) => {
                    return Err(super::SubnetError::ParseFailed {
                        input: s.to_string(),
                        reason: format!("level `{p}` not a u8: {e}"),
                    })
                }
            }
        }
        Self::try_new(&levels)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_global() {
        assert!(SubnetId::GLOBAL.is_global());
        assert_eq!(SubnetId::GLOBAL.depth(), 0);
        assert_eq!(SubnetId::GLOBAL.raw(), 0);
    }

    #[test]
    fn test_new() {
        let id = SubnetId::new(&[3, 7]);
        assert_eq!(id.level(0), 3);
        assert_eq!(id.level(1), 7);
        assert_eq!(id.level(2), 0);
        assert_eq!(id.level(3), 0);
        assert_eq!(id.depth(), 2);
        assert!(!id.is_global());
    }

    #[test]
    fn test_full_depth() {
        let id = SubnetId::new(&[1, 2, 3, 4]);
        assert_eq!(id.depth(), 4);
        assert_eq!(id.level(0), 1);
        assert_eq!(id.level(1), 2);
        assert_eq!(id.level(2), 3);
        assert_eq!(id.level(3), 4);
        assert_eq!(id.raw(), 0x01020304);
    }

    #[test]
    fn test_parent() {
        let id = SubnetId::new(&[3, 7, 2]);
        let parent = id.parent();
        assert_eq!(parent, SubnetId::new(&[3, 7]));

        let grandparent = parent.parent();
        assert_eq!(grandparent, SubnetId::new(&[3]));

        let root = grandparent.parent();
        assert_eq!(root, SubnetId::GLOBAL);

        assert_eq!(SubnetId::GLOBAL.parent(), SubnetId::GLOBAL);
    }

    #[test]
    fn test_is_ancestor_of() {
        let region = SubnetId::new(&[3]);
        let fleet = SubnetId::new(&[3, 7]);
        let vehicle = SubnetId::new(&[3, 7, 2]);
        let other_fleet = SubnetId::new(&[3, 8]);
        let other_region = SubnetId::new(&[4]);

        // Global is ancestor of everything
        assert!(SubnetId::GLOBAL.is_ancestor_of(region));
        assert!(SubnetId::GLOBAL.is_ancestor_of(vehicle));

        // Region is ancestor of its fleets and vehicles
        assert!(region.is_ancestor_of(fleet));
        assert!(region.is_ancestor_of(vehicle));

        // Fleet is ancestor of its vehicles
        assert!(fleet.is_ancestor_of(vehicle));

        // But not the other way
        assert!(!vehicle.is_ancestor_of(fleet));
        assert!(!fleet.is_ancestor_of(region));

        // Not ancestor of different branch
        assert!(!region.is_ancestor_of(other_region));
        assert!(!fleet.is_ancestor_of(other_fleet));

        // Self is ancestor of self
        assert!(fleet.is_ancestor_of(fleet));
    }

    #[test]
    fn test_is_sibling() {
        let fleet_a = SubnetId::new(&[3, 7]);
        let fleet_b = SubnetId::new(&[3, 8]);
        let fleet_c = SubnetId::new(&[4, 7]);
        let region = SubnetId::new(&[3]);

        assert!(fleet_a.is_sibling(fleet_b));
        assert!(!fleet_a.is_sibling(fleet_c)); // different region
        assert!(!fleet_a.is_sibling(fleet_a)); // self is not sibling
        assert!(!fleet_a.is_sibling(region)); // different depth
    }

    #[test]
    fn test_display() {
        assert_eq!(format!("{}", SubnetId::GLOBAL), "global");
        assert_eq!(format!("{}", SubnetId::new(&[3])), "3");
        assert_eq!(format!("{}", SubnetId::new(&[3, 7])), "3.7");
        assert_eq!(format!("{}", SubnetId::new(&[1, 2, 3, 4])), "1.2.3.4");
    }

    #[test]
    fn test_from_raw() {
        let id = SubnetId::from_raw(0x03070000);
        assert_eq!(id, SubnetId::new(&[3, 7]));
    }

    #[test]
    fn test_mask_for_depth() {
        assert_eq!(SubnetId::mask_for_depth(0), 0x00000000);
        assert_eq!(SubnetId::mask_for_depth(1), 0xFF000000);
        assert_eq!(SubnetId::mask_for_depth(2), 0xFFFF0000);
        assert_eq!(SubnetId::mask_for_depth(3), 0xFFFFFF00);
        assert_eq!(SubnetId::mask_for_depth(4), 0xFFFFFFFF);
    }

    /// Too many levels must surface as `Err(...)`, not
    /// panic. SubnetId values typically come from config / FFI /
    /// JSON; a malformed entry must not crash the daemon loader.
    #[test]
    fn try_new_rejects_too_many_levels() {
        use super::super::error::SubnetError;
        let err = SubnetId::try_new(&[1, 2, 3, 4, 5]).unwrap_err();
        assert!(
            matches!(err, SubnetError::TooManyLevels { got: 5, max: 4 }),
            "expected TooManyLevels{{got: 5, max: 4}}, got {:?}",
            err
        );
    }

    #[test]
    fn try_new_accepts_max_depth() {
        // Boundary: exactly 4 levels must succeed.
        let id = SubnetId::try_new(&[1, 2, 3, 4]).expect("4 levels must be accepted (boundary)");
        assert_eq!(id, SubnetId::new(&[1, 2, 3, 4]));
    }

    #[test]
    fn try_new_accepts_empty() {
        let id = SubnetId::try_new(&[]).expect("0 levels (GLOBAL) must be accepted");
        assert_eq!(id, SubnetId::GLOBAL);
    }

    #[test]
    fn from_str_round_trips_global_and_dotted_levels() {
        use std::str::FromStr;
        assert_eq!(SubnetId::from_str("global").unwrap(), SubnetId::GLOBAL);
        assert_eq!(SubnetId::from_str("GLOBAL").unwrap(), SubnetId::GLOBAL);
        assert_eq!(SubnetId::from_str("3").unwrap(), SubnetId::new(&[3]));
        assert_eq!(SubnetId::from_str("3.7").unwrap(), SubnetId::new(&[3, 7]));
        assert_eq!(
            SubnetId::from_str("1.2.3.4").unwrap(),
            SubnetId::new(&[1, 2, 3, 4])
        );
        // Display ↔ FromStr round-trip.
        let id = SubnetId::new(&[3, 7, 2]);
        assert_eq!(SubnetId::from_str(&id.to_string()).unwrap(), id);
    }

    #[test]
    fn from_str_rejects_garbage() {
        use super::super::error::SubnetError;
        use std::str::FromStr;
        assert!(matches!(
            SubnetId::from_str("").unwrap_err(),
            SubnetError::ParseFailed { .. }
        ));
        assert!(matches!(
            SubnetId::from_str("256").unwrap_err(),
            SubnetError::ParseFailed { .. }
        ));
        assert!(matches!(
            SubnetId::from_str("1.2.3.4.5").unwrap_err(),
            SubnetError::TooManyLevels { got: 5, max: 4 }
        ));
        assert!(matches!(
            SubnetId::from_str("not-a-number").unwrap_err(),
            SubnetError::ParseFailed { .. }
        ));
    }
}