1use 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
23pub const GRAMMAR: &str = "zk2";
26pub const CONTROL: &str = "@zk";
28
29#[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#[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#[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 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
114pub struct IfaceId {
115 name: String,
116 major: u32,
117}
118
119impl IfaceId {
120 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 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 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
170macro_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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
198pub enum KindToken {
199 Stream,
201 ExplicitStream,
203 State,
205 ExplicitState,
207 Events,
210 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 #[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
257pub const AMBIENT: &str = "zk2/**";
266
267pub const VERBATIM: [&str; 4] = ["@stream", "@state", "@op", CONTROL];
270
271#[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#[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
328pub 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 InstanceId,
399 "instance id",
400 16
401);
402hex_id!(
403 Fp16,
405 "fingerprint prefix",
406 16
407);
408hex_id!(
409 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 #[must_use]
426 pub fn fp16(&self) -> Fp16 {
427 Fp16(self.0[..16].to_owned())
428 }
429}
430
431#[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
459pub 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
494pub 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
506pub 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
526pub 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
553pub 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#[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 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
621pub 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 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 #[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 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 #[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 #[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 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 #[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}