Skip to main content

astrs_wire/ids/
name.rs

1//! Name-shaped identifiers: `[A-Za-z0-9_.-]+`.
2//!
3//! Node ids, port (data) ids, operator ids, machine labels and parameter keys
4//! all share one grammar. Keeping it narrow is deliberate: these strings end
5//! up in shared-memory segment names (`{dataflow_id}/{node_id}/{generation}`,
6//! §6.2), file paths, metrics labels, log lines and CLI arguments, and every
7//! character outside the set is a quoting hazard in at least one of those.
8//!
9//! **Validation applies on every construction path.** `FromStr`, `TryFrom`,
10//! `serde::Deserialize` and `oxicode::Decode` all funnel through the same
11//! validator, so a hostile peer cannot inject an unvalidated identifier by
12//! encoding one directly into a frame — and the byte cap enforced during
13//! decoding means a forged length prefix cannot allocate without bound even
14//! inside an otherwise legal frame.
15//!
16//! # Examples
17//!
18//! ```
19//! use astrs_wire::{DataId, NodeId};
20//!
21//! let node: NodeId = "camera-01".parse()?;
22//! let port: DataId = "image".parse()?;
23//! assert_eq!(node.as_str(), "camera-01");
24//! assert!("bad id".parse::<NodeId>().is_err());
25//! assert!("".parse::<DataId>().is_err());
26//! # Ok::<(), astrs_wire::IdError>(())
27//! ```
28
29use core::fmt;
30use core::str::FromStr;
31
32use oxicode::de::{Decode, Decoder};
33use oxicode::enc::{Encode, Encoder};
34use serde::{Deserialize, Deserializer, Serialize};
35
36use crate::error::{IdError, IdKind, codec_invalid, preview};
37
38/// The maximum length, in bytes, of a name-shaped identifier.
39///
40/// 255 keeps every identifier inside a single length byte's worth of range and
41/// leaves room for the composite names built from them (a POSIX shared-memory
42/// object name is limited to 255 bytes on Linux and 31 on macOS, so composites
43/// are bounded separately by `astrs-shm`).
44pub const MAX_NAME_LEN: usize = 255;
45
46/// Whether `ch` is admissible inside a name-shaped identifier.
47///
48/// The set is exactly `[A-Za-z0-9_.-]`.
49///
50/// # Examples
51///
52/// ```
53/// use astrs_wire::ids::is_name_char;
54///
55/// assert!(is_name_char('a'));
56/// assert!(is_name_char('_'));
57/// assert!(is_name_char('-'));
58/// assert!(is_name_char('.'));
59/// assert!(!is_name_char('/'));
60/// assert!(!is_name_char(' '));
61/// ```
62#[must_use]
63pub const fn is_name_char(ch: char) -> bool {
64    ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '-')
65}
66
67/// Validates a name-shaped identifier.
68///
69/// # Errors
70///
71/// - [`IdError::Empty`] for the empty string.
72/// - [`IdError::TooLong`] beyond `max` bytes.
73/// - [`IdError::InvalidChar`] for the first character outside the grammar.
74///
75/// # Examples
76///
77/// ```
78/// use astrs_wire::error::IdKind;
79/// use astrs_wire::ids::{MAX_NAME_LEN, validate_name};
80///
81/// assert!(validate_name(IdKind::Node, "camera.left-01", MAX_NAME_LEN).is_ok());
82/// assert!(validate_name(IdKind::Node, "camera/left", MAX_NAME_LEN).is_err());
83/// ```
84pub fn validate_name(kind: IdKind, value: &str, max: usize) -> Result<(), IdError> {
85    if value.is_empty() {
86        return Err(IdError::Empty { kind });
87    }
88    if value.len() > max {
89        return Err(IdError::TooLong {
90            kind,
91            len: value.len(),
92            max,
93        });
94    }
95    for (index, ch) in value.char_indices() {
96        if !is_name_char(ch) {
97            return Err(IdError::InvalidChar {
98                kind,
99                value: preview(value),
100                ch,
101                index,
102            });
103        }
104    }
105    Ok(())
106}
107
108/// Defines a validated, name-shaped identifier newtype.
109///
110/// Every generated type gets the identical construction, comparison,
111/// formatting, `serde` and `oxicode` behaviour, so there is exactly one
112/// validator and one wire encoding to reason about. The macro exists to keep
113/// that guarantee mechanical rather than to save typing.
114macro_rules! define_name_id {
115    (
116        $(#[$meta:meta])*
117        $name:ident, $kind:expr, $noun:literal
118    ) => {
119        $(#[$meta])*
120        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
121        #[serde(transparent)]
122        pub struct $name(String);
123
124        impl $name {
125            /// The identifier family this type belongs to.
126            pub const KIND: IdKind = $kind;
127
128            /// The maximum length in bytes.
129            pub const MAX_LEN: usize = MAX_NAME_LEN;
130
131            #[doc = concat!("Validates `value` and wraps it as a ", $noun, ".")]
132            ///
133            /// # Errors
134            ///
135            /// [`IdError`] if the value is empty, over
136            #[doc = concat!("[`MAX_NAME_LEN`] bytes, or outside `[A-Za-z0-9_.-]`.")]
137            ///
138            /// # Examples
139            ///
140            /// ```
141            #[doc = concat!("use astrs_wire::", stringify!($name), ";")]
142            ///
143            #[doc = concat!("assert!(", stringify!($name), "::new(\"valid-01\").is_ok());")]
144            #[doc = concat!("assert!(", stringify!($name), "::new(\"in valid\").is_err());")]
145            /// ```
146            pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
147                let value = value.into();
148                validate_name(Self::KIND, &value, Self::MAX_LEN)?;
149                Ok(Self(value))
150            }
151
152            #[doc = concat!("Wraps `value` as a ", $noun, ", repairing it if it does not fit the grammar.")]
153            ///
154            /// A **total** constructor, for callers that must produce an
155            /// identifier and have no error path to take: a reserved literal
156            /// this crate itself defines, a metrics label derived from
157            /// operator-supplied text, a fallback in a `Display` impl.
158            /// Characters outside `[A-Za-z0-9_.-]` become `_`, the result is
159            /// truncated to [`MAX_NAME_LEN`] bytes on a character boundary,
160            /// and an empty result becomes `"_"` — so the returned value
161            /// always satisfies the same invariant [`Self::new`] enforces.
162            ///
163            /// Prefer [`Self::new`] wherever a malformed name is a real error
164            /// worth reporting; silent repair is the right answer only when
165            /// there is nobody to report it to.
166            ///
167            /// # Examples
168            ///
169            /// ```
170            #[doc = concat!("use astrs_wire::", stringify!($name), ";")]
171            ///
172            #[doc = concat!("assert_eq!(", stringify!($name), "::sanitized(\"camera.image\").as_str(), \"camera.image\");")]
173            #[doc = concat!("assert_eq!(", stringify!($name), "::sanitized(\"in valid\").as_str(), \"in_valid\");")]
174            #[doc = concat!("assert_eq!(", stringify!($name), "::sanitized(\"\").as_str(), \"_\");")]
175            /// ```
176            #[must_use]
177            pub fn sanitized(value: &str) -> Self {
178                let mut repaired = String::with_capacity(value.len().min(Self::MAX_LEN));
179                for ch in value.chars() {
180                    let ch = if is_name_char(ch) { ch } else { '_' };
181                    if repaired.len() + ch.len_utf8() > Self::MAX_LEN {
182                        break;
183                    }
184                    repaired.push(ch);
185                }
186                if repaired.is_empty() {
187                    repaired.push('_');
188                }
189                Self(repaired)
190            }
191
192            /// The identifier as a string slice.
193            #[must_use]
194            pub fn as_str(&self) -> &str {
195                &self.0
196            }
197
198            /// Consumes the identifier and returns the inner [`String`].
199            #[must_use]
200            pub fn into_string(self) -> String {
201                self.0
202            }
203
204            /// The identifier's length in bytes.
205            #[must_use]
206            pub fn len(&self) -> usize {
207                self.0.len()
208            }
209
210            /// Always `false` — a validated identifier is never empty.
211            ///
212            /// Provided because clippy (rightly) expects any type with `len`
213            /// to offer `is_empty`; the constant answer documents the
214            /// invariant.
215            #[must_use]
216            pub fn is_empty(&self) -> bool {
217                false
218            }
219        }
220
221        impl fmt::Display for $name {
222            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223                f.write_str(&self.0)
224            }
225        }
226
227        impl fmt::Debug for $name {
228            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229                write!(f, "{}({:?})", stringify!($name), self.0)
230            }
231        }
232
233        impl FromStr for $name {
234            type Err = IdError;
235
236            fn from_str(value: &str) -> Result<Self, Self::Err> {
237                Self::new(value)
238            }
239        }
240
241        impl TryFrom<String> for $name {
242            type Error = IdError;
243
244            fn try_from(value: String) -> Result<Self, Self::Error> {
245                Self::new(value)
246            }
247        }
248
249        impl TryFrom<&str> for $name {
250            type Error = IdError;
251
252            fn try_from(value: &str) -> Result<Self, Self::Error> {
253                Self::new(value)
254            }
255        }
256
257        impl AsRef<str> for $name {
258            fn as_ref(&self) -> &str {
259                &self.0
260            }
261        }
262
263        impl core::borrow::Borrow<str> for $name {
264            fn borrow(&self) -> &str {
265                &self.0
266            }
267        }
268
269        impl PartialEq<str> for $name {
270            fn eq(&self, other: &str) -> bool {
271                self.0 == other
272            }
273        }
274
275        impl PartialEq<&str> for $name {
276            fn eq(&self, other: &&str) -> bool {
277                self.0 == *other
278            }
279        }
280
281        impl<'de> Deserialize<'de> for $name {
282            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
283                let raw = String::deserialize(deserializer)?;
284                Self::new(raw).map_err(serde::de::Error::custom)
285            }
286        }
287
288        impl Encode for $name {
289            fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), oxicode::error::Error> {
290                self.0.encode(encoder)
291            }
292        }
293
294        impl<Context> Decode<Context> for $name {
295            fn decode<D: Decoder<Context = Context>>(
296                decoder: &mut D,
297            ) -> Result<Self, oxicode::error::Error> {
298                let raw = String::decode(decoder)?;
299                Self::new(raw).map_err(|err| codec_invalid(err.to_string()))
300            }
301        }
302    };
303}
304
305define_name_id! {
306    /// The id of a node in a dataflow — the `id:` field of a manifest node
307    /// (blueprint §8.3).
308    ///
309    /// Module expansion produces dotted composites (`parent.child`, §8.5),
310    /// which is why `.` is part of the grammar.
311    ///
312    /// # Examples
313    ///
314    /// ```
315    /// use astrs_wire::NodeId;
316    ///
317    /// let id: NodeId = "perception.detector".parse()?;
318    /// assert_eq!(id.as_str(), "perception.detector");
319    /// # Ok::<(), astrs_wire::IdError>(())
320    /// ```
321    NodeId, IdKind::Node, "node id"
322}
323
324define_name_id! {
325    /// The id of an input or output port — a manifest `outputs:` entry, or
326    /// the port half of an `inputs:` entry.
327    ///
328    /// # Examples
329    ///
330    /// ```
331    /// use astrs_wire::DataId;
332    ///
333    /// let id: DataId = "detections".parse()?;
334    /// assert_eq!(id.to_string(), "detections");
335    /// # Ok::<(), astrs_wire::IdError>(())
336    /// ```
337    DataId, IdKind::Data, "data id"
338}
339
340define_name_id! {
341    /// The id of an operator hosted inside a runtime node (blueprint §9.3).
342    ///
343    /// # Examples
344    ///
345    /// ```
346    /// use astrs_wire::OperatorId;
347    ///
348    /// let id: OperatorId = "nms".parse()?;
349    /// assert_eq!(id.as_str(), "nms");
350    /// # Ok::<(), astrs_wire::IdError>(())
351    /// ```
352    OperatorId, IdKind::Operator, "operator id"
353}
354
355define_name_id! {
356    /// A machine label: the `deploy.machine` of a manifest node and the
357    /// human-readable half of a [`crate::DaemonId`].
358    ///
359    /// Hostnames routinely contain hyphens and dots (`robot-arm-01.lab`),
360    /// both of which the grammar admits.
361    ///
362    /// # Examples
363    ///
364    /// ```
365    /// use astrs_wire::MachineName;
366    ///
367    /// let machine: MachineName = "robot-arm-01.lab".parse()?;
368    /// assert_eq!(machine.as_str(), "robot-arm-01.lab");
369    /// # Ok::<(), astrs_wire::IdError>(())
370    /// ```
371    MachineName, IdKind::Machine, "machine name"
372}
373
374define_name_id! {
375    /// A key in a [`crate::Metadata`] parameter map (blueprint §6.1).
376    ///
377    /// Keys beginning with `_` are AstRS-internal and stripped before user
378    /// delivery — see [`crate::ParamKey::is_internal`] and
379    /// [`crate::Metadata::strip_internal`].
380    ///
381    /// # Examples
382    ///
383    /// ```
384    /// use astrs_wire::ParamKey;
385    ///
386    /// let key: ParamKey = "request_id".parse()?;
387    /// assert!(!key.is_internal());
388    /// assert!(ParamKey::new("_schema_hash")?.is_internal());
389    /// # Ok::<(), astrs_wire::IdError>(())
390    /// ```
391    ParamKey, IdKind::Param, "parameter key"
392}
393
394impl ParamKey {
395    /// Whether this key is AstRS-internal.
396    ///
397    /// Internal keys start with `_`; they carry plumbing (the schema hash,
398    /// trace context) and are removed by [`crate::Metadata::strip_internal`]
399    /// before an event reaches user code.
400    ///
401    /// # Examples
402    ///
403    /// ```
404    /// use astrs_wire::ParamKey;
405    ///
406    /// assert!(ParamKey::new("_schema_hash")?.is_internal());
407    /// assert!(!ParamKey::new("seq")?.is_internal());
408    /// # Ok::<(), astrs_wire::IdError>(())
409    /// ```
410    #[must_use]
411    pub fn is_internal(&self) -> bool {
412        self.as_str().starts_with('_')
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
419
420    use super::*;
421    use crate::codec::{WireDecode, WireEncode};
422
423    #[test]
424    fn accepts_the_full_grammar() {
425        let all = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-";
426        assert!(NodeId::new(all).is_ok());
427    }
428
429    #[test]
430    fn rejects_the_empty_string() {
431        for result in [
432            NodeId::new("").err(),
433            DataId::new("").err(),
434            OperatorId::new("").err(),
435            MachineName::new("").err(),
436            ParamKey::new("").err(),
437        ] {
438            assert!(matches!(result, Some(IdError::Empty { .. })));
439        }
440    }
441
442    #[test]
443    fn rejects_characters_outside_the_grammar() {
444        for bad in ["a/b", "a b", "a:b", "a\u{0}b", "café", "a\nb", "a+b", "a*b"] {
445            match NodeId::new(bad) {
446                Err(IdError::InvalidChar { kind, .. }) => assert_eq!(kind, IdKind::Node),
447                other => panic!("{bad:?} should be rejected, got {other:?}"),
448            }
449        }
450    }
451
452    #[test]
453    fn reports_the_first_offending_character_and_offset() {
454        match DataId::new("ok.then/bad") {
455            Err(IdError::InvalidChar { ch, index, .. }) => {
456                assert_eq!(ch, '/');
457                assert_eq!(index, 7);
458            }
459            other => panic!("unexpected {other:?}"),
460        }
461    }
462
463    #[test]
464    fn enforces_the_length_cap() {
465        let at_limit = "a".repeat(MAX_NAME_LEN);
466        assert!(NodeId::new(&at_limit).is_ok());
467
468        let over = "a".repeat(MAX_NAME_LEN + 1);
469        match NodeId::new(&over) {
470            Err(IdError::TooLong { len, max, .. }) => {
471                assert_eq!(len, MAX_NAME_LEN + 1);
472                assert_eq!(max, MAX_NAME_LEN);
473            }
474            other => panic!("unexpected {other:?}"),
475        }
476    }
477
478    #[test]
479    fn error_messages_do_not_echo_unbounded_input() {
480        let hostile = format!("{}/", "z".repeat(10_000));
481        let err = NodeId::new(&hostile).unwrap_err();
482        assert!(err.to_string().len() < 200, "message: {err}");
483    }
484
485    #[test]
486    fn accessors_agree() {
487        let id = NodeId::new("camera").unwrap();
488        assert_eq!(id.as_str(), "camera");
489        assert_eq!(id.as_ref(), "camera");
490        assert_eq!(id.len(), 6);
491        assert!(!id.is_empty());
492        assert_eq!(id.to_string(), "camera");
493        assert_eq!(id, "camera");
494        assert_eq!(id.clone().into_string(), "camera");
495        assert_eq!(format!("{id:?}"), "NodeId(\"camera\")");
496    }
497
498    #[test]
499    fn borrow_enables_str_lookup_in_maps() {
500        use std::collections::BTreeMap;
501
502        let mut map = BTreeMap::new();
503        map.insert(NodeId::new("camera").unwrap(), 1);
504        assert_eq!(map.get("camera"), Some(&1));
505    }
506
507    #[test]
508    fn ordering_is_lexicographic() {
509        let mut ids = [
510            NodeId::new("zeta").unwrap(),
511            NodeId::new("alpha").unwrap(),
512            NodeId::new("Beta").unwrap(),
513        ];
514        ids.sort();
515        assert_eq!(ids[0].as_str(), "Beta");
516        assert_eq!(ids[1].as_str(), "alpha");
517        assert_eq!(ids[2].as_str(), "zeta");
518    }
519
520    #[test]
521    fn codec_round_trips() {
522        let id = DataId::new("image.raw-0").unwrap();
523        let bytes = id.encode_to_vec().unwrap();
524        assert_eq!(DataId::decode_exact(&bytes).unwrap(), id);
525    }
526
527    #[test]
528    fn decoding_validates_just_like_parsing() {
529        // A peer that encodes a raw String where a NodeId belongs must be
530        // rejected: the validator runs on the decode path too.
531        let hostile = "not a valid id".to_owned().encode_to_vec().unwrap();
532        let err = NodeId::decode_exact(&hostile).unwrap_err();
533        assert!(matches!(err, crate::WireError::Codec(_)), "{err:?}");
534    }
535
536    #[test]
537    fn decoding_enforces_the_length_cap() {
538        let hostile = "a".repeat(MAX_NAME_LEN + 1).encode_to_vec().unwrap();
539        assert!(NodeId::decode_exact(&hostile).is_err());
540    }
541
542    #[test]
543    fn decoding_rejects_the_empty_string() {
544        let empty = String::new().encode_to_vec().unwrap();
545        assert!(DataId::decode_exact(&empty).is_err());
546    }
547
548    #[test]
549    fn serde_round_trips_as_a_bare_string() {
550        let id = NodeId::new("planner").unwrap();
551        let json = serde_json::to_string(&id).unwrap();
552        assert_eq!(json, "\"planner\"");
553        assert_eq!(serde_json::from_str::<NodeId>(&json).unwrap(), id);
554    }
555
556    #[test]
557    fn serde_deserialization_validates() {
558        assert!(serde_json::from_str::<NodeId>("\"has space\"").is_err());
559        assert!(serde_json::from_str::<NodeId>("\"\"").is_err());
560    }
561
562    #[test]
563    fn try_from_variants_are_equivalent() {
564        assert_eq!(
565            NodeId::try_from("x").unwrap(),
566            NodeId::try_from("x".to_owned()).unwrap()
567        );
568        assert_eq!("x".parse::<NodeId>().unwrap(), NodeId::new("x").unwrap());
569    }
570
571    #[test]
572    fn each_type_reports_its_own_kind() {
573        assert_eq!(NodeId::KIND, IdKind::Node);
574        assert_eq!(DataId::KIND, IdKind::Data);
575        assert_eq!(OperatorId::KIND, IdKind::Operator);
576        assert_eq!(MachineName::KIND, IdKind::Machine);
577        assert_eq!(ParamKey::KIND, IdKind::Param);
578
579        let err = DataId::new("!").unwrap_err();
580        assert_eq!(err.kind(), IdKind::Data);
581    }
582
583    #[test]
584    fn param_keys_flag_internal_names() {
585        assert!(ParamKey::new("_schema_hash").unwrap().is_internal());
586        assert!(ParamKey::new("_trace").unwrap().is_internal());
587        assert!(!ParamKey::new("seq").unwrap().is_internal());
588        assert!(!ParamKey::new("goal.id").unwrap().is_internal());
589    }
590
591    #[test]
592    fn name_char_predicate_matches_the_validator() {
593        for byte in 0u8..=127 {
594            let ch = char::from(byte);
595            let mut buffer = String::from("a");
596            buffer.push(ch);
597            let accepted = NodeId::new(&buffer).is_ok();
598            assert_eq!(accepted, is_name_char(ch), "disagreement for {ch:?}");
599        }
600    }
601
602    #[test]
603    fn sanitized_keeps_a_legal_name_unchanged() {
604        for value in ["camera", "astrs.status", "node-01", "a_b.c-d"] {
605            assert_eq!(NodeId::sanitized(value).as_str(), value);
606            assert_eq!(DataId::sanitized(value).as_str(), value);
607        }
608    }
609
610    #[test]
611    fn sanitized_repairs_illegal_characters() {
612        assert_eq!(NodeId::sanitized("in valid").as_str(), "in_valid");
613        assert_eq!(NodeId::sanitized("a/b").as_str(), "a_b");
614        assert_eq!(NodeId::sanitized("a=b\0c").as_str(), "a_b_c");
615    }
616
617    #[test]
618    fn sanitized_never_returns_an_empty_name() {
619        assert_eq!(NodeId::sanitized("").as_str(), "_");
620        assert_eq!(DataId::sanitized("").as_str(), "_");
621    }
622
623    #[test]
624    fn sanitized_truncates_on_a_character_boundary() {
625        let long = "\u{00e9}".repeat(MAX_NAME_LEN);
626        let repaired = NodeId::sanitized(&long);
627        assert!(repaired.len() <= MAX_NAME_LEN);
628        // Every source character is multi-byte and therefore illegal, so each
629        // becomes a single-byte '_'; the result fills the budget exactly.
630        assert_eq!(repaired.as_str(), "_".repeat(MAX_NAME_LEN));
631    }
632
633    #[test]
634    fn sanitized_output_always_passes_the_validator() {
635        for value in [
636            "",
637            "  ",
638            "a/b/c",
639            "\u{1f600}",
640            &"x".repeat(MAX_NAME_LEN * 3),
641        ] {
642            let repaired = NodeId::sanitized(value);
643            assert!(
644                NodeId::new(repaired.as_str()).is_ok(),
645                "{value:?} repaired to {repaired:?}, which is still invalid"
646            );
647        }
648    }
649}