Skip to main content

zenkey_model/
grammar.rs

1//! The zk2 key grammar (r3 §3.1, r3.3 D3).
2//!
3//! ```text
4//! zk2/<system>/<service>/<iface>.v<major>/<kind>/<resource…>              data
5//! zk2/<system>/<service>/@zk/instance/<instance>                          instance token + descriptor
6//! zk2/<system>/<service>/@zk/alive/<iface>.v<major>/<instance>/<fp16>     interface token
7//! zk2/<system>/<service>/@zk/member/<iface>.v<major>/<member>/<epoch>     member token (r3.3 D9b)
8//! zk2/@zk/contract/<iface>.v<major>/<sha256>                              contract bundle
9//! ```
10//!
11//! Positions 1–5 have fixed arity, so `zk2/*/*/*/state/**` is exact. Every
12//! key here is *base-relative*: a deployment's optional namespace is added
13//! by the Zenoh session, never spelled by code.
14
15use std::fmt;
16use std::str::FromStr;
17
18use thiserror::Error;
19use zenoh_keyexpr::OwnedKeyExpr;
20
21use crate::chunk::{is_ident, is_lower_hex, is_plain_chunk};
22
23/// The grammar major: the first chunk of every zk2 key. A plain chunk,
24/// never verbatim (v1's `@v1` broke zenoh-ext's `@adv` parsing).
25pub const GRAMMAR: &str = "zk2";
26/// The control token, verbatim, at position 4 (per service) or 2 (contracts).
27pub const CONTROL: &str = "@zk";
28
29/// Why a key, or one of its parts, was refused.
30#[derive(Debug, Clone, PartialEq, Eq, Error)]
31pub enum KeyError {
32    #[error("{what} {value:?} is not a plain chunk ([a-z0-9]([a-z0-9._-]*[a-z0-9])?)")]
33    NotPlain { what: &'static str, value: String },
34    #[error("interface {0:?} is not <name>.v<major> with name segments [a-z][a-z0-9_]*")]
35    Interface(String),
36    #[error("{what} {value:?} must be {len} lowercase hex digits")]
37    Hex {
38        what: &'static str,
39        value: String,
40        len: usize,
41    },
42    #[error("unknown kind token {0:?} (stream, @stream, state, @state, events, @op)")]
43    Kind(String),
44    #[error("{0:?} is not a zk2 key: {1}")]
45    Shape(String, &'static str),
46    #[error("{0:?} is not a valid Zenoh key expression: {1}")]
47    KeyExpr(String, String),
48}
49
50/// A system or service name: one plain chunk, chosen by deployment.
51#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
52pub struct Name(String);
53
54impl Name {
55    pub fn new(what: &'static str, s: &str) -> Result<Self, KeyError> {
56        if is_plain_chunk(s) {
57            Ok(Self(s.to_owned()))
58        } else {
59            Err(KeyError::NotPlain {
60                what,
61                value: s.to_owned(),
62            })
63        }
64    }
65    #[must_use]
66    pub fn as_str(&self) -> &str {
67        &self.0
68    }
69}
70
71impl fmt::Display for Name {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str(&self.0)
74    }
75}
76
77/// A service address, `<system>/<service>`.
78#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
79pub struct Addr {
80    pub system: Name,
81    pub service: Name,
82}
83
84impl Addr {
85    pub fn new(system: &str, service: &str) -> Result<Self, KeyError> {
86        Ok(Self {
87            system: Name::new("system", system)?,
88            service: Name::new("service", service)?,
89        })
90    }
91}
92
93impl FromStr for Addr {
94    type Err = KeyError;
95    /// Parses `<system>/<service>`.
96    fn from_str(s: &str) -> Result<Self, KeyError> {
97        let (sys, svc) = s.split_once('/').ok_or(KeyError::Shape(
98            s.to_owned(),
99            "an address is <system>/<service>",
100        ))?;
101        Self::new(sys, svc)
102    }
103}
104
105impl fmt::Display for Addr {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        write!(f, "{}/{}", self.system, self.service)
108    }
109}
110
111/// An interface identity: a dotted name plus a major, spelled
112/// `<name>.v<major>` in a key (`nav.v2`, `tc.netem.v1`).
113#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
114pub struct IfaceId {
115    name: String,
116    major: u32,
117}
118
119impl IfaceId {
120    /// `name` is one or more `[a-z][a-z0-9_]*` segments joined by `.`, and
121    /// may not itself end in `.v<digits>` (that would make the chunk
122    /// ambiguous).
123    pub fn new(name: &str, major: u32) -> Result<Self, KeyError> {
124        let segments_ok = !name.is_empty() && name.split('.').all(is_ident);
125        let ends_like_major = name
126            .rsplit_once('.')
127            .is_some_and(|(_, last)| is_major_segment(last));
128        if segments_ok && !ends_like_major && !is_major_segment(name) {
129            Ok(Self {
130                name: name.to_owned(),
131                major,
132            })
133        } else {
134            Err(KeyError::Interface(name.to_owned()))
135        }
136    }
137    #[must_use]
138    pub fn name(&self) -> &str {
139        &self.name
140    }
141    #[must_use]
142    pub fn major(&self) -> u32 {
143        self.major
144    }
145}
146
147fn is_major_segment(s: &str) -> bool {
148    s.strip_prefix('v')
149        .is_some_and(|d| !d.is_empty() && d.bytes().all(|c| c.is_ascii_digit()))
150}
151
152impl FromStr for IfaceId {
153    type Err = KeyError;
154    /// Parses the key chunk `<name>.v<major>`.
155    fn from_str(s: &str) -> Result<Self, KeyError> {
156        let err = || KeyError::Interface(s.to_owned());
157        let (name, major) = s.rsplit_once(".v").ok_or_else(err)?;
158        if major.is_empty() || !major.bytes().all(|c| c.is_ascii_digit()) {
159            return Err(err());
160        }
161        // No leading zeros: one spelling per major.
162        if major.len() > 1 && major.starts_with('0') {
163            return Err(err());
164        }
165        let major: u32 = major.parse().map_err(|_| err())?;
166        Self::new(name, major).map_err(|_| err())
167    }
168}
169
170/// `Addr` and `IfaceId` travel as their key spellings (`vehicle-01/nav`,
171/// `nav.v2`), parsed by the same `FromStr` that guards keys, so a
172/// configuration file cannot hold an address a key would refuse.
173macro_rules! serde_via_str {
174    ($($t:ty),*) => {$(
175        impl serde::Serialize for $t {
176            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
177                s.collect_str(self)
178            }
179        }
180        impl<'de> serde::Deserialize<'de> for $t {
181            fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
182                let s = String::deserialize(d)?;
183                s.parse().map_err(serde::de::Error::custom)
184            }
185        }
186    )*};
187}
188serde_via_str!(Addr, IfaceId);
189
190impl fmt::Display for IfaceId {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        write!(f, "{}.v{}", self.name, self.major)
193    }
194}
195
196/// The kind token at position 5 (r3.3 D3).
197#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
198pub enum KindToken {
199    /// `stream`: an ambient stream (rides `zk2/<system>/**`).
200    Stream,
201    /// `@stream`: an explicit-only stream (high rate, large).
202    ExplicitStream,
203    /// `state`: latest value, answerable on GET.
204    State,
205    /// `@state`: explicit-only state (large populations).
206    ExplicitState,
207    /// `events`: one key per occurrence, ending in its occurrence chunk
208    /// (core §1.2).
209    Events,
210    /// `@op`: request/reply.
211    Op,
212}
213
214impl KindToken {
215    pub const ALL: [KindToken; 6] = [
216        Self::Stream,
217        Self::ExplicitStream,
218        Self::State,
219        Self::ExplicitState,
220        Self::Events,
221        Self::Op,
222    ];
223    #[must_use]
224    pub fn as_str(self) -> &'static str {
225        match self {
226            Self::Stream => "stream",
227            Self::ExplicitStream => "@stream",
228            Self::State => "state",
229            Self::ExplicitState => "@state",
230            Self::Events => "events",
231            Self::Op => "@op",
232        }
233    }
234    /// Verbatim tokens are reached by no `*`/`**`.
235    #[must_use]
236    pub fn is_verbatim(self) -> bool {
237        self.as_str().starts_with('@')
238    }
239}
240
241impl FromStr for KindToken {
242    type Err = KeyError;
243    fn from_str(s: &str) -> Result<Self, KeyError> {
244        Self::ALL
245            .into_iter()
246            .find(|k| k.as_str() == s)
247            .ok_or_else(|| KeyError::Kind(s.to_owned()))
248    }
249}
250
251impl fmt::Display for KindToken {
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        f.write_str(self.as_str())
254    }
255}
256
257// ─── kind selectors (§1.3) ──────────────────────────────────────────────────
258
259/// The ambient selector (§1.3): every plain-kind data key of every service
260/// — `stream`, `state` and `events` — and nothing verbatim. Zenoh's `**`
261/// never matches a verbatim chunk, so it never delivers an `@stream` or
262/// `@state` sample and a GET on it never reaches an `@op` queryable or a
263/// control key: that is the guard, and [`blind_spots`] names what it
264/// leaves out.
265pub const AMBIENT: &str = "zk2/**";
266
267/// The grammar's verbatim chunks (§1.2): the three verbatim kind tokens,
268/// then the control token. What [`blind_spots`] answers in.
269pub const VERBATIM: [&str; 4] = ["@stream", "@state", "@op", CONTROL];
270
271/// An exact kind selector (§1.3): `zk2/<system>/<service>/<iface>/<kind>/**`,
272/// `*` at each of the first three positions left `None`. Positions 1–5 have
273/// fixed arity, so it selects the resources of `kind` and no other: the
274/// token can never be read at position 6, and a verbatim token is named
275/// here, which is the only way to reach it. Base-relative, like every key
276/// of this module; a session's namespace adds the prefix.
277#[must_use]
278pub fn kind_selector(
279    system: Option<&Name>,
280    service: Option<&Name>,
281    iface: Option<&IfaceId>,
282    kind: KindToken,
283) -> String {
284    let iface = iface.map(ToString::to_string);
285    [
286        GRAMMAR,
287        system.map_or("*", Name::as_str),
288        service.map_or("*", Name::as_str),
289        iface.as_deref().unwrap_or("*"),
290        kind.as_str(),
291        "**",
292    ]
293    .join("/")
294}
295
296/// Every member of one resource of one service, as one selector:
297/// `zk2/<system>/<service>/<iface>/<kind>/<template…>`, each literal of the
298/// template its chunk, each parameter `*` and a rest parameter `**`.
299/// Base-relative, like every key of this module; a session's namespace adds
300/// the prefix on egress and strips it from what it receives, so a reply's
301/// key reads base-relative too. A GET on it reaches the resource's members
302/// and no other's but a template that shares its pattern (§2.2): a reader
303/// sorts them by [`crate::template::resolve`].
304#[must_use]
305pub fn template_selector(
306    addr: &Addr,
307    iface: &IfaceId,
308    kind: KindToken,
309    template: &crate::template::Template,
310) -> String {
311    use crate::template::Segment;
312    let iface = iface.to_string();
313    let mut chunks: Vec<&str> = vec![
314        GRAMMAR,
315        addr.system.as_str(),
316        addr.service.as_str(),
317        &iface,
318        kind.as_str(),
319    ];
320    chunks.extend(template.segments().iter().map(|s| match s {
321        Segment::Literal(l) => l.as_str(),
322        Segment::Param(_) => "*",
323        Segment::Rest(_) => "**",
324    }));
325    chunks.join("/")
326}
327
328/// The verbatim chunks of [`VERBATIM`] that `selector` can never reach, in
329/// that order (§1.3's guard): a frontend's line saying what a watch does
330/// not show, rather than letting its silence read as nothing there.
331///
332/// `@stream`, `@state` and `@op` are the data keys of that kind token under
333/// any service; `@zk` is every control key, a service's tokens and
334/// descriptors and the contract bundles alike. A selector may carry a
335/// namespace before `zk2` or none: the answer is the same, since `**`
336/// crosses no verbatim chunk wherever it stands. A non-canonical selector
337/// is canonized first (`zk2/**/**` is `zk2/**`); one that is not a key
338/// expression at all is refused.
339pub fn blind_spots(selector: &str) -> Result<Vec<&'static str>, KeyError> {
340    let selector = OwnedKeyExpr::autocanonize(selector.to_owned())
341        .map_err(|e| KeyError::KeyExpr(selector.to_owned(), e.to_string()))?;
342    let probes = |chunk: &str| -> Vec<String> {
343        if chunk == CONTROL {
344            vec![
345                format!("**/{GRAMMAR}/*/*/{CONTROL}/**"),
346                format!("**/{GRAMMAR}/{CONTROL}/**"),
347            ]
348        } else {
349            vec![format!("**/{GRAMMAR}/*/*/*/{chunk}/**")]
350        }
351    };
352    Ok(VERBATIM
353        .into_iter()
354        .filter(|chunk| {
355            !probes(chunk).iter().any(|p| {
356                zenoh_keyexpr::keyexpr::new(p.as_str())
357                    .is_ok_and(|probe| selector.intersects(probe))
358            })
359        })
360        .collect())
361}
362
363macro_rules! hex_id {
364    ($(#[$m:meta])* $t:ident, $what:literal, $len:literal) => {
365        $(#[$m])*
366        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
367        pub struct $t(String);
368        impl $t {
369            pub fn new(s: &str) -> Result<Self, KeyError> {
370                if is_lower_hex(s, $len) {
371                    Ok(Self(s.to_owned()))
372                } else {
373                    Err(KeyError::Hex { what: $what, value: s.to_owned(), len: $len })
374                }
375            }
376            #[must_use]
377            pub fn as_str(&self) -> &str {
378                &self.0
379            }
380        }
381        impl FromStr for $t {
382            type Err = KeyError;
383            fn from_str(s: &str) -> Result<Self, KeyError> {
384                Self::new(s)
385            }
386        }
387        impl fmt::Display for $t {
388            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389                f.write_str(&self.0)
390            }
391        }
392    };
393}
394
395hex_id!(
396    /// One run of a service, and its continuity epoch (r3.2 §3.5): 64 random
397    /// bits as 16 lowercase hex digits, re-minted whenever counters reset.
398    InstanceId,
399    "instance id",
400    16
401);
402hex_id!(
403    /// The first 64 bits of a contract fingerprint, in presence tokens.
404    Fp16,
405    "fingerprint prefix",
406    16
407);
408hex_id!(
409    /// A full sha256, 64 lowercase hex digits (a contract fingerprint without
410    /// its `sha256:` prefix).
411    Sha256Hex,
412    "sha256",
413    64
414);
415
416impl InstanceId {
417    #[must_use]
418    pub fn from_u64(v: u64) -> Self {
419        Self(format!("{v:016x}"))
420    }
421}
422
423impl Sha256Hex {
424    /// The 64-bit prefix used in presence tokens.
425    #[must_use]
426    pub fn fp16(&self) -> Fp16 {
427        Fp16(self.0[..16].to_owned())
428    }
429}
430
431/// A validated, canonical, base-relative zk2 key, convertible to the
432/// Zenoh key-expression type without re-parsing.
433#[derive(Debug, Clone, PartialEq, Eq, Hash)]
434pub struct Key(OwnedKeyExpr);
435
436impl Key {
437    fn from_chunks(chunks: &[&str]) -> Result<Self, KeyError> {
438        let s = chunks.join("/");
439        OwnedKeyExpr::try_from(s.clone())
440            .map(Self)
441            .map_err(|e| KeyError::KeyExpr(s, e.to_string()))
442    }
443    #[must_use]
444    pub fn as_str(&self) -> &str {
445        self.0.as_str()
446    }
447    #[must_use]
448    pub fn into_keyexpr(self) -> OwnedKeyExpr {
449        self.0
450    }
451}
452
453impl fmt::Display for Key {
454    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455        f.write_str(self.as_str())
456    }
457}
458
459/// A data key: `zk2/<system>/<service>/<iface>/<kind>/<resource…>`.
460/// `resource` chunks must already be plain chunks (template building slugs
461/// parameter values, see [`crate::template`]).
462pub fn data_key(
463    addr: &Addr,
464    iface: &IfaceId,
465    kind: KindToken,
466    resource: &[&str],
467) -> Result<Key, KeyError> {
468    if resource.is_empty() {
469        return Err(KeyError::Shape(
470            String::new(),
471            "a data key needs a resource path",
472        ));
473    }
474    for c in resource {
475        if !is_plain_chunk(c) {
476            return Err(KeyError::NotPlain {
477                what: "resource chunk",
478                value: (*c).to_owned(),
479            });
480        }
481    }
482    let iface = iface.to_string();
483    let mut chunks = vec![
484        GRAMMAR,
485        addr.system.as_str(),
486        addr.service.as_str(),
487        &iface,
488        kind.as_str(),
489    ];
490    chunks.extend_from_slice(resource);
491    Key::from_chunks(&chunks)
492}
493
494/// The instance token's key, which is also the descriptor's key.
495pub fn instance_key(addr: &Addr, instance: &InstanceId) -> Result<Key, KeyError> {
496    Key::from_chunks(&[
497        GRAMMAR,
498        addr.system.as_str(),
499        addr.service.as_str(),
500        CONTROL,
501        "instance",
502        instance.as_str(),
503    ])
504}
505
506/// An interface token: `…/@zk/alive/<iface>/<instance>/<fp16>`.
507pub fn alive_key(
508    addr: &Addr,
509    iface: &IfaceId,
510    instance: &InstanceId,
511    fp: &Fp16,
512) -> Result<Key, KeyError> {
513    let iface = iface.to_string();
514    Key::from_chunks(&[
515        GRAMMAR,
516        addr.system.as_str(),
517        addr.service.as_str(),
518        CONTROL,
519        "alive",
520        &iface,
521        instance.as_str(),
522        fp.as_str(),
523    ])
524}
525
526/// A member token (r3.3 D9b): `…/@zk/member/<iface>/<member>/<epoch>`.
527/// `member` is the slugged value of the template's `epoch` parameter.
528pub fn member_key(
529    addr: &Addr,
530    iface: &IfaceId,
531    member: &str,
532    epoch: &InstanceId,
533) -> Result<Key, KeyError> {
534    if !is_plain_chunk(member) {
535        return Err(KeyError::NotPlain {
536            what: "member",
537            value: member.to_owned(),
538        });
539    }
540    let iface = iface.to_string();
541    Key::from_chunks(&[
542        GRAMMAR,
543        addr.system.as_str(),
544        addr.service.as_str(),
545        CONTROL,
546        "member",
547        &iface,
548        member,
549        epoch.as_str(),
550    ])
551}
552
553/// A contract bundle's location-free key: `zk2/@zk/contract/<iface>/<sha256>`.
554pub fn contract_key(iface: &IfaceId, fingerprint: &Sha256Hex) -> Result<Key, KeyError> {
555    let iface = iface.to_string();
556    Key::from_chunks(&[GRAMMAR, CONTROL, "contract", &iface, fingerprint.as_str()])
557}
558
559/// A parsed zk2 key.
560#[derive(Debug, Clone, PartialEq, Eq)]
561pub enum ZkKey {
562    Data {
563        addr: Addr,
564        iface: IfaceId,
565        kind: KindToken,
566        resource: Vec<String>,
567    },
568    Instance {
569        addr: Addr,
570        instance: InstanceId,
571    },
572    Alive {
573        addr: Addr,
574        iface: IfaceId,
575        instance: InstanceId,
576        fp: Fp16,
577    },
578    Member {
579        addr: Addr,
580        iface: IfaceId,
581        member: String,
582        epoch: InstanceId,
583    },
584    Contract {
585        iface: IfaceId,
586        fingerprint: Sha256Hex,
587    },
588}
589
590impl ZkKey {
591    /// Builds the key back, which must give the parsed string exactly.
592    pub fn to_key(&self) -> Result<Key, KeyError> {
593        match self {
594            Self::Data {
595                addr,
596                iface,
597                kind,
598                resource,
599            } => {
600                let r: Vec<&str> = resource.iter().map(String::as_str).collect();
601                data_key(addr, iface, *kind, &r)
602            }
603            Self::Instance { addr, instance } => instance_key(addr, instance),
604            Self::Alive {
605                addr,
606                iface,
607                instance,
608                fp,
609            } => alive_key(addr, iface, instance, fp),
610            Self::Member {
611                addr,
612                iface,
613                member,
614                epoch,
615            } => member_key(addr, iface, member, epoch),
616            Self::Contract { iface, fingerprint } => contract_key(iface, fingerprint),
617        }
618    }
619}
620
621/// Parses a base-relative key. Anything not in the grammar is refused with
622/// the reason; a key outside `zk2/` is not an error of the key, but it is
623/// not a zk2 key either.
624pub fn parse(key: &str) -> Result<ZkKey, KeyError> {
625    let shape = |why| KeyError::Shape(key.to_owned(), why);
626    let c: Vec<&str> = key.split('/').collect();
627    if c.first() != Some(&GRAMMAR) {
628        return Err(shape("it does not start with zk2/"));
629    }
630    if c.get(1) == Some(&CONTROL) {
631        return match c.as_slice() {
632            [_, _, "contract", iface, sha] => Ok(ZkKey::Contract {
633                iface: iface.parse()?,
634                fingerprint: sha.parse()?,
635            }),
636            _ => Err(shape("zk2/@zk/ holds only contract/<iface>/<sha256>")),
637        };
638    }
639    if c.len() < 6 {
640        return Err(shape("too few chunks"));
641    }
642    let addr = Addr::new(c[1], c[2])?;
643    if c[3] == CONTROL {
644        return match &c[4..] {
645            ["instance", inst] => Ok(ZkKey::Instance {
646                addr,
647                instance: inst.parse()?,
648            }),
649            ["alive", iface, inst, fp] => Ok(ZkKey::Alive {
650                addr,
651                iface: iface.parse()?,
652                instance: inst.parse()?,
653                fp: fp.parse()?,
654            }),
655            ["member", iface, member, epoch] => {
656                if !is_plain_chunk(member) {
657                    return Err(KeyError::NotPlain {
658                        what: "member",
659                        value: (*member).to_owned(),
660                    });
661                }
662                Ok(ZkKey::Member {
663                    addr,
664                    iface: iface.parse()?,
665                    member: (*member).to_owned(),
666                    epoch: epoch.parse()?,
667                })
668            }
669            _ => Err(shape("unknown @zk control key")),
670        };
671    }
672    let iface: IfaceId = c[3].parse()?;
673    let kind: KindToken = c[4].parse()?;
674    let resource: Vec<String> = c[5..].iter().map(|s| (*s).to_owned()).collect();
675    for r in &resource {
676        if !is_plain_chunk(r) {
677            return Err(KeyError::NotPlain {
678                what: "resource chunk",
679                value: r.clone(),
680            });
681        }
682    }
683    // An occurrence chunk (core §1.2): a key that ends in anything else,
684    // a ULID's 26 characters among them, is no zk2 key (#980's C2d).
685    if kind == KindToken::Events
686        && !resource
687            .last()
688            .is_some_and(|l| crate::chunk::is_occurrence(l))
689    {
690        return Err(shape("an events key ends in an occurrence chunk"));
691    }
692    Ok(ZkKey::Data {
693        addr,
694        iface,
695        kind,
696        resource,
697    })
698}
699
700#[cfg(test)]
701mod tests {
702    use super::*;
703
704    fn addr() -> Addr {
705        Addr::new("vehicle-01", "navigation").unwrap()
706    }
707
708    /// A template's selector: literals kept, a parameter `*`, a rest
709    /// `**`, and every key it builds matched by it.
710    #[test]
711    fn a_template_selector_matches_its_members() {
712        use crate::template::Template;
713        let iface: IfaceId = "modem.v3".parse().unwrap();
714        let t = Template::parse("sdu/endpoint/{endpoint}").unwrap();
715        let sel = template_selector(&addr(), &iface, KindToken::State, &t);
716        assert_eq!(
717            sel,
718            "zk2/vehicle-01/navigation/modem.v3/state/sdu/endpoint/*"
719        );
720        let one = Template::parse("radio").unwrap();
721        assert_eq!(
722            template_selector(&addr(), &iface, KindToken::ExplicitState, &one),
723            "zk2/vehicle-01/navigation/modem.v3/@state/radio"
724        );
725        let rest = Template::parse("logs/{path...}").unwrap();
726        assert!(template_selector(&addr(), &iface, KindToken::State, &rest).ends_with("/logs/**"));
727        let key = data_key(
728            &addr(),
729            &iface,
730            KindToken::State,
731            &["sdu", "endpoint", "e1"],
732        )
733        .unwrap()
734        .to_string();
735        let sel = zenoh_keyexpr::keyexpr::new(sel.as_str()).unwrap();
736        assert!(sel.includes(zenoh_keyexpr::keyexpr::new(key.as_str()).unwrap()));
737    }
738
739    #[test]
740    fn iface_chunks() {
741        let n: IfaceId = "nav.v2".parse().unwrap();
742        assert_eq!((n.name(), n.major()), ("nav", 2));
743        let t: IfaceId = "tc.netem.v1".parse().unwrap();
744        assert_eq!((t.name(), t.major()), ("tc.netem", 1));
745        for bad in [
746            "nav",
747            "nav.v",
748            "nav.vx",
749            "Nav.v2",
750            "nav.v02",
751            ".v2",
752            "nav..x.v1",
753            "a.v2.v3",
754            "v2.v3",
755        ] {
756            assert!(bad.parse::<IfaceId>().is_err(), "{bad}");
757        }
758        assert!(
759            IfaceId::new("acme.v2", 1).is_err(),
760            "a name may not end in .v<int>"
761        );
762    }
763
764    #[test]
765    fn data_keys_round_trip() {
766        let k = data_key(
767            &addr(),
768            &"nav.v2".parse().unwrap(),
769            KindToken::Stream,
770            &["position"],
771        )
772        .unwrap();
773        assert_eq!(
774            k.as_str(),
775            "zk2/vehicle-01/navigation/nav.v2/stream/position"
776        );
777        let p = parse(k.as_str()).unwrap();
778        assert_eq!(p.to_key().unwrap(), k);
779        let op = data_key(
780            &addr(),
781            &"nav.v2".parse().unwrap(),
782            KindToken::Op,
783            &["set_origin"],
784        )
785        .unwrap();
786        assert_eq!(
787            op.as_str(),
788            "zk2/vehicle-01/navigation/nav.v2/@op/set_origin"
789        );
790        assert_eq!(parse(op.as_str()).unwrap().to_key().unwrap(), op);
791    }
792
793    #[test]
794    fn control_keys_round_trip() {
795        let i = InstanceId::from_u64(0x8f3a_5c2e_9b1d_4f70);
796        let sha = Sha256Hex::new(&"3fa9c2d41b7e9a01".repeat(4)).unwrap();
797        let iface: IfaceId = "nav.v2".parse().unwrap();
798        for k in [
799            instance_key(&addr(), &i).unwrap(),
800            alive_key(&addr(), &iface, &i, &sha.fp16()).unwrap(),
801            member_key(&addr(), &iface, "rf0", &i).unwrap(),
802            contract_key(&iface, &sha).unwrap(),
803        ] {
804            assert_eq!(parse(k.as_str()).unwrap().to_key().unwrap(), k, "{k}");
805        }
806        assert_eq!(
807            alive_key(&addr(), &iface, &i, &sha.fp16())
808                .unwrap()
809                .as_str(),
810            "zk2/vehicle-01/navigation/@zk/alive/nav.v2/8f3a5c2e9b1d4f70/3fa9c2d41b7e9a01"
811        );
812    }
813
814    #[test]
815    fn refusals() {
816        for bad in [
817            "v1/h-3fa9c2d41b7e/state/sysinfo/health",
818            "zk2/vehicle-01/navigation/nav.v2/telemetry/x",
819            "zk2/Vehicle/navigation/nav.v2/stream/x",
820            "zk2/vehicle-01/navigation/nav.v2/stream",
821            "zk2/vehicle-01/navigation/nav.v2/events/applied/not-a-chunk",
822            "zk2/vehicle-01/navigation/nav.v2/events/applied/01jgxqz4yqk8v6txw3m9f2a7cd",
823            "zk2/@zk/contract/nav.v2/abc",
824            "zk2/vehicle-01/navigation/@zk/instance/XYZ",
825        ] {
826            assert!(parse(bad).is_err(), "{bad}");
827        }
828    }
829
830    #[test]
831    fn verbatim_tokens() {
832        assert!(KindToken::ExplicitStream.is_verbatim());
833        assert!(KindToken::ExplicitState.is_verbatim());
834        assert!(KindToken::Op.is_verbatim());
835        assert!(!KindToken::Events.is_verbatim());
836        assert!(!KindToken::Stream.is_verbatim());
837        let verbatim: Vec<&str> = KindToken::ALL
838            .into_iter()
839            .filter(|k| k.is_verbatim())
840            .map(KindToken::as_str)
841            .collect();
842        assert_eq!(
843            verbatim,
844            VERBATIM[..3],
845            "VERBATIM lists the verbatim kinds, then @zk"
846        );
847    }
848
849    /// One data key of each kind token, and one key of each control form.
850    fn one_of_each() -> (Vec<(KindToken, Key)>, Vec<Key>) {
851        let nav: IfaceId = "nav.v2".parse().unwrap();
852        let data = KindToken::ALL
853            .into_iter()
854            .map(|k| {
855                let resource: &[&str] = if k == KindToken::Events {
856                    &["applied", "01hzy3d1s5k8b2c4e6g8j0m2p4"]
857                } else {
858                    &["position"]
859                };
860                (k, data_key(&addr(), &nav, k, resource).unwrap())
861            })
862            .collect();
863        let i = InstanceId::from_u64(1);
864        let sha = Sha256Hex::new(&"3fa9c2d41b7e9a01".repeat(4)).unwrap();
865        let control = vec![
866            instance_key(&addr(), &i).unwrap(),
867            alive_key(&addr(), &nav, &i, &sha.fp16()).unwrap(),
868            member_key(&addr(), &nav, "rf0", &i).unwrap(),
869            contract_key(&nav, &sha).unwrap(),
870        ];
871        (data, control)
872    }
873
874    fn reaches(selector: &str, key: &Key) -> bool {
875        zenoh_keyexpr::keyexpr::new(selector)
876            .unwrap()
877            .intersects(&key.clone().into_keyexpr())
878    }
879
880    /// §1.3's guard: the ambient selector reaches every plain-kind data key
881    /// and no verbatim chunk — no `@stream`, `@state` or `@op` key, and no
882    /// control key, a service's or a contract's.
883    #[test]
884    fn ambient_never_reaches_a_verbatim_chunk() {
885        let (data, control) = one_of_each();
886        for (kind, key) in &data {
887            assert_eq!(
888                reaches(AMBIENT, key),
889                !kind.is_verbatim(),
890                "{AMBIENT} and {key}"
891            );
892        }
893        for key in &control {
894            assert!(!reaches(AMBIENT, key), "{AMBIENT} reached {key}");
895        }
896        assert_eq!(blind_spots(AMBIENT).unwrap(), VERBATIM);
897    }
898
899    /// §1.3's exact kind selectors: positions 1–5 have fixed arity, so a
900    /// kind selector reaches its own kind's keys and no other kind's, the
901    /// token never being read further down the key; and a verbatim one is
902    /// not blind to its own token.
903    #[test]
904    fn kind_selectors_have_fixed_arity() {
905        let (data, control) = one_of_each();
906        for kind in KindToken::ALL {
907            let selector = kind_selector(None, None, None, kind);
908            assert_eq!(selector, format!("zk2/*/*/*/{kind}/**"));
909            for (other, key) in &data {
910                assert_eq!(reaches(&selector, key), *other == kind, "{selector}, {key}");
911            }
912            for key in &control {
913                assert!(!reaches(&selector, key), "{selector} reached {key}");
914            }
915            let blind = blind_spots(&selector).unwrap();
916            assert!(!blind.contains(&kind.as_str()), "{selector} sees {kind}");
917            assert!(blind.contains(&CONTROL));
918        }
919        // The token at position 6 is a resource chunk, never a kind.
920        let deeper = "zk2/vehicle-01/navigation/nav.v2/stream/state/x";
921        let deeper = Key(OwnedKeyExpr::try_from(deeper.to_owned()).unwrap());
922        assert!(!reaches(
923            &kind_selector(None, None, None, KindToken::State),
924            &deeper
925        ));
926        let a = addr();
927        let nav: IfaceId = "nav.v2".parse().unwrap();
928        assert_eq!(
929            kind_selector(
930                Some(&a.system),
931                Some(&a.service),
932                Some(&nav),
933                KindToken::ExplicitState
934            ),
935            "zk2/vehicle-01/navigation/nav.v2/@state/**"
936        );
937        assert_eq!(
938            kind_selector(Some(&a.system), None, None, KindToken::Op),
939            "zk2/vehicle-01/*/*/@op/**"
940        );
941    }
942
943    /// What a selector cannot see, named: the whole bus root sees no
944    /// verbatim chunk, a namespace changes nothing, a control selector sees
945    /// `@zk` alone, and what is not a key expression is refused.
946    #[test]
947    fn blind_spots_name_what_a_selector_cannot_see() {
948        assert_eq!(blind_spots("**").unwrap(), VERBATIM);
949        assert_eq!(blind_spots("prod/site/zk2/**").unwrap(), VERBATIM);
950        assert_eq!(blind_spots("zk2/**/**").unwrap(), VERBATIM, "canonized");
951        assert_eq!(
952            blind_spots("zk2/*/*/@zk/**").unwrap(),
953            ["@stream", "@state", "@op"]
954        );
955        assert_eq!(
956            blind_spots("zk2/@zk/contract/**").unwrap(),
957            ["@stream", "@state", "@op"]
958        );
959        assert_eq!(
960            blind_spots("prod/zk2/robot1/*/nav.v2/@stream/**").unwrap(),
961            ["@state", "@op", "@zk"]
962        );
963        assert!(blind_spots("a//b").is_err());
964    }
965}