Skip to main content

zenkey_model/
link.rs

1//! `link.v1`: what crosses a constrained face
2//! (`spec/profiles/link/v1.md`, #769), and `link.v2`: the transport it runs
3//! (`spec/profiles/link/v2.md`, #988 L1).
4//!
5//! The profile's session-free half: the exposure a contract gives a
6//! resource (§2.2), the face policy a deployment writes and its lints
7//! (§2.1), the plan a generator derives from both (§2.3–§2.12), every
8//! revision of an interface read together, how a generator keeps every
9//! other principal's subject off a face (§2.4), and the checks of a
10//! router's block (§2.15), whether its access control is enabled among
11//! them (0.7, F-124). A far principal two faces name carries both plans'
12//! denies on each, which the linter warns of (§2.1, §2.4, 0.7, F-125).
13//!
14//! ```text
15//! exposure(kind, annotations)       ─▶ host │ link │ invalid │ ignored
16//! crossing(token, templated, …)     ─▶ downsampled │ whole │ denied │ none, + reason
17//! parse(face policy TOML)           ─▶ the policy, or the findings that refuse it
18//! plan(policy, deployment)          ─▶ per face: denies, downsampling, attachment,
19//!                                      window floors, liveness evidence, warnings
20//! narrowed(policy, is_far)          ─▶ the link protocols a principal's subject keeps
21//! check_windows / check_block /
22//!   check_subjects /
23//!   check_narrowing                 ─▶ findings
24//! ```
25//!
26//! There is no session here and no router: a generator writes the plan
27//! into a router's configuration (`zenkey-fleet`'s `acl gen`), and a tool
28//! reads a block somebody says the router runs. The deployment's services
29//! and the contracts come in as values.
30//!
31//! **`link.v2`** (#988 L1) is read by the same [`parse`]: a policy whose
32//! `profile` is `"link.v2"` adds the router's [`Transport`] (v2 §2.16), the
33//! [`Binding`] it runs, which names its link protocols (v2 §2.4) and its
34//! defaults (v2 §2.19), the catalog's id, and per face the loss, the ARQ
35//! and the reply timeout (v2 §2.1); one without `profile` is a `link.v1`
36//! policy, read as it was. A v2 face's `batch_bytes` and `lease_ms` are
37//! its `[transport]`'s, so the plan and §2.10 read both profiles alike.
38//!
39//! **link.v2's contract side** (#988 L3, v2 0.3): a contract that lists
40//! `link.v2` types every resource it exposes as packed ([`contract_findings`],
41//! `packed_required`, v2 §2.17); a face's `frames` lists the frame resources
42//! that cross it, each at its cadence, and its `horizon_s` is the shortest
43//! horizon it affords (v2 §2.1, §2.7, §2.12); and under a link.v2 policy the
44//! plan denies a timed stream rather than downsample it (v2 §2.8), refuses a
45//! crossing revision the deployment's catalog lacks (v2 §2.18), and weighs
46//! what crosses against the face (`not_packed`, `frame_unlisted`,
47//! `horizon_under_face`, `block_over_batch`, `keep_alive_not_suppressed`,
48//! `timed_downsampled`).
49//!
50//! **What fits one batch** (#1136, link.v1 0.22, v2 0.30): `frame_over_batch`
51//! and `block_over_batch` weigh a put's payload with its [`allowance`], what
52//! zenoh 1.10.1 writes beside it: the put's header and the payload's length,
53//! the push's and the frame's QoS extensions where the resource's QoS
54//! ([`PutQos`]) has them, the frame's header at the sequence width's widest
55//! ([`Sequence::max_bytes`], 32 bits under a link.v1 policy), and the
56//! batch's 2-byte length on a link that may be streamed. Measured at the
57//! bound on zenoh-modem's RF face.
58//!
59//! **A device face** (#982 H1, v2 0.7): `attach = "device"` with `devices`,
60//! the owners on a first hop by address (v2 §2.1, §2.5). Each device is a
61//! listed owner on every face ([`FacePolicy::owners`]), but for
62//! downsampling on its own face (v2 §2.8); the plan refuses one that
63//! implements `archive.v1` or a governed interface (`presence_required`),
64//! warns of its `epoch` templates (`epoch_on_device`), and carves `zk` into
65//! three denies, so that an instance key crosses on core §11.2's Own row's
66//! pairs alone ([`OWN_PAIRS`], v2 §2.6); [`check_block`] reads that carve
67//! on a device face (v2 §2.15).
68//!
69//! ```text
70//! crossing_v2(token, shape, …)      ─▶ link.v2's reading of one resource
71//! contract_findings(contract)       ─▶ packed_required, per exposed resource
72//! ```
73//!
74//! ```text
75//! Transport::value(key)             ─▶ the value a generator writes at zenoh's key
76//! StatedTransport::read(config)     ─▶ the keys a router's configuration states
77//! check_transport(policy, router,
78//!                 peer)             ─▶ transport_differs, wait_under_lease, peer_differs,
79//!                                      face_timestamping
80//! check_catalog(policy, held)       ─▶ catalog_mismatch
81//! ```
82
83use std::cmp::Ordering;
84use std::collections::{BTreeMap, BTreeSet};
85use std::fmt;
86
87use serde::Serialize;
88use serde_json::Value;
89use zenoh_keyexpr::keyexpr;
90
91use crate::authoring::Kind;
92use crate::chunk::is_plain_chunk;
93use crate::contract::{Contract, Resource};
94use crate::freshness::{self, Horizon};
95use crate::grammar::KindToken;
96use crate::template::{Segment, Template};
97
98/// The profile's id, as a contract lists it in `uses`.
99pub const PROFILE: &str = "link.v1";
100
101/// `archive.v1`'s interface id: a device implementing it is
102/// `presence_required` (v2 §2.5).
103const ARCHIVE: &str = "archive.v1";
104
105/// The profile's name, as an annotation key's prefix carries it.
106pub const NAME: &str = "link";
107
108/// The one annotation key (§4).
109pub const EXPOSURE: &str = "link.exposure";
110
111/// The published vocabulary (§4): the keys under `link.`, which W105 reads
112/// in place of core Appendix D's interim row (core 0.29).
113pub const VOCABULARY: &[&str] = &["exposure"];
114
115/// `link.v2`'s id, as a face policy's `profile` names it (v2 §2.1), and as
116/// a contract lists it in `uses` (v2 §2.17).
117pub const PROFILE_V2: &str = "link.v2";
118
119/// Whether a contract lists `link.v2` in `uses`: it then types every
120/// resource it exposes as packed (v2 §2.17).
121#[must_use]
122pub fn uses_v2(c: &Contract) -> bool {
123    c.uses.iter().any(|u| u.to_string() == PROFILE_V2)
124}
125
126/// The bytes of the envelope a packed record or a frame travels in, with a
127/// 32-bit run (core §7.5): CH, the run and the seq.
128pub const ENVELOPE_BYTES: u64 = 8;
129
130/// zenoh's transport lease, `transport.link.tx.lease`, when a face policy
131/// gives none (§2.1).
132pub const DEFAULT_LEASE_MS: u64 = 10_000;
133
134/// The core's tombstone window when a deployment configures none (core S3).
135pub const DEFAULT_WINDOW_S: u64 = 60;
136
137/// Stock zenoh's link protocol names (`InterceptorLink`, kebab-case), the
138/// values `select.link_protocols` takes (§2.1): 1.10.1's nine, and 1.10.2's,
139/// the same (`zenoh-config`'s `lib.rs`, line 317 in 1.10.1 and 320 in
140/// 1.10.2); `zm-1.10.2-r1` adds `unixsock-dgram` after `unixsock-stream`
141/// (v2 §2.4).
142const STOCK_PROTOCOLS: &[&str] = &[
143    "tcp",
144    "udp",
145    "tls",
146    "quic",
147    "serial",
148    "unixpipe",
149    "unixsock-stream",
150    "vsock",
151    "ws",
152];
153
154/// The fork's `InterceptorLink` (`commons/zenoh-config/src/lib.rs` at
155/// `zm-1.10.2-r1`, lines 320–331), in its order.
156const ZM_1_10_2_R1_PROTOCOLS: &[&str] = &[
157    "tcp",
158    "udp",
159    "tls",
160    "quic",
161    "serial",
162    "unixpipe",
163    "unixsock-stream",
164    "unixsock-dgram",
165    "vsock",
166    "ws",
167];
168
169/// The nine access-control messages, in the order a plan lists them (§0).
170pub const MESSAGES: [&str; 9] = [
171    "put",
172    "delete",
173    "declare_subscriber",
174    "query",
175    "declare_queryable",
176    "reply",
177    "liveliness_token",
178    "declare_liveliness_subscriber",
179    "liveliness_query",
180];
181
182/// The push messages, which an exposure deny names (§0, §2.7).
183pub const PUSH_MESSAGES: [&str; 3] = ["put", "delete", "declare_subscriber"];
184
185/// Both flows, in the order a plan lists them (§0).
186pub const FLOWS: [&str; 2] = ["egress", "ingress"];
187
188/// The `@zk` deny's key expression, base-relative (§2.6).
189pub const ZK_DENY: &str = "zk2/**/@zk/**";
190
191/// The `@adv` deny's key expression, base-relative (§2.6).
192pub const ADV_DENY: &str = "zk2/**/@adv/**";
193
194/// The admin space's deny, never namespaced (§2.6).
195pub const ADMIN_DENY: &str = "@/**";
196
197/// The kind tokens whose pushes a plan denies, in its order (§2.7).
198pub const PUSH_TOKENS: [KindToken; 5] = [
199    KindToken::Stream,
200    KindToken::ExplicitStream,
201    KindToken::State,
202    KindToken::ExplicitState,
203    KindToken::Events,
204];
205
206const MAX_U32: u64 = u32::MAX as u64;
207const MAX_BATCH: u64 = 65_535;
208const MAX_REGION: usize = 32;
209/// `keep_alive`'s bound (v2 §2.1): it keeps `keep_alive_flaps`'s exact
210/// arithmetic small, and no medium runs more.
211const MAX_KEEP_ALIVE: u64 = 255;
212const MAX_LOSS_PPM: u64 = 1_000_000;
213
214// ── link.v2: the profile, the binding, the transport (v2 §2.1, §2.4, §2.16) ─
215
216/// Which text a face policy is read by (v2 §2.1).
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
218pub enum Profile {
219    /// No `profile`: `link.v1`, read as its §2.1 says.
220    #[default]
221    V1,
222    /// `profile = "link.v2"`.
223    V2,
224}
225
226impl Profile {
227    /// The profile's id.
228    #[must_use]
229    pub fn as_str(self) -> &'static str {
230        match self {
231            Self::V1 => PROFILE,
232            Self::V2 => PROFILE_V2,
233        }
234    }
235}
236
237/// The prefix of a release of the fork on zenoh 1.10.2, `zm-1.10.2-r<n>`
238/// (v2 §2.4).
239const FORK_RELEASE: &str = "zm-1.10.2-r";
240
241/// The zenoh a near router runs (v2 §2.4): it names the router's link
242/// protocols, and the defaults a configuration that omits a transport key
243/// runs with (v2 §2.19). A `link.v1` policy reads as `zenoh-1.10.1`.
244#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
245pub enum Binding {
246    /// Stock zenoh 1.10.1.
247    #[default]
248    Zenoh1_10_1,
249    /// Stock zenoh 1.10.2 (#1165): 1.10.1's link protocols and defaults.
250    Zenoh1_10_2,
251    /// `zm-1.10.2-r1`, the fork zenoh-modem builds on, and each later
252    /// release of the fork on zenoh 1.10.2, `zm-1.10.2-r<n>`, that changes
253    /// none of what a plan reads (v2 §2.4).
254    Zm1_10_2R1,
255}
256
257impl Binding {
258    /// Every binding, in the order v2 §2.4 lists them.
259    pub const ALL: [Binding; 3] = [
260        Binding::Zenoh1_10_1,
261        Binding::Zenoh1_10_2,
262        Binding::Zm1_10_2R1,
263    ];
264
265    /// Every binding's name, in [`Binding::ALL`]'s order: the one list a
266    /// refusal offers ([`UnknownBinding`], and `Deserialize`'s).
267    pub const NAMES: [&'static str; Binding::ALL.len()] = {
268        let mut names = [""; Binding::ALL.len()];
269        let mut i = 0;
270        while i < names.len() {
271            names[i] = Binding::ALL[i].as_str();
272            i += 1;
273        }
274        names
275    };
276
277    /// Its name in a policy.
278    #[must_use]
279    pub const fn as_str(self) -> &'static str {
280        match self {
281            Self::Zenoh1_10_1 => "zenoh-1.10.1",
282            Self::Zenoh1_10_2 => "zenoh-1.10.2",
283            Self::Zm1_10_2R1 => "zm-1.10.2-r1",
284        }
285    }
286
287    /// The binding a policy's `binding` names, if any: a binding's name, or
288    /// `zm-1.10.2-r<n>`, `n` a decimal from 1 with no leading zero, which
289    /// names `zm-1.10.2-r1`'s binding (v2 §2.4).
290    #[must_use]
291    pub fn parse(s: &str) -> Option<Binding> {
292        Self::ALL.into_iter().find(|b| b.as_str() == s).or_else(|| {
293            let n = s.strip_prefix(FORK_RELEASE)?;
294            (!n.is_empty() && !n.starts_with('0') && n.bytes().all(|b| b.is_ascii_digit()))
295                .then_some(Binding::Zm1_10_2R1)
296        })
297    }
298
299    /// The closed list of link protocols `select.link_protocols` takes and
300    /// §2.4's narrowing reads, in its order (v2 §2.4).
301    #[must_use]
302    pub fn protocols(self) -> &'static [&'static str] {
303        match self {
304            Self::Zenoh1_10_1 | Self::Zenoh1_10_2 => STOCK_PROTOCOLS,
305            Self::Zm1_10_2R1 => ZM_1_10_2_R1_PROTOCOLS,
306        }
307    }
308
309    /// What a router of this binding runs for a transport key its
310    /// configuration omits (v2 §2.19; `zenoh-config`'s `defaults.rs`, the
311    /// same in 1.10.1 and 1.10.2): the fork's `wait_before_close` is its
312    /// lease, 10 s, its own change, where stock zenoh's is 5 s.
313    #[must_use]
314    pub fn defaults(self) -> Transport {
315        Transport {
316            lease_ms: 10_000,
317            keep_alive: 4,
318            wait_before_close_ms: match self {
319                Self::Zenoh1_10_1 | Self::Zenoh1_10_2 => 5_000,
320                Self::Zm1_10_2R1 => 10_000,
321            },
322            sequence: Sequence::Bit32,
323            batch_bytes: MAX_BATCH,
324            open_timeout_ms: DEFAULT_TIMEOUT_MS,
325            accept_timeout_ms: DEFAULT_TIMEOUT_MS,
326            interests_timeout_ms: DEFAULT_TIMEOUT_MS,
327        }
328    }
329}
330
331impl fmt::Display for Binding {
332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333        f.write_str(self.as_str())
334    }
335}
336
337impl Serialize for Binding {
338    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
339        s.serialize_str(self.as_str())
340    }
341}
342
343/// A name that is no binding (v2 §2.4): what [`Binding`]'s `FromStr`
344/// refuses, said with the names it could have been.
345#[derive(Debug, Clone, PartialEq, Eq)]
346pub struct UnknownBinding(pub String);
347
348impl fmt::Display for UnknownBinding {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        write!(
351            f,
352            "not a binding; one of: {}, or {FORK_RELEASE}<n> for a later release of the fork",
353            Binding::NAMES.join(", ")
354        )
355    }
356}
357
358impl std::error::Error for UnknownBinding {}
359
360/// A binding by its name in a policy, for a tool's flag (`--binding`): any
361/// other string is refused with the names it could have been.
362impl std::str::FromStr for Binding {
363    type Err = UnknownBinding;
364
365    fn from_str(s: &str) -> Result<Self, Self::Err> {
366        Binding::parse(s).ok_or_else(|| UnknownBinding(s.to_owned()))
367    }
368}
369
370/// A binding by its name in a policy, for a tool's own configuration (a
371/// policy's `binding` is read by [`parse`], with its findings): any other
372/// string is refused with the names it could have been.
373impl<'de> serde::Deserialize<'de> for Binding {
374    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
375        let name = String::deserialize(d)?;
376        Binding::parse(&name)
377            .ok_or_else(|| serde::de::Error::unknown_variant(&name, &Binding::NAMES))
378    }
379}
380
381/// zenoh 1.10.1's `open_timeout`, `accept_timeout` and interests timeout,
382/// in ms: an optional `[transport]` key's default (v2 §2.1).
383pub const DEFAULT_TIMEOUT_MS: u64 = 10_000;
384
385/// The frame sequence number's resolution (v2 §2.16), as zenoh's `Bits`.
386#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
387pub enum Sequence {
388    Bit8,
389    Bit16,
390    Bit32,
391    Bit64,
392}
393
394impl Sequence {
395    /// Every resolution.
396    pub const ALL: [Sequence; 4] = [
397        Sequence::Bit8,
398        Sequence::Bit16,
399        Sequence::Bit32,
400        Sequence::Bit64,
401    ];
402
403    /// zenoh's spelling, `"16bit"`.
404    #[must_use]
405    pub fn as_str(self) -> &'static str {
406        match self {
407            Self::Bit8 => "8bit",
408            Self::Bit16 => "16bit",
409            Self::Bit32 => "32bit",
410            Self::Bit64 => "64bit",
411        }
412    }
413
414    /// The resolution a spelling names, if any.
415    #[must_use]
416    pub fn parse(s: &str) -> Option<Sequence> {
417        Self::ALL.into_iter().find(|q| q.as_str() == s)
418    }
419
420    /// The window (v2 §2.16): a frame half the mask or more past the last
421    /// one received is dropped as old. zenoh 1.10.1 masks a frame's sequence
422    /// number to 7, 14, 28 and 32 bits (`common/seq_num.rs`, its
423    /// `TransportSn` being 32 bits), so the window is 64, 8,192, 2^27 and
424    /// 2^31 frames.
425    #[must_use]
426    pub fn window(self) -> u64 {
427        match self {
428            Self::Bit8 => 1 << 6,
429            Self::Bit16 => 1 << 13,
430            Self::Bit32 => 1 << 27,
431            Self::Bit64 => 1 << 31,
432        }
433    }
434
435    /// The most bytes a frame's sequence number takes (v2 §2.16, #1136):
436    /// masked as [`window`](Self::window) says, and written 7 bits a byte,
437    /// 1, 2, 4 and 5. Measured on rf0's face, a `16bit` number ran to
438    /// 16,383 and then 0, and a `32bit` one to 268,435,455 and then 0.
439    #[must_use]
440    pub fn max_bytes(self) -> u64 {
441        match self {
442            Self::Bit8 => 1,
443            Self::Bit16 => 2,
444            Self::Bit32 => 4,
445            Self::Bit64 => 5,
446        }
447    }
448}
449
450/// The link protocols on which zenoh 1.10.1 writes no batch length, a
451/// datagram's: `serial`, `ws` and the fork's `unixsock-dgram` (link.v1
452/// §2.8, v2 §2.16, #1136). Every other one may be streamed (`udp` where its
453/// endpoint asks for a reliable link), and a streamed link spends 2 bytes of
454/// its batch on the length.
455pub const UNSTREAMED_PROTOCOLS: [&str; 3] = ["serial", "ws", "unixsock-dgram"];
456
457/// What a put's QoS adds to its batch (link.v1 §2.8, core §2.4): the push's
458/// QoS extension unless its priority is `data`, its congestion `drop` and
459/// it is not express, and the frame's unless its priority is `data`.
460#[derive(Debug, Clone, Copy, PartialEq, Eq)]
461pub struct PutQos {
462    /// Its congestion is `block`.
463    pub block: bool,
464    /// Its priority is `data`, zenoh's default.
465    pub priority_data: bool,
466    /// It is express.
467    pub express: bool,
468}
469
470impl PutQos {
471    /// zenoh's defaults: `data`, `drop`, not express. No extension.
472    pub const DATA_DROP: PutQos = PutQos {
473        block: false,
474        priority_data: true,
475        express: false,
476    };
477}
478
479/// The most bytes zenoh 1.10.1 writes in a batch beside a put's payload of
480/// `payload` bytes, on a key its far reader declared (link.v1 §2.8, #1136):
481/// the put's 3 bytes and the payload's length, 7 bits a byte; the push's
482/// and the frame's QoS extensions, 2 bytes each where `qos` has one; the
483/// frame's header byte and its sequence number at `sequence`'s widest; and
484/// the batch's 2-byte length unless no link of `protocols` is streamed
485/// ([`UNSTREAMED_PROTOCOLS`]). Measured at the bound on zenoh-modem's RF
486/// face (`docs/zk2/measurements/wire-baseline/`, "The batch's bound").
487#[must_use]
488pub fn allowance(payload: u64, qos: PutQos, sequence: Sequence, protocols: &[String]) -> u64 {
489    let length = match payload {
490        0..128 => 1,
491        128..16_384 => 2,
492        _ => 3,
493    };
494    let push_qos = if qos.priority_data && !qos.block && !qos.express {
495        0
496    } else {
497        2
498    };
499    let frame_qos = if qos.priority_data { 0 } else { 2 };
500    let batch_length = if protocols
501        .iter()
502        .all(|p| UNSTREAMED_PROTOCOLS.contains(&p.as_str()))
503    {
504        0
505    } else {
506        2
507    };
508    3 + length + push_qos + 1 + sequence.max_bytes() + frame_qos + batch_length
509}
510
511/// Whether a put of `payload` bytes fits one batch of `batch_bytes` with its
512/// [`allowance`] (link.v1 §2.8): zenoh fragments one that does not.
513#[must_use]
514pub fn fits_batch(
515    payload: u64,
516    batch_bytes: u64,
517    qos: PutQos,
518    sequence: Sequence,
519    protocols: &[String],
520) -> bool {
521    u128::from(payload) + u128::from(allowance(payload, qos, sequence, protocols))
522        <= u128::from(batch_bytes)
523}
524
525impl Serialize for Sequence {
526    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
527        s.serialize_str(self.as_str())
528    }
529}
530
531/// A near router's transport, `[transport]` (v2 §2.16): zenoh 1.10.1 reads
532/// it once per router, for every link. Every key resolved: an optional
533/// one the policy omits is at its default.
534#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
535pub struct Transport {
536    pub lease_ms: u64,
537    pub keep_alive: u64,
538    pub wait_before_close_ms: u64,
539    pub sequence: Sequence,
540    pub batch_bytes: u64,
541    pub open_timeout_ms: u64,
542    pub accept_timeout_ms: u64,
543    pub interests_timeout_ms: u64,
544}
545
546impl Transport {
547    /// The value a generator writes at `key`'s zenoh key (v2 §2.18), in
548    /// zenoh's units: `wait_before_close` in µs, the rest as the policy
549    /// states them.
550    #[must_use]
551    pub fn value(&self, key: TransportKey) -> Value {
552        match key {
553            TransportKey::Lease => Value::from(self.lease_ms),
554            TransportKey::KeepAlive => Value::from(self.keep_alive),
555            TransportKey::WaitBeforeClose => Value::from(self.wait_before_close_ms * 1_000),
556            TransportKey::Sequence => Value::from(self.sequence.as_str()),
557            TransportKey::BatchBytes => Value::from(self.batch_bytes),
558            TransportKey::OpenTimeout => Value::from(self.open_timeout_ms),
559            TransportKey::AcceptTimeout => Value::from(self.accept_timeout_ms),
560            TransportKey::InterestsTimeout => Value::from(self.interests_timeout_ms),
561        }
562    }
563
564    /// The keep-alive interval, `lease_ms` / `keep_alive`, in whole ms,
565    /// rounded down.
566    #[must_use]
567    pub fn keep_alive_interval_ms(&self) -> u64 {
568        self.lease_ms / self.keep_alive.max(1)
569    }
570
571    /// The keep-alive interval in words: `"60000 ms"`, or `"about 666 ms"`
572    /// where the lease is no multiple of `keep_alive`.
573    #[must_use]
574    pub fn keep_alive_interval_words(&self) -> String {
575        let exact = self.lease_ms.is_multiple_of(self.keep_alive.max(1));
576        format!(
577            "{}{} ms",
578            if exact { "" } else { "about " },
579            self.keep_alive_interval_ms()
580        )
581    }
582}
583
584/// One key of `[transport]` (v2 §2.1), with zenoh 1.10.1's configuration
585/// key it is written at.
586#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
587pub enum TransportKey {
588    Lease,
589    KeepAlive,
590    WaitBeforeClose,
591    Sequence,
592    BatchBytes,
593    OpenTimeout,
594    AcceptTimeout,
595    InterestsTimeout,
596}
597
598impl TransportKey {
599    /// Every key, in the policy's order (v2 §2.1).
600    pub const ALL: [TransportKey; 8] = [
601        TransportKey::Lease,
602        TransportKey::KeepAlive,
603        TransportKey::WaitBeforeClose,
604        TransportKey::Sequence,
605        TransportKey::BatchBytes,
606        TransportKey::OpenTimeout,
607        TransportKey::AcceptTimeout,
608        TransportKey::InterestsTimeout,
609    ];
610
611    /// The key in `[transport]`.
612    #[must_use]
613    pub fn key(self) -> &'static str {
614        match self {
615            Self::Lease => "lease_ms",
616            Self::KeepAlive => "keep_alive",
617            Self::WaitBeforeClose => "wait_before_close_ms",
618            Self::Sequence => "sequence",
619            Self::BatchBytes => "batch_bytes",
620            Self::OpenTimeout => "open_timeout_ms",
621            Self::AcceptTimeout => "accept_timeout_ms",
622            Self::InterestsTimeout => "interests_timeout_ms",
623        }
624    }
625
626    /// A finding's `at` for it, `transport.<key>`.
627    #[must_use]
628    pub fn at(self) -> String {
629        format!("transport.{}", self.key())
630    }
631
632    /// zenoh 1.10.1's configuration key, `/`-separated as
633    /// `zenoh::Config::insert_json5` takes it (`zenoh-config`'s `lib.rs`).
634    #[must_use]
635    pub fn path(self) -> &'static str {
636        match self {
637            Self::Lease => "transport/link/tx/lease",
638            Self::KeepAlive => "transport/link/tx/keep_alive",
639            Self::WaitBeforeClose => {
640                "transport/link/tx/queue/congestion_control/block/wait_before_close"
641            }
642            Self::Sequence => "transport/link/tx/sequence_number_resolution",
643            Self::BatchBytes => "transport/link/tx/batch_size",
644            Self::OpenTimeout => "transport/unicast/open_timeout",
645            Self::AcceptTimeout => "transport/unicast/accept_timeout",
646            Self::InterestsTimeout => "routing/interests/timeout",
647        }
648    }
649
650    /// The key whose zenoh key is `path`, if any.
651    #[must_use]
652    pub fn of_path(path: &str) -> Option<TransportKey> {
653        Self::ALL.into_iter().find(|k| k.path() == path)
654    }
655}
656
657/// What a generator writes beside the transport, at zenoh 1.10.1's
658/// configuration key (`zenoh-config`'s `TimestampingConf`, a
659/// `ModeDependentValue<bool>`): timestamping off for a router and a peer,
660/// so that the near router stamps no put it routes onto the face, whichever
661/// mode it runs in (v2 §2.18, core §8.2).
662pub const TIMESTAMPING_OFF: [(&str, bool); 2] = [
663    ("timestamping/enabled/router", false),
664    ("timestamping/enabled/peer", false),
665];
666
667/// The keys a router's timestamping is read from (v2 §2.19): its mode, and
668/// `timestamping/enabled`, a boolean or a value per mode.
669pub const POSTURE_PATHS: [&str; 2] = ["mode", "timestamping/enabled"];
670
671/// zenoh's three modes, the only `mode` strings its loader accepts
672/// (`zenoh-protocol`'s `WhatAmI`): any other is read as left out.
673const MODES: [&str; 3] = ["router", "peer", "client"];
674
675/// The transport keys a router's configuration states, by zenoh key, as
676/// the file writes them (v2 §2.19): a key it omits is absent, and read at
677/// the binding's default. Its mode and `timestamping/enabled`
678/// ([`POSTURE_PATHS`]) beside them, where it states them.
679///
680/// The map holds what the file writes, a `null` included. What a `null`
681/// means is read where the key is: [`StatedTransport::states`] and
682/// [`StatedTransport::runs`] for the eight keys, [`StatedTransport::stamps`]
683/// for the mode and the timestamping. So a value built from a map, as a
684/// fixture's is, reads as one [`StatedTransport::read`] made.
685#[derive(Debug, Clone, Default, PartialEq)]
686pub struct StatedTransport(pub BTreeMap<String, Value>);
687
688impl StatedTransport {
689    /// The keys `config`, a router's configuration as a JSON tree, writes:
690    /// each of [`TransportKey::ALL`]'s and [`POSTURE_PATHS`]' whose path it
691    /// holds, a `null` kept as written. Whether a `null` is a value stated
692    /// is its key's to say ([`StatedTransport::states`]).
693    #[must_use]
694    pub fn read(config: &Value) -> StatedTransport {
695        let mut out = BTreeMap::new();
696        let paths = TransportKey::ALL
697            .into_iter()
698            .map(TransportKey::path)
699            .chain(POSTURE_PATHS);
700        for path in paths {
701            let v = path
702                .split('/')
703                .try_fold(config, |node, part| node.get(part));
704            if let Some(v) = v {
705                out.insert(path.to_owned(), v.clone());
706            }
707        }
708        StatedTransport(out)
709    }
710
711    /// Whether the router stamps the puts it routes (v2 §2.19, core §4.1):
712    /// `timestamping/enabled` as a boolean, or its value for the mode the
713    /// configuration runs, `router` where it states none, as zenohd runs; a
714    /// mode the value leaves out, or no value, at zenoh 1.10.1's default,
715    /// on for a router and off for a peer and a client.
716    ///
717    /// A `null` is read as zenoh 1.10.1 reads it, as left out: each value
718    /// is an `Option` it fills with its default (`zenoh-config`'s
719    /// `ModeValues`, `unwrap_or_default!`). So is a `mode` of `null`. Any
720    /// other value that is no boolean, or a `mode` that is none of zenoh's
721    /// three, is one zenoh refuses to load ("bool or mode dependent bool";
722    /// "unknown variant", `WhatAmI`'s visitor): no router runs it, and it
723    /// is read at the default too, a refused `mode` as `router` (link.v2
724    /// 0.22 §2.19, "As data").
725    #[must_use]
726    pub fn stamps(&self) -> bool {
727        let mode = match self.0.get("mode") {
728            Some(Value::String(mode)) if MODES.contains(&mode.as_str()) => mode.as_str(),
729            // Unstated or `null`, as zenohd runs, or a value zenoh refuses:
730            // a string that is none of its three, or no string.
731            _ => "router",
732        };
733        let default = mode == "router";
734        let read = |value: Option<&Value>| match value {
735            Some(Value::Bool(b)) => *b,
736            // Left out, `null` (which zenoh reads as left out), or a value
737            // zenoh refuses to load.
738            _ => default,
739        };
740        match self.0.get("timestamping/enabled") {
741            Some(Value::Object(per_mode)) => read(per_mode.get(mode)),
742            value => read(value),
743        }
744    }
745
746    /// Whether the configuration writes a `null` at `key` that zenoh
747    /// 1.10.1 reads as left out (v2 §2.19): only at
748    /// [`TransportKey::InterestsTimeout`], `routing/interests/timeout`, an
749    /// `Option<u64>` the router fills with its default
750    /// (`unwrap_or_default!`), as `zm-1.10.2-r1` types it too. Each of the
751    /// seven other keys is no `Option`: zenoh refuses a `null` there at
752    /// load, so it stays a value stated, and no value zenoh runs.
753    #[must_use]
754    pub fn null_left_out(&self, key: TransportKey) -> bool {
755        key == TransportKey::InterestsTimeout && matches!(self.0.get(key.path()), Some(Value::Null))
756    }
757
758    /// The value the configuration states for `key`: what it writes there,
759    /// but for a `null` zenoh reads as left out
760    /// ([`StatedTransport::null_left_out`]).
761    fn stated(&self, key: TransportKey) -> Option<&Value> {
762        self.0.get(key.path()).filter(|_| !self.null_left_out(key))
763    }
764
765    /// Whether the configuration states `key`: it writes it, and not as a
766    /// `null` zenoh reads as left out.
767    #[must_use]
768    pub fn states(&self, key: TransportKey) -> bool {
769        self.stated(key).is_some()
770    }
771
772    /// What the configuration runs for `key`: the value it states, or
773    /// `defaults`'s (a binding's, [`Binding::defaults`]) where it states
774    /// none ([`StatedTransport::states`]).
775    #[must_use]
776    pub fn runs(&self, key: TransportKey, defaults: &Transport) -> Value {
777        self.stated(key)
778            .cloned()
779            .unwrap_or_else(|| defaults.value(key))
780    }
781}
782
783// ── Exposure (§2.2) ──────────────────────────────────────────────────────
784
785/// A resource's exposure, read from its resolved annotations (§2.2).
786#[derive(Debug, Clone, PartialEq, Eq)]
787pub enum Exposure {
788    /// `"host"`, or no `link.exposure`: it never crosses a constrained face.
789    Host,
790    /// `"link"`: it may cross a face that exposes.
791    Link,
792    /// A value that is no exposure, as JSON text: read as `host`.
793    Invalid(String),
794    /// On an operation, whatever the value: a call crosses by grant.
795    Ignored,
796}
797
798impl Exposure {
799    /// The fixture's token (`exposure.json`).
800    #[must_use]
801    pub fn as_str(&self) -> &'static str {
802        match self {
803            Self::Host => "host",
804            Self::Link => "link",
805            Self::Invalid(_) => "invalid",
806            Self::Ignored => "ignored",
807        }
808    }
809}
810
811/// Reads the exposure of a resource of `kind` from its resolved annotations
812/// (§2.2): `[defaults]`, then `[defaults.<kind>]`, then its own (core §9.3).
813#[must_use]
814pub fn exposure(kind: Kind, annotations: &BTreeMap<String, Value>) -> Exposure {
815    if kind == Kind::Operation {
816        return Exposure::Ignored;
817    }
818    match annotations.get(EXPOSURE) {
819        None => Exposure::Host,
820        Some(Value::String(s)) if s == "host" => Exposure::Host,
821        Some(Value::String(s)) if s == "link" => Exposure::Link,
822        Some(v) => Exposure::Invalid(v.to_string()),
823    }
824}
825
826/// [`exposure`] of a resource of a contract.
827#[must_use]
828pub fn exposure_of(r: &Resource) -> Exposure {
829    exposure(r.kind, &r.annotations)
830}
831
832/// What a face's policy lets cross (§2.1 `expose`).
833#[derive(Debug, Clone, Copy, PartialEq, Eq)]
834pub enum Expose {
835    /// Exposed resources cross.
836    Link,
837    /// No push crosses.
838    None,
839}
840
841/// What happens to a resource's pushes on a face (§2.7).
842#[derive(Debug, Clone, Copy, PartialEq, Eq)]
843pub enum Pushes {
844    /// A stream that crosses, one put per key per interval (§2.8).
845    Downsampled,
846    /// A state or an event that crosses, every put and delete (§2.7, §2.9).
847    Whole,
848    /// Denied on the face.
849    Denied,
850    /// An operation, which has no pushes (§2.9).
851    None,
852}
853
854impl Pushes {
855    /// The fixture's token.
856    #[must_use]
857    pub fn as_str(self) -> &'static str {
858        match self {
859            Self::Downsampled => "downsampled",
860            Self::Whole => "whole",
861            Self::Denied => "denied",
862            Self::None => "none",
863        }
864    }
865}
866
867/// Why, the first of these that holds, in this order (`exposure.json`).
868#[derive(Debug, Clone, Copy, PartialEq, Eq)]
869pub enum Reason {
870    /// An operation: its calls cross by grant (§2.9).
871    RequestsOnly,
872    /// A value that is no exposure, read as `host` (§2.2).
873    Invalid,
874    /// `host`, or no annotation (§2.2).
875    Host,
876    /// The face exposes none (§2.1).
877    FaceClosed,
878    /// A stream whose template has a parameter: no rule names its members
879    /// (§2.8).
880    Templated,
881    /// link.v2's: a frame resource on a face whose `frames` does not list it
882    /// (v2 §2.7).
883    Unlisted,
884    /// link.v2's: a stream that would be downsampled, and declares
885    /// `timing.deadline_ms` (v2 §2.8).
886    Timed,
887    /// It crosses.
888    Exposed,
889}
890
891impl Reason {
892    /// The fixture's token.
893    #[must_use]
894    pub fn as_str(self) -> &'static str {
895        match self {
896            Self::RequestsOnly => "requests_only",
897            Self::Invalid => "invalid",
898            Self::Host => "host",
899            Self::FaceClosed => "face_closed",
900            Self::Templated => "templated",
901            Self::Unlisted => "unlisted",
902            Self::Timed => "timed",
903            Self::Exposed => "exposed",
904        }
905    }
906}
907
908/// Whether a resource's pushes cross a face, and why (§2.7).
909#[derive(Debug, Clone, Copy, PartialEq, Eq)]
910pub struct Crossing {
911    pub pushes: Pushes,
912    pub reason: Reason,
913}
914
915impl Crossing {
916    /// Whether its pushes cross (§0's "crossing").
917    #[must_use]
918    pub fn crosses(self) -> bool {
919        matches!(self.pushes, Pushes::Downsampled | Pushes::Whole)
920    }
921}
922
923/// Whether the pushes of a resource of `token` cross a face that exposes
924/// `expose` (§2.7): `templated` when its template has a parameter.
925#[must_use]
926pub fn crossing(
927    token: KindToken,
928    templated: bool,
929    exposure: &Exposure,
930    expose: Expose,
931) -> Crossing {
932    let denied = |reason| Crossing {
933        pushes: Pushes::Denied,
934        reason,
935    };
936    if token == KindToken::Op {
937        return Crossing {
938            pushes: Pushes::None,
939            reason: Reason::RequestsOnly,
940        };
941    }
942    match exposure {
943        Exposure::Ignored => Crossing {
944            pushes: Pushes::None,
945            reason: Reason::RequestsOnly,
946        },
947        Exposure::Invalid(_) => denied(Reason::Invalid),
948        Exposure::Host => denied(Reason::Host),
949        Exposure::Link if expose == Expose::None => denied(Reason::FaceClosed),
950        Exposure::Link if is_stream(token) && templated => denied(Reason::Templated),
951        Exposure::Link if is_stream(token) => Crossing {
952            pushes: Pushes::Downsampled,
953            reason: Reason::Exposed,
954        },
955        Exposure::Link => Crossing {
956            pushes: Pushes::Whole,
957            reason: Reason::Exposed,
958        },
959    }
960}
961
962/// What link.v2 reads of a resource's own declaration, beside its exposure,
963/// to say whether it crosses (v2 §2.7, §2.8).
964#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
965pub struct Shape {
966    /// Its template has a parameter.
967    pub templated: bool,
968    /// It is a frame resource (core §7.7): never downsampled.
969    pub frame: bool,
970    /// Its resolved annotations hold `timing.deadline_ms`, whatever its
971    /// value ([`timed`]).
972    pub timed: bool,
973}
974
975impl Shape {
976    /// The shape of a resource of `token`: `templated` when its template
977    /// has a parameter, `frame` when it is a frame resource, and timed when
978    /// it is a stream whose `annotations` hold `timing.deadline_ms`.
979    #[must_use]
980    pub fn of(
981        token: KindToken,
982        templated: bool,
983        frame: bool,
984        annotations: &BTreeMap<String, Value>,
985    ) -> Self {
986        Shape {
987            templated,
988            frame,
989            timed: is_stream(token) && timed(annotations),
990        }
991    }
992}
993
994/// Whether resolved annotations hold `timing.deadline_ms` (v2 §2.8). Its
995/// value is not read: an invalid one still says the contract meant a
996/// deadline, and the plan fails closed.
997#[must_use]
998pub fn timed(annotations: &BTreeMap<String, Value>) -> bool {
999    annotations.contains_key(crate::timing::DEADLINE_MS)
1000}
1001
1002/// link.v2's reading of whether a resource's pushes cross a face (v2 §2.7,
1003/// §2.8): [`crossing`]'s, and then a frame resource crosses whole, never
1004/// downsampled, unless the face's `frames` leaves it out (`listed`
1005/// `Some(false)`; `None` for a face with no `frames`), an exposed event
1006/// crosses whole unless the face's `events` leaves it out (`listed` alike,
1007/// from `events`), and a stream that would be downsampled is denied when
1008/// it is timed.
1009#[must_use]
1010pub fn crossing_v2(
1011    token: KindToken,
1012    shape: Shape,
1013    exposure: &Exposure,
1014    expose: Expose,
1015    listed: Option<bool>,
1016) -> Crossing {
1017    let c = crossing(token, shape.templated, exposure, expose);
1018    let denied = |reason| Crossing {
1019        pushes: Pushes::Denied,
1020        reason,
1021    };
1022    if token == KindToken::Events && c.pushes == Pushes::Whole && listed == Some(false) {
1023        return denied(Reason::Unlisted);
1024    }
1025    if c.pushes != Pushes::Downsampled {
1026        return c;
1027    }
1028    if shape.frame {
1029        if listed == Some(false) {
1030            return denied(Reason::Unlisted);
1031        }
1032        return Crossing {
1033            pushes: Pushes::Whole,
1034            reason: Reason::Exposed,
1035        };
1036    }
1037    if shape.timed {
1038        return denied(Reason::Timed);
1039    }
1040    c
1041}
1042
1043/// Whether a resource breaks link.v2's packed requirement (v2 §2.17): its
1044/// contract lists `link.v2`, it is a stream, a state or an event exposed
1045/// `link`, and its type is not packed.
1046#[must_use]
1047pub fn packed_required(uses_v2: bool, token: KindToken, exposure: &Exposure, packed: bool) -> bool {
1048    uses_v2 && token != KindToken::Op && *exposure == Exposure::Link && !packed
1049}
1050
1051/// A contract's findings under link.v2's contract side (v2 §2.17): for a
1052/// contract that lists `link.v2`, `packed_required` at each resource it
1053/// exposes `link` whose type is not packed, `at` its name (§0), with no
1054/// face. None for any other contract.
1055#[must_use]
1056pub fn contract_findings(c: &Contract) -> Vec<Finding> {
1057    let v2 = uses_v2(c);
1058    let mut out: Vec<Finding> = c
1059        .resources
1060        .iter()
1061        .map(|r| Res::of(c, r))
1062        .filter(|r| {
1063            packed_required(
1064                v2,
1065                r.token,
1066                &exposure(kind_of(r.token), &r.annotations),
1067                r.packed,
1068            )
1069        })
1070        .map(|r| {
1071            Finding::new(
1072                Code::PackedRequired,
1073                None,
1074                res_name(&c.iface.to_string(), &r),
1075            )
1076        })
1077        .collect();
1078    sort_findings(&mut out);
1079    out
1080}
1081
1082fn is_stream(token: KindToken) -> bool {
1083    matches!(token, KindToken::Stream | KindToken::ExplicitStream)
1084}
1085
1086fn is_state(token: KindToken) -> bool {
1087    matches!(token, KindToken::State | KindToken::ExplicitState)
1088}
1089
1090/// The kind a token carries (core §1.3).
1091#[must_use]
1092pub fn kind_of(token: KindToken) -> Kind {
1093    match token {
1094        KindToken::Stream | KindToken::ExplicitStream => Kind::Stream,
1095        KindToken::State | KindToken::ExplicitState => Kind::State,
1096        KindToken::Events => Kind::Event,
1097        KindToken::Op => Kind::Operation,
1098    }
1099}
1100
1101// ── Findings (§2.1, §2.3, §2.11, §2.15) ───────────────────────────────────
1102
1103/// The closed vocabulary of findings.
1104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1105pub enum Code {
1106    /// The file is not TOML 1.0 (§2.1).
1107    Toml,
1108    /// A key the format does not define (§2.1).
1109    UnknownField,
1110    /// A required key absent (§2.1).
1111    MissingField,
1112    /// A value of the wrong type or outside its range (§2.1).
1113    BadValue,
1114    /// `attach = "router"` (§2.5).
1115    RouterAttach,
1116    /// `select.interfaces` (§2.14).
1117    SelectInterfaces,
1118    /// A link protocol zenoh 1.10.1 does not name (§2.1).
1119    UnknownProtocol,
1120    /// Two faces with a common link protocol (§2.14).
1121    SharedProtocol,
1122    /// A batch over a third of the lease (§2.10).
1123    BatchOverLease,
1124    /// Two or more faces naming one far principal, whose policy then
1125    /// carries every one of their plans' denies on each of them (§2.1,
1126    /// §2.4, 0.7, F-125).
1127    FarOfTwoFaces,
1128    /// A listed service the deployment names no interfaces for (§2.3).
1129    ServiceUnknown,
1130    /// An interface whose contract is not given (§2.3).
1131    ContractUnknown,
1132    /// An exposed stream with a parameter, denied (§2.8).
1133    TemplatedExposure,
1134    /// An exposed resource a deny must include (§2.7).
1135    CarveOutOverlap,
1136    /// A crossing stream whose horizon is below twice the interval
1137    /// (§2.12).
1138    IntervalOverHorizon,
1139    /// Revisions of a listed interface that disagree on a resource's
1140    /// exposure, one `link` and another not: it does not cross (§2.3, 0.3).
1141    ExposureDisagrees,
1142    /// A crossing frame resource whose interval is shorter than the
1143    /// face's `interval_s`: never downsampled, it crosses at its own
1144    /// cadence (§2.8).
1145    FrameOverInterval,
1146    /// A crossing frame resource whose largest frame, with its
1147    /// [`allowance`], does not fit the face's batch: it is fragmented, and
1148    /// lost whole (§2.8).
1149    FrameOverBatch,
1150    /// A crossing frame resource that declares `history`: every put pays
1151    /// the advanced publisher's source info across the face, and its
1152    /// history stays home (§2.8).
1153    HistoryOnFrame,
1154    /// A listed service whose owner heartbeats the deployment turns on,
1155    /// implementing an interface whose heartbeat crosses a `link.v1` face:
1156    /// no owner heartbeat crosses one, so its far readers may hear no
1157    /// confirmation (§2.3, §2.9; #1145).
1158    OwnerHeartbeatDenied,
1159    /// A listed owner's tombstone window below the outage (§2.11).
1160    WindowUnderOutage,
1161    /// A block whose denies leave a pair of `@zk` open (§2.15).
1162    ZkNotDenied,
1163    /// A downsampling rule that is not one concrete key (§2.15).
1164    WildcardDownsampling,
1165    /// Two downsampling rules that intersect (§2.15).
1166    IntersectingDownsampling,
1167    /// A block whose access control is not enabled: zenoh enforces none of
1168    /// its rules (§2.15, 0.7, F-124).
1169    BlockDisabled,
1170    /// A subject on the face bound to another principal than the face's
1171    /// far one, whatever else it names (§2.4, §2.15, 0.3; widened in 0.4,
1172    /// F-120).
1173    NearSubjectOnFace,
1174    /// Under `allow`, a link protocol of the face that no face subject
1175    /// naming no interface and no zid selects (§2.4, §2.15, 0.3).
1176    FaceSubjectMissing,
1177    /// A face subject that also selects sessions off the face (§2.4,
1178    /// §2.15, 0.4, F-120).
1179    FaceSubjectBeyondFace,
1180    /// A face subject not listed in exactly the far principal's policies
1181    /// (§2.4, §2.15, 0.4, F-120).
1182    FaceSubjectMisplaced,
1183    /// Under `allow`, a name the block binds whose session over a link
1184    /// protocol it is not kept off matches no subject (§2.4, §2.15, 0.4,
1185    /// F-120).
1186    NarrowedTooFar,
1187    /// A link.v2 policy with no `[transport]` (v2 §2.1).
1188    TransportMissing,
1189    /// A face's `lease_ms` or `batch_bytes` in a link.v2 policy: they are
1190    /// `[transport]`'s (v2 §2.1).
1191    MovedField,
1192    /// `wait_before_close` below the lease, in a policy or a router's
1193    /// configuration (v2 §2.16, §2.19).
1194    WaitUnderLease,
1195    /// A face's loss makes more than one false close a day likely (v2
1196    /// §2.16).
1197    KeepAliveFlaps,
1198    /// One lease can carry the sequence window in full batches (v2 §2.16).
1199    SequenceWindow,
1200    /// An open or accept timeout below twice the handshake's air (v2
1201    /// §2.16).
1202    OpenUnderHandshake,
1203    /// A face's reply timeout below 16 full batches' air (v2 §2.1).
1204    ReplyTimeoutShort,
1205    /// A face whose medium repairs no lost frame (v2 §2.1).
1206    NoArq,
1207    /// A router's configuration runs a transport key other than the
1208    /// policy's (v2 §2.19).
1209    TransportDiffers,
1210    /// The far end's lease or keep-alive is not the near router's (v2
1211    /// §2.19).
1212    PeerDiffers,
1213    /// A router's configuration stamps the puts it routes onto the face
1214    /// (v2 §2.18, §2.19; core §8.2).
1215    FaceTimestamping,
1216    /// The catalog the far side holds is not the policy's (v2 §2.19).
1217    CatalogMismatch,
1218    /// A contract that lists `link.v2` exposes a resource whose type is not
1219    /// packed (v2 §2.17).
1220    PackedRequired,
1221    /// A crossing resource of a contract that does not list `link.v2`,
1222    /// whose type is not packed (v2 §2.3, §2.17).
1223    NotPacked,
1224    /// A face's `frames` entry that names no frame resource of a listed
1225    /// interface (v2 §2.7).
1226    FrameUnknown,
1227    /// A face's `events` entry that names no event resource of a listed
1228    /// interface (v2 §2.7). An event that is listed but not exposed is
1229    /// denied, never this.
1230    EventUnknown,
1231    /// An exposed frame resource of a listed interface that a face's
1232    /// `frames` leaves out, and that crosses no face of the policy (v2
1233    /// §2.7).
1234    FrameUnlisted,
1235    /// A listed frame whose `keyframe_s` its contract's `keyframe_every`
1236    /// cannot reach at the face's `every_s` (v2 §2.7).
1237    KeyframeUnreachable,
1238    /// A crossing heartbeat, owner heartbeat or frame resource whose
1239    /// horizon is below the face's `horizon_s` (v2 §2.9, §2.12).
1240    HorizonUnderFace,
1241    /// A crossing `block` resource whose longest put, with its
1242    /// [`allowance`], does not fit the batch, or a crossing owner
1243    /// heartbeat's, `at` `freshness.v2/stream/heartbeats/link` (v2 §2.16).
1244    BlockOverBatch,
1245    /// A face whose shortest crossing cadence is the keep-alive interval
1246    /// or above it (v2 §2.16).
1247    KeepAliveNotSuppressed,
1248    /// A timed stream, denied rather than downsampled (v2 §2.8).
1249    TimedDownsampled,
1250    /// A revision of an interface that crosses the face, which the
1251    /// deployment's catalog does not list (v2 §2.18).
1252    CatalogMissing,
1253    /// A device the policy lists elsewhere: among `services`, or in
1254    /// another face's `devices` (v2 §2.1, §2.5).
1255    DeviceListed,
1256    /// A device that implements `archive.v1`, or an interface a revision
1257    /// given of which uses `redundancy.v1` or `redundancy.v2`: each needs
1258    /// presence on its peers' side of the face (v2 §2.5, 0.29; core §8.1,
1259    /// `redundancy.v2` §2.13).
1260    PresenceRequired,
1261    /// On a device face, a template of a device's interface that declares
1262    /// `epoch`: its member tokens cross the face at each transport, and the
1263    /// face denies them (v2 §2.5).
1264    EpochOnDevice,
1265    /// A face the near router opens (`opens = "near"`) whose far principal
1266    /// the deployment binds by a user name: zenoh's usrpwd binds a user
1267    /// name only to a link the router accepted (v2 §2.5).
1268    NearOpensUser,
1269    /// Under `allow`, a face the near router opens whose far principal is a
1270    /// user name: planned, and nobody across it is authenticated (v2 §2.5).
1271    NearOpensUnauthenticated,
1272}
1273
1274impl Code {
1275    /// The fixture's token.
1276    #[must_use]
1277    pub fn as_str(self) -> &'static str {
1278        match self {
1279            Self::Toml => "toml",
1280            Self::UnknownField => "unknown_field",
1281            Self::MissingField => "missing_field",
1282            Self::BadValue => "bad_value",
1283            Self::RouterAttach => "router_attach",
1284            Self::SelectInterfaces => "select_interfaces",
1285            Self::UnknownProtocol => "unknown_protocol",
1286            Self::SharedProtocol => "shared_protocol",
1287            Self::BatchOverLease => "batch_over_lease",
1288            Self::FarOfTwoFaces => "far_of_two_faces",
1289            Self::ServiceUnknown => "service_unknown",
1290            Self::ContractUnknown => "contract_unknown",
1291            Self::TemplatedExposure => "templated_exposure",
1292            Self::CarveOutOverlap => "carve_out_overlap",
1293            Self::IntervalOverHorizon => "interval_over_horizon",
1294            Self::ExposureDisagrees => "exposure_disagrees",
1295            Self::FrameOverInterval => "frame_over_interval",
1296            Self::FrameOverBatch => "frame_over_batch",
1297            Self::HistoryOnFrame => "history_on_frame",
1298            Self::OwnerHeartbeatDenied => "owner_heartbeat_denied",
1299            Self::WindowUnderOutage => "window_under_outage",
1300            Self::ZkNotDenied => "zk_not_denied",
1301            Self::WildcardDownsampling => "wildcard_downsampling",
1302            Self::IntersectingDownsampling => "intersecting_downsampling",
1303            Self::BlockDisabled => "block_disabled",
1304            Self::NearSubjectOnFace => "near_subject_on_face",
1305            Self::FaceSubjectMissing => "face_subject_missing",
1306            Self::FaceSubjectBeyondFace => "face_subject_beyond_face",
1307            Self::FaceSubjectMisplaced => "face_subject_misplaced",
1308            Self::NarrowedTooFar => "narrowed_too_far",
1309            Self::TransportMissing => "transport_missing",
1310            Self::MovedField => "moved_field",
1311            Self::WaitUnderLease => "wait_under_lease",
1312            Self::KeepAliveFlaps => "keep_alive_flaps",
1313            Self::SequenceWindow => "sequence_window",
1314            Self::OpenUnderHandshake => "open_under_handshake",
1315            Self::ReplyTimeoutShort => "reply_timeout_short",
1316            Self::NoArq => "no_arq",
1317            Self::TransportDiffers => "transport_differs",
1318            Self::PeerDiffers => "peer_differs",
1319            Self::FaceTimestamping => "face_timestamping",
1320            Self::CatalogMismatch => "catalog_mismatch",
1321            Self::PackedRequired => "packed_required",
1322            Self::NotPacked => "not_packed",
1323            Self::FrameUnknown => "frame_unknown",
1324            Self::EventUnknown => "event_unknown",
1325            Self::FrameUnlisted => "frame_unlisted",
1326            Self::KeyframeUnreachable => "keyframe_unreachable",
1327            Self::HorizonUnderFace => "horizon_under_face",
1328            Self::BlockOverBatch => "block_over_batch",
1329            Self::KeepAliveNotSuppressed => "keep_alive_not_suppressed",
1330            Self::TimedDownsampled => "timed_downsampled",
1331            Self::CatalogMissing => "catalog_missing",
1332            Self::DeviceListed => "device_listed",
1333            Self::PresenceRequired => "presence_required",
1334            Self::EpochOnDevice => "epoch_on_device",
1335            Self::NearOpensUser => "near_opens_user",
1336            Self::NearOpensUnauthenticated => "near_opens_unauthenticated",
1337        }
1338    }
1339
1340    /// Its severity, fixed per code.
1341    #[must_use]
1342    pub fn severity(self) -> Severity {
1343        match self {
1344            Self::BatchOverLease
1345            | Self::FarOfTwoFaces
1346            | Self::TemplatedExposure
1347            | Self::CarveOutOverlap
1348            | Self::IntervalOverHorizon
1349            | Self::ExposureDisagrees
1350            | Self::FrameOverInterval
1351            | Self::FrameOverBatch
1352            | Self::HistoryOnFrame
1353            | Self::OwnerHeartbeatDenied
1354            | Self::KeepAliveFlaps
1355            | Self::SequenceWindow
1356            | Self::OpenUnderHandshake
1357            | Self::ReplyTimeoutShort
1358            | Self::NoArq
1359            | Self::PeerDiffers
1360            | Self::FaceTimestamping
1361            | Self::NotPacked
1362            | Self::FrameUnlisted
1363            | Self::HorizonUnderFace
1364            | Self::BlockOverBatch
1365            | Self::KeepAliveNotSuppressed
1366            | Self::TimedDownsampled
1367            | Self::EpochOnDevice
1368            | Self::NearOpensUnauthenticated => Severity::Warning,
1369            _ => Severity::Error,
1370        }
1371    }
1372}
1373
1374impl fmt::Display for Code {
1375    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1376        f.write_str(self.as_str())
1377    }
1378}
1379
1380impl Serialize for Code {
1381    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1382        s.serialize_str(self.as_str())
1383    }
1384}
1385
1386/// An error refuses the policy, or the plan; a warning does not.
1387#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
1388#[serde(rename_all = "snake_case")]
1389pub enum Severity {
1390    Error,
1391    Warning,
1392}
1393
1394/// One finding: what, about which face, at which key (§2.1).
1395#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
1396pub struct Finding {
1397    pub code: Code,
1398    pub severity: Severity,
1399    /// The face's name, or `None` for the top level and the deployment.
1400    pub face: Option<String>,
1401    /// The key it is about (§2.1), the service, the interface, the
1402    /// resource's name, or the rule's key expression.
1403    pub at: String,
1404}
1405
1406impl Finding {
1407    /// A finding of `code`, with its fixed severity.
1408    #[must_use]
1409    pub fn new(code: Code, face: Option<&str>, at: impl Into<String>) -> Self {
1410        Finding {
1411            code,
1412            severity: code.severity(),
1413            face: face.map(str::to_owned),
1414            at: at.into(),
1415        }
1416    }
1417
1418    /// Whether it refuses the policy or the plan.
1419    #[must_use]
1420    pub fn is_error(&self) -> bool {
1421        self.severity == Severity::Error
1422    }
1423}
1424
1425impl fmt::Display for Finding {
1426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1427        let sev = match self.severity {
1428            Severity::Error => "error",
1429            Severity::Warning => "warning",
1430        };
1431        match &self.face {
1432            Some(face) => write!(f, "{sev} {} [face {face}] {}", self.code, self.at),
1433            None => write!(f, "{sev} {} {}", self.code, self.at),
1434        }
1435    }
1436}
1437
1438/// Sorts findings by face (none first), `at`, then code, each by its bytes,
1439/// and drops the repeated ones: findings are a set (§2.1).
1440pub fn sort_findings(findings: &mut Vec<Finding>) {
1441    findings.sort_by(|a, b| {
1442        a.face
1443            .cmp(&b.face)
1444            .then_with(|| a.at.cmp(&b.at))
1445            .then_with(|| a.code.as_str().cmp(b.code.as_str()))
1446    });
1447    findings.dedup();
1448}
1449
1450// ── The face policy (§2.1) ───────────────────────────────────────────────
1451
1452/// How the far side attaches (§2.5; v2 §2.5).
1453#[derive(Debug, Clone, PartialEq, Eq)]
1454pub enum Attach {
1455    /// One far-side session, or a gateway session, as a client.
1456    Client,
1457    /// A far router in a south region, named by its `region_name`.
1458    SouthRegion { region: String },
1459    /// link.v2's device face (v2 §2.5): the sessions of owners on a first
1460    /// hop (core §8.1), each a client of the near router, by address
1461    /// `<system>/<service>`, sorted by their bytes.
1462    Device { devices: Vec<String> },
1463}
1464
1465impl Attach {
1466    /// The devices a device face attaches; none for any other face.
1467    #[must_use]
1468    pub fn devices(&self) -> &[String] {
1469        match self {
1470            Attach::Device { devices } => devices,
1471            _ => &[],
1472        }
1473    }
1474
1475    /// Whether it is a device face (v2 §2.5).
1476    #[must_use]
1477    pub fn is_device(&self) -> bool {
1478        matches!(self, Attach::Device { .. })
1479    }
1480}
1481
1482/// Which end of a face opens its links (v2 §2.1, §2.5): connects, where
1483/// the other accepts.
1484#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1485pub enum Opens {
1486    /// The far end: the far side's session, gateway or router connects to
1487    /// the near router. Every shape's default, and `client`'s and
1488    /// `device`'s only.
1489    #[default]
1490    Far,
1491    /// The near router connects to the far router: `south-region` only.
1492    Near,
1493}
1494
1495/// One constrained face of a router (§2.1).
1496#[derive(Debug, Clone, PartialEq, Eq)]
1497pub struct Face {
1498    /// The far principal: a user name or a certificate CN (core §11.1).
1499    pub far: String,
1500    pub attach: Attach,
1501    /// `select.link_protocols`, in the policy's order.
1502    pub link_protocols: Vec<String>,
1503    pub expose: Expose,
1504    /// Exactly when `expose` is [`Expose::Link`].
1505    pub interval_s: Option<u64>,
1506    pub max_outage_s: u64,
1507    /// The face's `batch_bytes` in a `link.v1` policy; `[transport]`'s in a
1508    /// link.v2 one (v2 §2.10).
1509    pub batch_bytes: u64,
1510    pub link_bps: u64,
1511    /// The face's `lease_ms` in a `link.v1` policy, [`DEFAULT_LEASE_MS`]
1512    /// when it gives none; `[transport]`'s in a link.v2 one.
1513    pub lease_ms: u64,
1514    /// link.v2's (v2 §2.1): the share of frames the medium loses, in parts
1515    /// per million. `None` in a `link.v1` policy, as the next two.
1516    pub loss_ppm: Option<u64>,
1517    /// link.v2's: whether the medium repairs a lost frame below zenoh.
1518    pub arq: Option<bool>,
1519    /// link.v2's: how long a caller across the face waits for a reply, the
1520    /// deployment's word to every caller.
1521    pub reply_timeout_ms: Option<u64>,
1522    /// link.v2's `frames` (v2 §2.7): the frame resources that cross the
1523    /// face, by their name (§0, `<iface>/stream/<template>`), each at its
1524    /// cadence. `None` when the face lists none: every exposed frame
1525    /// resource crosses, as `link.v1` §2.7 says.
1526    pub frames: Option<BTreeMap<String, FrameCadence>>,
1527    /// link.v2's `events` (v2 §2.7): the event resources that cross the
1528    /// face, by their name (§0, `<iface>/events/<template>`). `None` when
1529    /// the face lists none: every exposed event crosses, as `link.v1` §2.7
1530    /// says.
1531    pub events: Option<BTreeSet<String>>,
1532    /// link.v2's `horizon_s` (v2 §2.12): the shortest horizon the face
1533    /// affords a crossing heartbeat or frame resource.
1534    pub horizon_s: Option<u64>,
1535    /// link.v2's `opens` (v2 §2.1, §2.5): which end opens the face's links.
1536    /// [`Opens::Far`] in a `link.v1` policy, and where it states none.
1537    pub opens: Opens,
1538}
1539
1540/// A listed frame's cadence on a face (v2 §2.7): the deployment's word to
1541/// the far side.
1542#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1543pub struct FrameCadence {
1544    /// How often its owner puts a frame on this face, in seconds.
1545    pub every_s: u64,
1546    /// The longest the face accepts between two full records, in seconds.
1547    #[serde(skip_serializing_if = "Option::is_none")]
1548    pub keyframe_s: Option<u64>,
1549}
1550
1551impl Face {
1552    /// Whether a batch takes at most a third of the lease to cross (§2.10):
1553    /// `batch_bytes` × 24,000 ≤ `lease_ms` × `link_bps`, in integers.
1554    #[must_use]
1555    pub fn batch_within_lease(&self) -> bool {
1556        within_lease(self.batch_bytes, self.link_bps, self.lease_ms)
1557    }
1558
1559    /// The downsampling frequency, 1/`interval_s` Hz, the quotient as an
1560    /// IEEE 754 double (§2.8). `interval_s` is at most 2^32−1, which a
1561    /// double holds exactly.
1562    #[must_use]
1563    pub fn freq(&self) -> Option<f64> {
1564        self.interval_s
1565            .map(|n| 1.0 / f64::from(u32::try_from(n).unwrap_or(u32::MAX)))
1566    }
1567}
1568
1569fn within_lease(batch_bytes: u64, link_bps: u64, lease_ms: u64) -> bool {
1570    u128::from(batch_bytes) * 24_000 <= u128::from(lease_ms) * u128::from(link_bps)
1571}
1572
1573/// Whether more than one false close a day is expected (v2 §2.16): 2 ×
1574/// 86,400 × 1,000 × `keep_alive` × `loss_ppm`^(`keep_alive` − 1) >
1575/// `lease_ms` × 10^(6 × (`keep_alive` − 1)), exactly.
1576fn flaps(lease_ms: u64, keep_alive: u64, loss_ppm: u64) -> bool {
1577    use num_bigint::BigUint;
1578    let n = u32::try_from(keep_alive.saturating_sub(1)).unwrap_or(u32::MAX);
1579    let lhs = BigUint::from(172_800_000u64) * keep_alive * BigUint::from(loss_ppm).pow(n);
1580    let rhs = BigUint::from(lease_ms) * BigUint::from(1_000_000u64).pow(n);
1581    lhs > rhs
1582}
1583
1584/// Whether one lease can carry the sequence window in full batches (v2
1585/// §2.16): window × 8 × `batch_bytes` × 1,000 ≤ `lease_ms` × `link_bps`.
1586fn window_filled(sequence: Sequence, batch_bytes: u64, lease_ms: u64, link_bps: u64) -> bool {
1587    u128::from(sequence.window()) * 8 * u128::from(batch_bytes) * 1_000
1588        <= u128::from(lease_ms) * u128::from(link_bps)
1589}
1590
1591/// Whether a timeout is below twice the 384-byte handshake's air at
1592/// `link_bps` (v2 §2.16): timeout × `link_bps` < 2 × 384 × 8 × 1,000.
1593fn under_handshake(timeout_ms: u64, link_bps: u64) -> bool {
1594    u128::from(timeout_ms) * u128::from(link_bps) < 6_144_000
1595}
1596
1597/// Whether a reply timeout is below 16 full batches' air (v2 §2.1):
1598/// `reply_timeout_ms` × `link_bps` < 16 × 8 × 1,000 × `batch_bytes`.
1599fn reply_short(reply_timeout_ms: u64, link_bps: u64, batch_bytes: u64) -> bool {
1600    u128::from(reply_timeout_ms) * u128::from(link_bps) < 128_000 * u128::from(batch_bytes)
1601}
1602
1603/// A router's face policy (§2.1; v2 §2.1).
1604#[derive(Debug, Clone, PartialEq, Eq)]
1605pub struct FacePolicy {
1606    /// The text it is read by.
1607    pub profile: Profile,
1608    pub system: String,
1609    /// The listed services, on `system`.
1610    pub services: Vec<String>,
1611    /// The faces, by name.
1612    pub faces: BTreeMap<String, Face>,
1613    /// The zenoh the near router runs (v2 §2.4); a `link.v1` policy's is
1614    /// `zenoh-1.10.1`.
1615    pub binding: Binding,
1616    /// The binding's name as the policy spells it (#1204): `binding` reads
1617    /// `zm-1.10.2-r2` as `zm-1.10.2-r1`'s binding (v2 §2.4), and what a plan
1618    /// writes for a reader names the release the policy names.
1619    pub binding_name: String,
1620    /// The near router's transport (v2 §2.16): a link.v2 policy's, `None`
1621    /// for a `link.v1` one.
1622    pub transport: Option<Transport>,
1623    /// The catalog's id the far side decodes with (v2 §2.1), when a
1624    /// link.v2 policy names one.
1625    pub catalog: Option<String>,
1626}
1627
1628impl FacePolicy {
1629    /// A listed service's address, `<system>/<service>`.
1630    #[must_use]
1631    pub fn address(&self, service: &str) -> String {
1632        format!("{}/{service}", self.system)
1633    }
1634
1635    /// Every device a face of the policy attaches, by address, with its
1636    /// face's name (v2 §2.5), in the faces' order and each face's.
1637    pub fn devices(&self) -> impl Iterator<Item = (&str, &str)> {
1638        self.faces.iter().flat_map(|(name, f)| {
1639            f.attach
1640                .devices()
1641                .iter()
1642                .map(move |d| (name.as_str(), d.as_str()))
1643        })
1644    }
1645
1646    /// The face that attaches the device at `address`, when one does. A
1647    /// device sits on one face only (`device_listed`, v2 §2.1): a policy
1648    /// the linter accepted never lists it twice.
1649    #[must_use]
1650    pub fn device_face(&self, address: &str) -> Option<&str> {
1651        debug_assert!(
1652            self.devices().filter(|(_, d)| *d == address).count() <= 1,
1653            "{address} on more than one device face: the linter's device_listed refuses it"
1654        );
1655        self.devices()
1656            .find(|(_, d)| *d == address)
1657            .map(|(name, _)| name)
1658    }
1659
1660    /// Every listed owner the plan reads (v2 §2.5): each listed service,
1661    /// then each device, sorted by address. Each is `(address, the key the
1662    /// deployment's `implements` names it by, the face that attaches it
1663    /// when it is a device)`.
1664    #[must_use]
1665    pub fn owners(&self) -> Vec<Owner<'_>> {
1666        let mut out: Vec<Owner<'_>> = self
1667            .services
1668            .iter()
1669            .map(|s| Owner {
1670                address: self.address(s),
1671                key: s.as_str(),
1672                device_face: None,
1673            })
1674            .chain(self.devices().map(|(face, d)| Owner {
1675                address: d.to_owned(),
1676                key: d,
1677                device_face: Some(face),
1678            }))
1679            .collect();
1680        out.sort_by(|a, b| a.address.cmp(&b.address));
1681        out
1682    }
1683}
1684
1685/// One listed owner of a policy, as the plan reads it: a listed service,
1686/// or a device (v2 §2.5).
1687#[derive(Debug, Clone, PartialEq, Eq)]
1688pub struct Owner<'a> {
1689    /// `<system>/<service>`.
1690    pub address: String,
1691    /// The key the deployment's `implements` names it by: a listed
1692    /// service by its bare name (`radio-a`, on the policy's `system`), a
1693    /// device by its address (`lab/radio-a`), since a device may sit on
1694    /// any system (v2 §2.5).
1695    pub key: &'a str,
1696    /// The face that attaches it, for a device.
1697    pub device_face: Option<&'a str>,
1698}
1699
1700impl FacePolicy {
1701    /// What a reader or a caller across `face` reads of this policy (v2
1702    /// §2.20, §2.21): a link.v2 policy's face. A `link.v1` policy states
1703    /// no reply timeout and no transport, and is refused, as a face it
1704    /// does not name is.
1705    pub fn far_side(&self, face: &str) -> Result<FarSide, FarSideRefusal> {
1706        let (Profile::V2, Some(transport)) = (self.profile, self.transport) else {
1707            return Err(FarSideRefusal::NotV2);
1708        };
1709        let Some(f) = self.faces.get(face) else {
1710            return Err(FarSideRefusal::NoFace {
1711                face: face.to_owned(),
1712                faces: self.faces.keys().cloned().collect(),
1713            });
1714        };
1715        // A link.v2 face that parsed states both (v2 §2.1).
1716        let (Some(reply_timeout_ms), Some(arq)) = (f.reply_timeout_ms, f.arq) else {
1717            return Err(FarSideRefusal::NotV2);
1718        };
1719        Ok(FarSide {
1720            face: face.to_owned(),
1721            reply_timeout_ms,
1722            arq,
1723            transport,
1724        })
1725    }
1726}
1727
1728// ── link.v2: the far side's readers and callers (v2 §2.20, §2.21) ────────
1729
1730/// How many horizons of silence a subscription across a face waits before
1731/// it is declared again (core §8.5, v2 §2.21).
1732pub const SILENT_HORIZONS: u32 = 2;
1733
1734/// What a reader or a caller on the far side of one face of a link.v2
1735/// policy takes from the policy (v2 §2.20, §2.21; core §8.1, §8.5): how
1736/// long a reply may take, whether the medium repairs a lost frame, and the
1737/// transport its own session runs (v2 §2.16).
1738#[derive(Debug, Clone, PartialEq, Eq)]
1739pub struct FarSide {
1740    /// The face's name in the policy.
1741    pub face: String,
1742    /// `reply_timeout_ms`: the deployment's word to every caller across
1743    /// the face (v2 §2.1).
1744    pub reply_timeout_ms: u64,
1745    /// `arq`: whether the medium repairs a lost frame below zenoh.
1746    pub arq: bool,
1747    /// The router's `[transport]`, which both ends run (v2 §2.16).
1748    pub transport: Transport,
1749}
1750
1751impl FarSide {
1752    /// How long a caller across the face waits at least (core §8.1).
1753    #[must_use]
1754    pub fn reply_timeout(&self) -> std::time::Duration {
1755        std::time::Duration::from_millis(self.reply_timeout_ms)
1756    }
1757
1758    /// `timeout`, raised to the face's reply timeout when it is shorter
1759    /// (core §8.1: at least the face's).
1760    #[must_use]
1761    pub fn at_least(&self, timeout: std::time::Duration) -> std::time::Duration {
1762        timeout.max(self.reply_timeout())
1763    }
1764
1765    /// Whether a reader across the face declares a silent subscription
1766    /// again (core §8.5): where the medium repairs no lost frame. With
1767    /// ARQ, a frame arrives or the transport closes, and a transport that
1768    /// opens again declares everything anew.
1769    #[must_use]
1770    pub fn redeclares(&self) -> bool {
1771        !self.arq
1772    }
1773
1774    /// The configuration a session across the face runs (v2 §2.16, §2.18):
1775    /// each `[transport]` key at zenoh's key, in zenoh's units, as the far
1776    /// end's block writes it: a client of the near router is the gateway
1777    /// client's session.
1778    #[must_use]
1779    pub fn session_keys(&self) -> Vec<(TransportKey, Value)> {
1780        TransportKey::ALL
1781            .into_iter()
1782            .map(|k| (k, self.transport.value(k)))
1783            .collect()
1784    }
1785
1786    /// The silence after which a subscription with `horizon` is declared
1787    /// again: [`SILENT_HORIZONS`] of it (core §8.5).
1788    #[must_use]
1789    pub fn silence(horizon: std::time::Duration) -> std::time::Duration {
1790        horizon.saturating_mul(SILENT_HORIZONS)
1791    }
1792}
1793
1794/// Why [`FacePolicy::far_side`] gave no far side.
1795#[derive(Debug, Clone, PartialEq, Eq)]
1796pub enum FarSideRefusal {
1797    /// A `link.v1` policy: no reply timeout, no ARQ, no transport.
1798    NotV2,
1799    /// The policy has no face of that name; its faces, in order.
1800    NoFace { face: String, faces: Vec<String> },
1801}
1802
1803impl fmt::Display for FarSideRefusal {
1804    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1805        match self {
1806            Self::NotV2 => f.write_str(
1807                "a link.v1 policy states no reply timeout and no transport: a far side reads a \
1808                 link.v2 policy (link.v2 §2.20)",
1809            ),
1810            Self::NoFace { face, faces } => write!(
1811                f,
1812                "the policy has no face {face:?}; its faces are {}",
1813                faces.join(", ")
1814            ),
1815        }
1816    }
1817}
1818
1819/// The most repair subscriptions one subscription declares (core §8.5).
1820pub const REPAIRS: u32 = 3;
1821
1822/// The key expression of `selector`'s `n`-th repair subscription (core
1823/// §8.5), `n` from 1: `selector` with `$*` placed in the last chunk of its
1824/// literal prefix, the chunks before its first wildcard, at that chunk's
1825/// end for the first repair and one character further left for each
1826/// later one (`…/frames/fast$*`, then `…/frames/fas$*t`; an event's
1827/// `…/face/device_fault$*/*`; a template's `…/port$*/*/rx`).
1828///
1829/// `$*` matches no character too, so a repair matches every key `selector`
1830/// does, and it is canonical. No reader's own subscription declares it, so
1831/// its router declares it toward the far side, and with a key expression
1832/// of its own: its literal prefix ends a chunk earlier than `selector`'s.
1833/// The selector may carry a namespace in front of `zk2`.
1834///
1835/// `None` for `n` past [`REPAIRS`] or past the chunk's first character,
1836/// and for a selector that is no zk2 data selector or whose literal prefix
1837/// ends before its resource (a template whose first chunk is a parameter):
1838/// `$*` on its kind or its interface would leave the far side's grants
1839/// (core §11.1).
1840#[must_use]
1841pub fn repair_key(selector: &str, n: u32) -> Option<String> {
1842    if n == 0 || n > REPAIRS {
1843        return None;
1844    }
1845    let chunks: Vec<&str> = selector.split('/').collect();
1846    // The kind's chunk: `zk2`, the address, an interface, a kind token,
1847    // and a resource after it.
1848    let kind = (0..chunks.len()).find(|&z| {
1849        chunks[z] == crate::grammar::GRAMMAR
1850            && z + 5 < chunks.len()
1851            && chunks[z + 3].parse::<crate::grammar::IfaceId>().is_ok()
1852            && chunks[z + 4].parse::<KindToken>().is_ok()
1853    })? + 4;
1854    // The literal prefix's last chunk: a plain chunk is ASCII and holds no
1855    // wildcard (core §1.2).
1856    let literal = chunks
1857        .iter()
1858        .position(|c| c.contains(['*', '$']))
1859        .unwrap_or(chunks.len());
1860    let at = literal.checked_sub(1).filter(|&i| i > kind)?;
1861    if !is_plain_chunk(chunks[at]) {
1862        return None;
1863    }
1864    let split = chunks[at].len().checked_sub(usize::try_from(n - 1).ok()?)?;
1865    let chunk = format!("{}$*{}", &chunks[at][..split], &chunks[at][split..]);
1866    let mut out = chunks.clone();
1867    out[at] = &chunk;
1868    let repair = out.join("/");
1869    keyexpr::new(repair.as_str()).ok()?;
1870    Some(repair)
1871}
1872
1873/// The horizon of a subscription to `r`, a resource of `c`, that a reader
1874/// across a face declares again after silence (core §8.5): its
1875/// `freshness.ttl_s` above 0, where its owner puts at least once a
1876/// horizon. A state of a contract that uses `freshness.v2` has none of its
1877/// own: its owner re-puts nothing, and its heartbeat's subscription speaks
1878/// for it ([`redeclare_heartbeat_horizon`]). `None`: never silent this way.
1879#[must_use]
1880pub fn redeclare_horizon(c: &Contract, r: &Resource) -> Option<std::time::Duration> {
1881    if matches!(r.kind, Kind::State) && freshness::uses_v2(c) {
1882        return None;
1883    }
1884    freshness::horizon_of(r).ttl()
1885}
1886
1887/// The horizon of a subscription to `c`'s heartbeat (core §8.5,
1888/// `freshness.v2` §2.4): the shortest of the collections it covers, where
1889/// `c` uses `freshness.v2` and has one.
1890#[must_use]
1891pub fn redeclare_heartbeat_horizon(c: &Contract) -> Option<std::time::Duration> {
1892    if !freshness::uses_v2(c) {
1893        return None;
1894    }
1895    crate::heartbeat::Layout::of(c).horizon()
1896}
1897
1898/// The horizon of a subscription to an owner heartbeat key of `class`,
1899/// as a reader holding `c` alone can tell it (core §8.5, `freshness.v2`
1900/// §2.4): the shortest of `c`'s collections of that class, where `c` uses
1901/// `freshness.v2` and has one. A reader holding several revisions of one
1902/// provider takes the shortest among them
1903/// ([`freshness::Views::class_horizon`]).
1904#[must_use]
1905pub fn redeclare_owner_heartbeat_horizon(
1906    c: &Contract,
1907    class: crate::heartbeat::Class,
1908) -> Option<std::time::Duration> {
1909    if !freshness::uses_v2(c) {
1910        return None;
1911    }
1912    crate::heartbeat::Layout::of(c).class_horizon(class)
1913}
1914
1915/// What [`parse`] read: the policy when no error refused it, and every
1916/// finding, sorted.
1917#[derive(Debug, Clone)]
1918pub struct Parsed {
1919    pub policy: Option<FacePolicy>,
1920    pub findings: Vec<Finding>,
1921}
1922
1923const TOP_KEYS_V1: &[&str] = &["system", "services", "face"];
1924const TOP_KEYS_V2: &[&str] = &[
1925    "profile",
1926    "system",
1927    "services",
1928    "binding",
1929    "catalog",
1930    "transport",
1931    "face",
1932];
1933
1934/// Reads a face policy, and lints it (§2.1): a `link.v1` one when it has
1935/// no `profile`, a link.v2 one when its `profile` is `"link.v2"` (v2 §2.1).
1936#[must_use]
1937pub fn parse(text: &str) -> Parsed {
1938    let refuse = |f: Finding| Parsed {
1939        policy: None,
1940        findings: vec![f],
1941    };
1942    let table: toml::Table = match toml::from_str(text) {
1943        Ok(t) => t,
1944        Err(_) => return refuse(Finding::new(Code::Toml, None, "")),
1945    };
1946    if crate::toml10::first_beyond_toml10(text).is_some() {
1947        return refuse(Finding::new(Code::Toml, None, ""));
1948    }
1949    let mut out = Vec::new();
1950    // Any other `profile` is a wrong value, and the rest is read as a
1951    // link.v2 policy, whose key it is (v2 §2.1).
1952    let profile = match table.get("profile") {
1953        None => Profile::V1,
1954        Some(toml::Value::String(s)) if s == PROFILE_V2 => Profile::V2,
1955        Some(_) => {
1956            out.push(Finding::new(Code::BadValue, None, "profile"));
1957            Profile::V2
1958        }
1959    };
1960    let top = match profile {
1961        Profile::V1 => TOP_KEYS_V1,
1962        Profile::V2 => TOP_KEYS_V2,
1963    };
1964    for k in table.keys() {
1965        if !top.contains(&k.as_str()) {
1966            out.push(Finding::new(Code::UnknownField, None, k.clone()));
1967        }
1968    }
1969    let system = match table.get("system") {
1970        None => {
1971            out.push(Finding::new(Code::MissingField, None, "system"));
1972            None
1973        }
1974        Some(toml::Value::String(s)) if is_plain_chunk(s) => Some(s.clone()),
1975        Some(_) => {
1976            out.push(Finding::new(Code::BadValue, None, "system"));
1977            None
1978        }
1979    };
1980    let services = match table.get("services") {
1981        None => {
1982            out.push(Finding::new(Code::MissingField, None, "services"));
1983            None
1984        }
1985        Some(v) => match plain_list(v) {
1986            Some(l) => Some(l),
1987            None => {
1988                out.push(Finding::new(Code::BadValue, None, "services"));
1989                None
1990            }
1991        },
1992    };
1993    // link.v2's top level: the binding, the catalog, the transport.
1994    let (binding, catalog, transport) = match profile {
1995        Profile::V1 => (
1996            Some((
1997                Binding::Zenoh1_10_1,
1998                Binding::Zenoh1_10_1.as_str().to_owned(),
1999            )),
2000            None,
2001            None,
2002        ),
2003        Profile::V2 => {
2004            let binding = match table.get("binding") {
2005                None => {
2006                    out.push(Finding::new(Code::MissingField, None, "binding"));
2007                    None
2008                }
2009                Some(toml::Value::String(s)) => {
2010                    let b = Binding::parse(s);
2011                    if b.is_none() {
2012                        out.push(Finding::new(Code::BadValue, None, "binding"));
2013                    }
2014                    b.map(|b| (b, s.clone()))
2015                }
2016                Some(_) => {
2017                    out.push(Finding::new(Code::BadValue, None, "binding"));
2018                    None
2019                }
2020            };
2021            let catalog = match table.get("catalog") {
2022                None => None,
2023                Some(toml::Value::String(s)) if is_catalog_id(s) => Some(s.clone()),
2024                Some(_) => {
2025                    out.push(Finding::new(Code::BadValue, None, "catalog"));
2026                    None
2027                }
2028            };
2029            let transport = match table.get("transport") {
2030                None => {
2031                    out.push(Finding::new(Code::TransportMissing, None, "transport"));
2032                    None
2033                }
2034                Some(toml::Value::Table(t)) => Some(parse_transport(t, &mut out)),
2035                Some(_) => {
2036                    out.push(Finding::new(Code::BadValue, None, "transport"));
2037                    None
2038                }
2039            };
2040            (binding, catalog, transport)
2041        }
2042    };
2043    let ctx = FaceCtx {
2044        profile,
2045        protocols: binding.as_ref().map(|(b, _)| b.protocols()),
2046        transport: transport.as_ref(),
2047    };
2048    let mut faces = BTreeMap::new();
2049    match table.get("face") {
2050        None => out.push(Finding::new(Code::MissingField, None, "face")),
2051        Some(toml::Value::Table(t)) if t.is_empty() => {
2052            out.push(Finding::new(Code::BadValue, None, "face"));
2053        }
2054        Some(toml::Value::Table(t)) => {
2055            for (name, v) in t {
2056                if !is_plain_chunk(name) {
2057                    out.push(Finding::new(Code::BadValue, Some(name), ""));
2058                }
2059                match v {
2060                    toml::Value::Table(ft) => {
2061                        if let Some(face) = parse_face(name, ft, &ctx, &mut out) {
2062                            faces.insert(name.clone(), face);
2063                        }
2064                    }
2065                    _ => out.push(Finding::new(Code::BadValue, Some(name), "")),
2066                }
2067            }
2068        }
2069        Some(_) => out.push(Finding::new(Code::BadValue, None, "face")),
2070    }
2071    if let Some(protocols) = ctx.protocols {
2072        shared_protocols(&table, protocols, &mut out);
2073    }
2074    shared_far(&table, &mut out);
2075    if profile == Profile::V2 {
2076        device_listed(&table, system.as_deref(), services.as_deref(), &mut out);
2077    }
2078    sort_findings(&mut out);
2079    let policy = if out.iter().any(Finding::is_error) {
2080        None
2081    } else {
2082        Some(FacePolicy {
2083            profile,
2084            system: system.unwrap_or_default(),
2085            services: services.unwrap_or_default(),
2086            faces,
2087            binding_name: binding.as_ref().map_or_else(
2088                || Binding::default().as_str().to_owned(),
2089                |(_, n)| n.clone(),
2090            ),
2091            binding: binding.map(|(b, _)| b).unwrap_or_default(),
2092            transport: transport.as_ref().and_then(TransportDraft::complete),
2093            catalog,
2094        })
2095    };
2096    Parsed {
2097        policy,
2098        findings: out,
2099    }
2100}
2101
2102/// A catalog's id: 8 lowercase hex digits (v2 §2.1).
2103fn is_catalog_id(s: &str) -> bool {
2104    s.len() == 8 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
2105}
2106
2107/// `[transport]` as read, each key valid or not (`None`), an optional one
2108/// the policy omits at its default (v2 §2.1).
2109#[derive(Debug, Clone, Default)]
2110struct TransportDraft {
2111    lease_ms: Option<u64>,
2112    keep_alive: Option<u64>,
2113    wait_before_close_ms: Option<u64>,
2114    sequence: Option<Sequence>,
2115    batch_bytes: Option<u64>,
2116    open_timeout_ms: Option<u64>,
2117    accept_timeout_ms: Option<u64>,
2118    interests_timeout_ms: Option<u64>,
2119}
2120
2121impl TransportDraft {
2122    fn complete(&self) -> Option<Transport> {
2123        Some(Transport {
2124            lease_ms: self.lease_ms?,
2125            keep_alive: self.keep_alive?,
2126            wait_before_close_ms: self.wait_before_close_ms?,
2127            sequence: self.sequence?,
2128            batch_bytes: self.batch_bytes?,
2129            open_timeout_ms: self.open_timeout_ms?,
2130            accept_timeout_ms: self.accept_timeout_ms?,
2131            interests_timeout_ms: self.interests_timeout_ms?,
2132        })
2133    }
2134}
2135
2136/// Reads `[transport]` (v2 §2.1), and checks `wait_under_lease` (v2 §2.16)
2137/// when both keys it reads are valid.
2138fn parse_transport(t: &toml::Table, out: &mut Vec<Finding>) -> TransportDraft {
2139    let keys: Vec<&str> = TransportKey::ALL.iter().map(|k| k.key()).collect();
2140    for k in t.keys() {
2141        if !keys.contains(&k.as_str()) {
2142            out.push(Finding::new(
2143                Code::UnknownField,
2144                None,
2145                format!("transport.{k}"),
2146            ));
2147        }
2148    }
2149    let mut int = |key: TransportKey, hi: u64, default: Option<u64>| match t.get(key.key()) {
2150        None => {
2151            if default.is_none() {
2152                out.push(Finding::new(Code::MissingField, None, key.at()));
2153            }
2154            default
2155        }
2156        Some(v) => {
2157            let n = int_in(v, 1, hi);
2158            if n.is_none() {
2159                out.push(Finding::new(Code::BadValue, None, key.at()));
2160            }
2161            n
2162        }
2163    };
2164    let mut d = TransportDraft {
2165        lease_ms: int(TransportKey::Lease, MAX_U32, None),
2166        keep_alive: int(TransportKey::KeepAlive, MAX_KEEP_ALIVE, None),
2167        wait_before_close_ms: int(TransportKey::WaitBeforeClose, MAX_U32, None),
2168        sequence: None,
2169        batch_bytes: int(TransportKey::BatchBytes, MAX_BATCH, Some(MAX_BATCH)),
2170        open_timeout_ms: int(TransportKey::OpenTimeout, MAX_U32, Some(DEFAULT_TIMEOUT_MS)),
2171        accept_timeout_ms: int(
2172            TransportKey::AcceptTimeout,
2173            MAX_U32,
2174            Some(DEFAULT_TIMEOUT_MS),
2175        ),
2176        interests_timeout_ms: int(
2177            TransportKey::InterestsTimeout,
2178            MAX_U32,
2179            Some(DEFAULT_TIMEOUT_MS),
2180        ),
2181    };
2182    d.sequence = match t.get(TransportKey::Sequence.key()) {
2183        None => {
2184            out.push(Finding::new(
2185                Code::MissingField,
2186                None,
2187                TransportKey::Sequence.at(),
2188            ));
2189            None
2190        }
2191        Some(toml::Value::String(s)) => {
2192            let q = Sequence::parse(s);
2193            if q.is_none() {
2194                out.push(Finding::new(
2195                    Code::BadValue,
2196                    None,
2197                    TransportKey::Sequence.at(),
2198                ));
2199            }
2200            q
2201        }
2202        Some(_) => {
2203            out.push(Finding::new(
2204                Code::BadValue,
2205                None,
2206                TransportKey::Sequence.at(),
2207            ));
2208            None
2209        }
2210    };
2211    if let (Some(lease), Some(wbc)) = (d.lease_ms, d.wait_before_close_ms)
2212        && wbc < lease
2213    {
2214        out.push(Finding::new(
2215            Code::WaitUnderLease,
2216            None,
2217            TransportKey::WaitBeforeClose.at(),
2218        ));
2219    }
2220    d
2221}
2222
2223/// An array of plain chunks, none repeated.
2224fn plain_list(v: &toml::Value) -> Option<Vec<String>> {
2225    let a = v.as_array()?;
2226    let mut seen = BTreeSet::new();
2227    let mut out = Vec::with_capacity(a.len());
2228    for x in a {
2229        let s = x.as_str().filter(|s| is_plain_chunk(s))?;
2230        if !seen.insert(s) {
2231            return None;
2232        }
2233        out.push(s.to_owned());
2234    }
2235    Some(out)
2236}
2237
2238/// An integer of `v` within `lo..=hi`.
2239fn int_in(v: &toml::Value, lo: u64, hi: u64) -> Option<u64> {
2240    let i = v.as_integer()?;
2241    u64::try_from(i).ok().filter(|n| (lo..=hi).contains(n))
2242}
2243
2244/// A link protocol list: non-empty strings, none repeated. `None` when it
2245/// is not one.
2246fn protocol_list(v: &toml::Value) -> Option<Vec<String>> {
2247    let a = v.as_array()?;
2248    if a.is_empty() {
2249        return None;
2250    }
2251    let mut seen = BTreeSet::new();
2252    let mut out = Vec::with_capacity(a.len());
2253    for x in a {
2254        let s = x.as_str()?;
2255        if !seen.insert(s) {
2256            return None;
2257        }
2258        out.push(s.to_owned());
2259    }
2260    Some(out)
2261}
2262
2263const FACE_KEYS: &[&str] = &[
2264    "far",
2265    "attach",
2266    "region",
2267    "select",
2268    "class",
2269    "expose",
2270    "interval_s",
2271    "max_outage_s",
2272    "batch_bytes",
2273    "link_bps",
2274    "lease_ms",
2275];
2276
2277/// A link.v2 face's keys (v2 §2.1): `link.v1`'s less `batch_bytes` and
2278/// `lease_ms`, which are `moved_field`, and the medium's three.
2279const FACE_KEYS_V2: &[&str] = &[
2280    "far",
2281    "attach",
2282    "region",
2283    "select",
2284    "class",
2285    "expose",
2286    "interval_s",
2287    "max_outage_s",
2288    "link_bps",
2289    "loss_ppm",
2290    "arq",
2291    "reply_timeout_ms",
2292    "horizon_s",
2293    "frames",
2294    "events",
2295    "devices",
2296    "opens",
2297];
2298
2299/// What a face's `attach` names, when it is valid (§2.1; v2 §2.1).
2300#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2301enum AttachKind {
2302    Client,
2303    South,
2304    Device,
2305}
2306
2307/// A device face's `devices` (v2 §2.1): a non-empty array of addresses
2308/// `<system>/<service>`, each two plain chunks (core §1.2), none repeated.
2309/// `None` when it is not one: `devices` is one value.
2310fn device_list(v: &toml::Value) -> Option<Vec<String>> {
2311    let a = v.as_array()?;
2312    if a.is_empty() {
2313        return None;
2314    }
2315    let mut seen = BTreeSet::new();
2316    for x in a {
2317        let s = x.as_str()?;
2318        let (system, service) = s.split_once('/')?;
2319        if !is_plain_chunk(system) || !is_plain_chunk(service) || !seen.insert(s) {
2320            return None;
2321        }
2322    }
2323    // Sorted by their bytes (v2 §2.3).
2324    Some(seen.into_iter().map(str::to_owned).collect())
2325}
2326
2327/// A face's `frames` (v2 §2.1): a table of entries, each keyed
2328/// `<iface>/<template>`, an interface id and a template with no parameter,
2329/// and valued `{every_s, keyframe_s}`. Each wrong entry is reported once,
2330/// `at` `frames.<entry>` or a key within it; `None` when any is wrong.
2331fn parse_frames(
2332    face: &str,
2333    v: &toml::Value,
2334    out: &mut Vec<Finding>,
2335) -> Option<BTreeMap<String, FrameCadence>> {
2336    let at = Some(face);
2337    let toml::Value::Table(t) = v else {
2338        out.push(Finding::new(Code::BadValue, at, "frames"));
2339        return None;
2340    };
2341    let mut ok = true;
2342    let mut frames = BTreeMap::new();
2343    for (k, v) in t {
2344        let entry = format!("frames.{k}");
2345        let mut bad = |out: &mut Vec<Finding>, code: Code, key: String| {
2346            out.push(Finding::new(code, at, key));
2347            ok = false;
2348        };
2349        let name = k.split_once('/').and_then(|(i, rest)| {
2350            let iface: crate::grammar::IfaceId = i.parse().ok()?;
2351            let template = Template::parse(rest).ok().filter(|t| !t.has_params())?;
2352            Some(format!("{iface}/stream/{}", template.as_str()))
2353        });
2354        if name.is_none() {
2355            bad(out, Code::BadValue, entry.clone());
2356        }
2357        let toml::Value::Table(e) = v else {
2358            if name.is_some() {
2359                bad(out, Code::BadValue, entry);
2360            }
2361            continue;
2362        };
2363        for key in e.keys() {
2364            if key != "every_s" && key != "keyframe_s" {
2365                bad(out, Code::UnknownField, format!("{entry}.{key}"));
2366            }
2367        }
2368        let every_s = match e.get("every_s") {
2369            None => {
2370                bad(out, Code::MissingField, format!("{entry}.every_s"));
2371                None
2372            }
2373            Some(v) => {
2374                let n = int_in(v, 1, MAX_U32);
2375                if n.is_none() {
2376                    bad(out, Code::BadValue, format!("{entry}.every_s"));
2377                }
2378                n
2379            }
2380        };
2381        let keyframe_s = match e.get("keyframe_s") {
2382            None => Some(None),
2383            Some(v) => {
2384                let n = int_in(v, 1, MAX_U32);
2385                if n.is_none() {
2386                    bad(out, Code::BadValue, format!("{entry}.keyframe_s"));
2387                }
2388                n.map(Some)
2389            }
2390        };
2391        if let (Some(name), Some(every_s), Some(keyframe_s)) = (name, every_s, keyframe_s) {
2392            frames.insert(
2393                name,
2394                FrameCadence {
2395                    every_s,
2396                    keyframe_s,
2397                },
2398            );
2399        }
2400    }
2401    ok.then_some(frames)
2402}
2403
2404/// A face's `events` (v2 §2.1, §2.7): an array of entries
2405/// `<iface>/<template>`, an interface id and a template, none repeated,
2406/// possibly empty; each kept as the event resource's name (§0,
2407/// `<iface>/events/<template>`). `None` when it is not one: `events` is
2408/// one value, reported once.
2409fn parse_events(face: &str, v: &toml::Value, out: &mut Vec<Finding>) -> Option<BTreeSet<String>> {
2410    let read = || {
2411        let mut names = BTreeSet::new();
2412        for x in v.as_array()? {
2413            let (i, rest) = x.as_str()?.split_once('/')?;
2414            let iface: crate::grammar::IfaceId = i.parse().ok()?;
2415            let template = Template::parse(rest).ok()?;
2416            if !names.insert(format!("{iface}/events/{}", template.as_str())) {
2417                return None;
2418            }
2419        }
2420        Some(names)
2421    };
2422    let events = read();
2423    if events.is_none() {
2424        out.push(Finding::new(Code::BadValue, Some(face), "events"));
2425    }
2426    events
2427}
2428
2429/// What a face is read against: its profile, its binding's link protocols
2430/// (`None` when the binding is not one: the check is skipped), and a
2431/// link.v2 policy's `[transport]`.
2432struct FaceCtx<'a> {
2433    profile: Profile,
2434    protocols: Option<&'static [&'static str]>,
2435    transport: Option<&'a TransportDraft>,
2436}
2437
2438fn parse_face(
2439    name: &str,
2440    t: &toml::Table,
2441    ctx: &FaceCtx<'_>,
2442    out: &mut Vec<Finding>,
2443) -> Option<Face> {
2444    let at = Some(name);
2445    let v2 = ctx.profile == Profile::V2;
2446    let mut ok = true;
2447    let mut bad = |out: &mut Vec<Finding>, code: Code, key: &str| {
2448        out.push(Finding::new(code, at, key));
2449        ok = false;
2450    };
2451    for k in t.keys() {
2452        if v2 && (k == "batch_bytes" || k == "lease_ms") {
2453            bad(out, Code::MovedField, k);
2454        } else if !(if v2 { FACE_KEYS_V2 } else { FACE_KEYS }).contains(&k.as_str()) {
2455            bad(out, Code::UnknownField, k);
2456        }
2457    }
2458    let far = match t.get("far") {
2459        None => {
2460            bad(out, Code::MissingField, "far");
2461            None
2462        }
2463        Some(toml::Value::String(s)) if !s.is_empty() => Some(s.clone()),
2464        Some(_) => {
2465            bad(out, Code::BadValue, "far");
2466            None
2467        }
2468    };
2469    // `attach`, when it is valid: `device` only in a link.v2 policy, which
2470    // a link.v1 one knows nothing of (v2 §2.1).
2471    let attach = match t.get("attach") {
2472        None => {
2473            bad(out, Code::MissingField, "attach");
2474            None
2475        }
2476        Some(toml::Value::String(s)) if s == "client" => Some(AttachKind::Client),
2477        Some(toml::Value::String(s)) if s == "south-region" => Some(AttachKind::South),
2478        Some(toml::Value::String(s)) if v2 && s == "device" => Some(AttachKind::Device),
2479        Some(toml::Value::String(s)) if s == "router" => {
2480            bad(out, Code::RouterAttach, "attach");
2481            None
2482        }
2483        Some(_) => {
2484            bad(out, Code::BadValue, "attach");
2485            None
2486        }
2487    };
2488    let region = match t.get("region") {
2489        None => None,
2490        Some(toml::Value::String(s)) if !s.is_empty() && s.len() <= MAX_REGION => Some(s.clone()),
2491        Some(_) => {
2492            bad(out, Code::BadValue, "region");
2493            None
2494        }
2495    };
2496    match (attach, t.contains_key("region")) {
2497        (Some(AttachKind::South), false) => bad(out, Code::MissingField, "region"),
2498        (Some(AttachKind::Client | AttachKind::Device), true) => {
2499            bad(out, Code::BadValue, "region");
2500        }
2501        _ => {}
2502    }
2503    // `devices` (v2 §2.1): one value, required with `device` and refused
2504    // with any other `attach`, each checked against `attach` only when
2505    // `attach` is valid. A link.v1 face's is `unknown_field`, above.
2506    let devices = match t.get("devices") {
2507        Some(v) if v2 => {
2508            let l = device_list(v);
2509            if l.is_none() || matches!(attach, Some(AttachKind::Client | AttachKind::South)) {
2510                bad(out, Code::BadValue, "devices");
2511            }
2512            l
2513        }
2514        _ => None,
2515    };
2516    if attach == Some(AttachKind::Device) && !t.contains_key("devices") {
2517        bad(out, Code::MissingField, "devices");
2518    }
2519    // `opens` (v2 §2.1, §2.5): `"near"` only with `south-region`, checked
2520    // against `attach` only when `attach` is valid. A link.v1 face's is
2521    // `unknown_field`, above.
2522    let opens = match t.get("opens") {
2523        Some(v) if v2 => match v.as_str() {
2524            Some("far") => Some(Opens::Far),
2525            Some("near") if !matches!(attach, Some(AttachKind::Client | AttachKind::Device)) => {
2526                Some(Opens::Near)
2527            }
2528            _ => {
2529                bad(out, Code::BadValue, "opens");
2530                None
2531            }
2532        },
2533        _ => Some(Opens::Far),
2534    };
2535    let link_protocols = match t.get("select") {
2536        None => {
2537            bad(out, Code::MissingField, "select");
2538            None
2539        }
2540        Some(toml::Value::Table(s)) => {
2541            for k in s.keys() {
2542                if k == "interfaces" {
2543                    bad(out, Code::SelectInterfaces, "select.interfaces");
2544                } else if k != "link_protocols" {
2545                    bad(out, Code::UnknownField, &format!("select.{k}"));
2546                }
2547            }
2548            match s.get("link_protocols") {
2549                None => {
2550                    bad(out, Code::MissingField, "select.link_protocols");
2551                    None
2552                }
2553                Some(v) => match protocol_list(v) {
2554                    None => {
2555                        bad(out, Code::BadValue, "select.link_protocols");
2556                        None
2557                    }
2558                    // Against the binding's list, when the binding is one
2559                    // (v2 §2.4): each key is checked alone.
2560                    Some(l)
2561                        if ctx.protocols.is_some_and(|known| {
2562                            l.iter().any(|p| !known.contains(&p.as_str()))
2563                        }) =>
2564                    {
2565                        bad(out, Code::UnknownProtocol, "select.link_protocols");
2566                        None
2567                    }
2568                    Some(l) => Some(l),
2569                },
2570            }
2571        }
2572        Some(_) => {
2573            bad(out, Code::BadValue, "select");
2574            None
2575        }
2576    };
2577    match t.get("class") {
2578        None => bad(out, Code::MissingField, "class"),
2579        Some(toml::Value::String(s)) if s == "constrained" => {}
2580        Some(_) => bad(out, Code::BadValue, "class"),
2581    }
2582    let expose = match t.get("expose") {
2583        None => {
2584            bad(out, Code::MissingField, "expose");
2585            None
2586        }
2587        Some(toml::Value::String(s)) if s == "link" => Some(Expose::Link),
2588        Some(toml::Value::String(s)) if s == "none" => Some(Expose::None),
2589        Some(_) => {
2590            bad(out, Code::BadValue, "expose");
2591            None
2592        }
2593    };
2594    let interval_s = match t.get("interval_s") {
2595        None => None,
2596        Some(v) => match int_in(v, 1, MAX_U32) {
2597            Some(n) => Some(n),
2598            None => {
2599                bad(out, Code::BadValue, "interval_s");
2600                None
2601            }
2602        },
2603    };
2604    match (expose, t.contains_key("interval_s")) {
2605        (Some(Expose::Link), false) => bad(out, Code::MissingField, "interval_s"),
2606        (Some(Expose::None), true) => bad(out, Code::BadValue, "interval_s"),
2607        _ => {}
2608    }
2609    let mut int = |key: &str, lo: u64, hi: u64, required: bool| match t.get(key) {
2610        None => {
2611            if required {
2612                bad(out, Code::MissingField, key);
2613            }
2614            None
2615        }
2616        Some(v) => {
2617            let n = int_in(v, lo, hi);
2618            if n.is_none() {
2619                bad(out, Code::BadValue, key);
2620            }
2621            n
2622        }
2623    };
2624    let max_outage_s = int("max_outage_s", 1, MAX_U32, true);
2625    let link_bps = int("link_bps", 1, MAX_U32, true);
2626    if v2 {
2627        let loss_ppm = int("loss_ppm", 0, MAX_LOSS_PPM, true);
2628        let reply_timeout_ms = int("reply_timeout_ms", 1, MAX_U32, true);
2629        let horizon_s = int("horizon_s", 1, MAX_U32, false);
2630        let arq = match t.get("arq") {
2631            None => {
2632                bad(out, Code::MissingField, "arq");
2633                None
2634            }
2635            Some(toml::Value::Boolean(b)) => Some(*b),
2636            Some(_) => {
2637                bad(out, Code::BadValue, "arq");
2638                None
2639            }
2640        };
2641        let frames = match t.get("frames") {
2642            None => Some(None),
2643            Some(v) => {
2644                let f = parse_frames(name, v, out);
2645                if f.is_none() {
2646                    ok = false;
2647                }
2648                f.map(Some)
2649            }
2650        };
2651        let events = match t.get("events") {
2652            None => Some(None),
2653            Some(v) => {
2654                let e = parse_events(name, v, out);
2655                if e.is_none() {
2656                    ok = false;
2657                }
2658                e.map(Some)
2659            }
2660        };
2661        // Like `interval_s`, a face that exposes none lets nothing cross,
2662        // so it lists no frame and no event, and affords no horizon (v2
2663        // §2.1).
2664        if expose == Some(Expose::None) {
2665            for key in ["frames", "events", "horizon_s"] {
2666                if t.contains_key(key) {
2667                    out.push(Finding::new(Code::BadValue, at, key));
2668                    ok = false;
2669                }
2670            }
2671        }
2672        face_lints_v2(
2673            name,
2674            ctx.transport,
2675            link_bps,
2676            loss_ppm,
2677            reply_timeout_ms,
2678            arq,
2679            out,
2680        );
2681        if !ok {
2682            return None;
2683        }
2684        // The face is built only with its transport's batch and lease. When
2685        // either is missing, the policy is refused anyway, by the error that
2686        // `[transport]` itself pushed (`transport_missing`, or `bad_value` or
2687        // `missing_field` at its key, in `parse` and `parse_transport`), so
2688        // no policy is made of this face (`a_bad_transport_refuses_a_good_
2689        // face` holds it).
2690        let tr = ctx.transport?;
2691        return Some(Face {
2692            far: far?,
2693            attach: match attach? {
2694                AttachKind::Client => Attach::Client,
2695                AttachKind::South => Attach::SouthRegion { region: region? },
2696                AttachKind::Device => Attach::Device { devices: devices? },
2697            },
2698            link_protocols: link_protocols?,
2699            expose: expose?,
2700            interval_s,
2701            max_outage_s: max_outage_s?,
2702            batch_bytes: tr.batch_bytes?,
2703            link_bps: link_bps?,
2704            lease_ms: tr.lease_ms?,
2705            loss_ppm,
2706            arq,
2707            reply_timeout_ms,
2708            frames: frames?,
2709            events: events?,
2710            horizon_s,
2711            opens: opens?,
2712        });
2713    }
2714    let batch_bytes = int("batch_bytes", 1, MAX_BATCH, true);
2715    let lease_ms = int("lease_ms", 1, MAX_U32, false);
2716    // `batch_over_lease` needs these three keys alone, so it is checked
2717    // whatever else the face holds (§2.1: each key is checked alone).
2718    let lease = if t.contains_key("lease_ms") {
2719        lease_ms
2720    } else {
2721        Some(DEFAULT_LEASE_MS)
2722    };
2723    if let (Some(b), Some(bps), Some(l)) = (batch_bytes, link_bps, lease)
2724        && !within_lease(b, bps, l)
2725    {
2726        out.push(Finding::new(Code::BatchOverLease, at, "batch_bytes"));
2727    }
2728    if !ok {
2729        return None;
2730    }
2731    Some(Face {
2732        far: far?,
2733        attach: match attach? {
2734            AttachKind::Client => Attach::Client,
2735            AttachKind::South => Attach::SouthRegion { region: region? },
2736            // A link.v1 policy has no device face: `attach = "device"` is
2737            // its `bad_value`, above.
2738            AttachKind::Device => return None,
2739        },
2740        link_protocols: link_protocols?,
2741        expose: expose?,
2742        interval_s,
2743        max_outage_s: max_outage_s?,
2744        batch_bytes: batch_bytes?,
2745        link_bps: link_bps?,
2746        lease_ms: if t.contains_key("lease_ms") {
2747            lease_ms?
2748        } else {
2749            DEFAULT_LEASE_MS
2750        },
2751        loss_ppm: None,
2752        arq: None,
2753        reply_timeout_ms: None,
2754        frames: None,
2755        events: None,
2756        horizon_s: None,
2757        opens: Opens::Far,
2758    })
2759}
2760
2761/// A link.v2 face's checks that read `[transport]` (v2 §2.1, §2.10,
2762/// §2.16), each made when the keys it reads are valid, whatever else the
2763/// policy holds.
2764fn face_lints_v2(
2765    name: &str,
2766    tr: Option<&TransportDraft>,
2767    link_bps: Option<u64>,
2768    loss_ppm: Option<u64>,
2769    reply_timeout_ms: Option<u64>,
2770    arq: Option<bool>,
2771    out: &mut Vec<Finding>,
2772) {
2773    let at = Some(name);
2774    let tr = tr.cloned().unwrap_or_default();
2775    let mut warn = |code: Code, key: String| out.push(Finding::new(code, at, key));
2776    if let (Some(b), Some(bps), Some(l)) = (tr.batch_bytes, link_bps, tr.lease_ms)
2777        && !within_lease(b, bps, l)
2778    {
2779        warn(Code::BatchOverLease, TransportKey::BatchBytes.at());
2780    }
2781    if let (Some(l), Some(k), Some(p)) = (tr.lease_ms, tr.keep_alive, loss_ppm)
2782        && flaps(l, k, p)
2783    {
2784        warn(Code::KeepAliveFlaps, TransportKey::KeepAlive.at());
2785    }
2786    if let (Some(q), Some(b), Some(l), Some(bps)) =
2787        (tr.sequence, tr.batch_bytes, tr.lease_ms, link_bps)
2788        && window_filled(q, b, l, bps)
2789    {
2790        warn(Code::SequenceWindow, TransportKey::Sequence.at());
2791    }
2792    for (key, timeout) in [
2793        (TransportKey::OpenTimeout, tr.open_timeout_ms),
2794        (TransportKey::AcceptTimeout, tr.accept_timeout_ms),
2795    ] {
2796        if let (Some(t), Some(bps)) = (timeout, link_bps)
2797            && under_handshake(t, bps)
2798        {
2799            warn(Code::OpenUnderHandshake, key.at());
2800        }
2801    }
2802    if let (Some(r), Some(bps), Some(b)) = (reply_timeout_ms, link_bps, tr.batch_bytes)
2803        && reply_short(r, bps, b)
2804    {
2805        warn(Code::ReplyTimeoutShort, "reply_timeout_ms".to_owned());
2806    }
2807    if arq == Some(false) {
2808        warn(Code::NoArq, "arq".to_owned());
2809    }
2810}
2811
2812/// `shared_protocol` (§2.14), over every face whose protocol list is one
2813/// and names only link protocols of the binding's list: one naming another
2814/// is `unknown_protocol`, a wrong value, and checks that need it are
2815/// skipped (§2.1).
2816fn shared_protocols(table: &toml::Table, known: &[&str], out: &mut Vec<Finding>) {
2817    let Some(toml::Value::Table(faces)) = table.get("face") else {
2818        return;
2819    };
2820    let lists: Vec<(&String, Vec<String>)> = faces
2821        .iter()
2822        .filter_map(|(name, v)| {
2823            let l = protocol_list(v.get("select")?.get("link_protocols")?)?;
2824            l.iter()
2825                .all(|p| known.contains(&p.as_str()))
2826                .then_some((name, l))
2827        })
2828        .collect();
2829    for (i, (name, l)) in lists.iter().enumerate() {
2830        let shared = lists
2831            .iter()
2832            .enumerate()
2833            .any(|(j, (_, m))| i != j && l.iter().any(|p| m.contains(p)));
2834        if shared {
2835            out.push(Finding::new(
2836                Code::SharedProtocol,
2837                Some(name),
2838                "select.link_protocols",
2839            ));
2840        }
2841    }
2842}
2843
2844/// `far_of_two_faces` (§2.1, §2.4, 0.7, F-125), over every face whose `far`
2845/// is one, whatever else the policy holds: one warning per far principal
2846/// two or more faces name, with no face, `at` its name. Its policy carries
2847/// every one of their plans' denies, and no zenoh rule is limited to a link
2848/// protocol, so each of its faces carries them all.
2849fn shared_far(table: &toml::Table, out: &mut Vec<Finding>) {
2850    let Some(toml::Value::Table(faces)) = table.get("face") else {
2851        return;
2852    };
2853    let mut named: BTreeMap<&str, usize> = BTreeMap::new();
2854    for v in faces.values() {
2855        if let Some(toml::Value::String(far)) = v.get("far")
2856            && !far.is_empty()
2857        {
2858            *named.entry(far.as_str()).or_default() += 1;
2859        }
2860    }
2861    for (far, n) in named {
2862        if n > 1 {
2863            out.push(Finding::new(Code::FarOfTwoFaces, None, far));
2864        }
2865    }
2866}
2867
2868/// `device_listed` (v2 §2.1, §2.5), over every device face whose
2869/// `devices` is one, whatever else the policy holds: a device listed among
2870/// `services`, as `<system>/<service>`, or on another face. Each face
2871/// listing it has the finding, at `devices`.
2872fn device_listed(
2873    table: &toml::Table,
2874    system: Option<&str>,
2875    services: Option<&[String]>,
2876    out: &mut Vec<Finding>,
2877) {
2878    let Some(toml::Value::Table(faces)) = table.get("face") else {
2879        return;
2880    };
2881    let lists: Vec<(&String, Vec<String>)> = faces
2882        .iter()
2883        .filter(|(_, v)| v.get("attach").and_then(toml::Value::as_str) == Some("device"))
2884        .filter_map(|(name, v)| Some((name, device_list(v.get("devices")?)?)))
2885        .collect();
2886    let listed: BTreeSet<String> = match (system, services) {
2887        (Some(sys), Some(services)) => services.iter().map(|s| format!("{sys}/{s}")).collect(),
2888        _ => BTreeSet::new(),
2889    };
2890    for (i, (name, l)) in lists.iter().enumerate() {
2891        let elsewhere = l.iter().any(|d| {
2892            listed.contains(d)
2893                || lists
2894                    .iter()
2895                    .enumerate()
2896                    .any(|(j, (_, m))| i != j && m.contains(d))
2897        });
2898        if elsewhere {
2899            out.push(Finding::new(Code::DeviceListed, Some(name), "devices"));
2900        }
2901    }
2902}
2903
2904// ── A router's transport (v2 §2.19) ───────────────────────────────────────
2905
2906/// A transport value read as an integer: any u64, or a negative i64; `None`
2907/// for a value of another type.
2908fn integer(v: &Value) -> Option<i128> {
2909    v.as_u64()
2910        .map(i128::from)
2911        .or_else(|| v.as_i64().map(i128::from))
2912}
2913
2914/// Whether two transport values say the same (v2 §2.19): integers by
2915/// value, anything else as JSON.
2916#[must_use]
2917pub fn same_value(a: &Value, b: &Value) -> bool {
2918    match (a.as_u64(), b.as_u64()) {
2919        (Some(x), Some(y)) => x == y,
2920        _ => a == b,
2921    }
2922}
2923
2924/// Checks a router's configuration against a link.v2 policy's transport,
2925/// and the far end's against it (v2 §2.19): `router` and `peer` are the
2926/// keys each configuration states, a key it omits read at the binding's
2927/// default, and a `null` as zenoh reads one
2928/// ([`StatedTransport::null_left_out`]).
2929/// - `transport_differs`, each key whose router value is not the policy's;
2930/// - `wait_under_lease`, the router's `wait_before_close` below its lease,
2931///   whatever the policy says;
2932/// - `peer_differs`, the far end's lease or `keep_alive` not the router's;
2933/// - `face_timestamping`, the router stamping the puts it routes, read at
2934///   its mode ([`StatedTransport::stamps`]).
2935///
2936/// A `link.v1` policy states no transport: nothing to report.
2937#[must_use]
2938pub fn check_transport(
2939    policy: &FacePolicy,
2940    router: &StatedTransport,
2941    peer: Option<&StatedTransport>,
2942) -> Vec<Finding> {
2943    let mut out = Vec::new();
2944    let Some(planned) = &policy.transport else {
2945        return out;
2946    };
2947    let defaults = policy.binding.defaults();
2948    for key in TransportKey::ALL {
2949        if !same_value(&planned.value(key), &router.runs(key, &defaults)) {
2950            out.push(Finding::new(Code::TransportDiffers, None, key.at()));
2951        }
2952    }
2953    // Both read as integers, a u64's whole range among them; a negative
2954    // `wait_before_close`, which zenoh's i64 admits, is below any lease. A
2955    // value of another type (a string, a fraction) is no setting zenoh runs:
2956    // `transport_differs` has reported it above, since what the policy
2957    // plans is always an integer there, and this check has nothing to read.
2958    let lease_us = integer(&router.runs(TransportKey::Lease, &defaults)).map(|ms| ms * 1_000);
2959    let wbc_us = integer(&router.runs(TransportKey::WaitBeforeClose, &defaults));
2960    if let (Some(lease), Some(wbc)) = (lease_us, wbc_us)
2961        && wbc < lease
2962    {
2963        out.push(Finding::new(
2964            Code::WaitUnderLease,
2965            None,
2966            TransportKey::WaitBeforeClose.at(),
2967        ));
2968    }
2969    if let Some(peer) = peer {
2970        for key in [TransportKey::Lease, TransportKey::KeepAlive] {
2971            if !same_value(&router.runs(key, &defaults), &peer.runs(key, &defaults)) {
2972                out.push(Finding::new(Code::PeerDiffers, None, key.at()));
2973            }
2974        }
2975    }
2976    if router.stamps() {
2977        out.push(Finding::new(Code::FaceTimestamping, None, "timestamping"));
2978    }
2979    sort_findings(&mut out);
2980    out
2981}
2982
2983/// The id of the deployment catalog the far side holds (v2 §2.19): the
2984/// catalog read as core §8.6 reads one, and its id §8.6's, as 8 lowercase
2985/// hex digits.
2986///
2987/// # Errors
2988/// The first refusal of §8.6's reading: such a file is no catalog, and
2989/// holds no id to compare.
2990pub fn catalog_id(text: &str) -> Result<String, crate::catalog::Refusal> {
2991    crate::catalog::Catalog::parse(text).map(|c| c.id().hex())
2992}
2993
2994/// `catalog_mismatch` (v2 §2.19): the id of the catalog the far side holds,
2995/// `held`, is not the policy's, or the policy names none.
2996#[must_use]
2997pub fn check_catalog(policy: &FacePolicy, held: &str) -> Vec<Finding> {
2998    if policy.catalog.as_deref() == Some(held) {
2999        Vec::new()
3000    } else {
3001        vec![Finding::new(Code::CatalogMismatch, None, "catalog")]
3002    }
3003}
3004
3005// ── The deployment ───────────────────────────────────────────────────────
3006
3007/// One resource as the plan reads it: its template, its kind token, its
3008/// resolved annotations, whether it declares `history` (core §2.5), and,
3009/// for a frame resource (core §7.7), what the plan weighs of its frames;
3010/// and what link.v2 reads of it (v2 §2.16, §2.17): whether its type is
3011/// packed, whether its congestion is `block`, its longest put, and whether
3012/// its contract lists `link.v2`.
3013#[derive(Debug, Clone)]
3014pub struct Res {
3015    pub template: Template,
3016    pub token: KindToken,
3017    pub annotations: BTreeMap<String, Value>,
3018    pub history: bool,
3019    pub frame: Option<FrameFacts>,
3020    /// Its type is packed (core §7.6); a frame resource's always is. Read
3021    /// across revisions, packed only where every one types it packed (v2
3022    /// §2.3).
3023    pub packed: bool,
3024    /// Its congestion is `block` (core §2.4); across revisions, where any
3025    /// one declares it so.
3026    pub block: bool,
3027    /// Its priority is `data` (core §2.4); across revisions, where every
3028    /// one declares it so. Another priority adds a QoS extension to the
3029    /// push and the frame (link.v1 §2.8).
3030    pub priority_data: bool,
3031    /// It is express (core §2.4); across revisions, where any one is.
3032    pub express: bool,
3033    /// Its longest put's payload, in bytes: a packed record's longest
3034    /// (every optional field present) after an [`ENVELOPE_BYTES`] envelope,
3035    /// or a frame resource's largest frame. `None` for any other type.
3036    /// Across revisions, the longest of those that declare it `block`, or
3037    /// of every one where none does.
3038    pub longest_bytes: Option<u64>,
3039    /// The revision that declares it lists `link.v2` (v2 §2.17).
3040    pub link_v2: bool,
3041    /// The parameter its template declares as its epoch (core §4.3), whose
3042    /// members hold member tokens: on a device face, `epoch_on_device` (v2
3043    /// §2.5). Across revisions, any one's.
3044    pub epoch: Option<String>,
3045    /// A state whose deletes only a tombstone proves (v2 §2.11, 0.9; core
3046    /// S3): a per-key resource (core §4.2), or a template whose first chunk
3047    /// is a parameter, which has no snapshot key. [`tombstone_only`] reads
3048    /// it; across revisions, where any one is.
3049    pub tombstone_only: bool,
3050    /// A templated resource's cardinality (core §2.2), which an owner
3051    /// heartbeat's longest put reads of a collection (v2 §2.16): `None`
3052    /// for a template with no parameter, and for a templated one that
3053    /// states none, read there as no ceiling. Across revisions, the
3054    /// largest any one states.
3055    pub cardinality: Option<u64>,
3056}
3057
3058impl Res {
3059    /// A resource of `token` at `template`, with resolved `annotations`, and
3060    /// nothing else stated: no history, no frame, a type that is not packed,
3061    /// `drop` at priority `data` and not express, no cardinality, in a
3062    /// revision that does not list `link.v2` and uses no profile
3063    /// ([`tombstone_only`]).
3064    #[must_use]
3065    pub fn new(template: Template, token: KindToken, annotations: BTreeMap<String, Value>) -> Self {
3066        Res {
3067            history: false,
3068            frame: None,
3069            packed: false,
3070            block: false,
3071            priority_data: true,
3072            express: false,
3073            longest_bytes: None,
3074            link_v2: false,
3075            epoch: None,
3076            tombstone_only: tombstone_only(token, &template, &annotations, |_| false),
3077            cardinality: None,
3078            template,
3079            token,
3080            annotations,
3081        }
3082    }
3083
3084    /// Its shape, as [`crossing_v2`] reads it.
3085    #[must_use]
3086    pub fn shape(&self) -> Shape {
3087        Shape::of(
3088            self.token,
3089            self.template.has_params(),
3090            self.frame.is_some(),
3091            &self.annotations,
3092        )
3093    }
3094}
3095
3096/// What the plan reads of a frame resource (§2.8): never downsampled, it
3097/// crosses at its own cadence.
3098#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3099pub struct FrameFacts {
3100    /// Its interval (core §7.7): its span, else its `timing.period_ms`,
3101    /// else unstated.
3102    pub interval_ms: Option<u64>,
3103    /// The payload of the largest frame its owner writes, in bytes
3104    /// ([`crate::frame::Layout::largest_payload_bytes`]); `None` when its
3105    /// record type's layout does not read.
3106    pub largest_bytes: Option<u64>,
3107    /// Its `keyframe_every` (core §7.7): a full record at least once every
3108    /// this many records. Across revisions, the least (v2 §2.7).
3109    pub keyframe_every: u32,
3110}
3111
3112impl Res {
3113    /// What its QoS adds to its batch (link.v1 §2.8).
3114    #[must_use]
3115    pub fn qos(&self) -> PutQos {
3116        PutQos {
3117            block: self.block,
3118            priority_data: self.priority_data,
3119            express: self.express,
3120        }
3121    }
3122
3123    /// `r` of contract `c`, as the plan reads it.
3124    #[must_use]
3125    pub fn of(c: &Contract, r: &Resource) -> Self {
3126        let data = match &r.body {
3127            crate::contract::Body::Data(d) => Some(d),
3128            crate::contract::Body::Operation(_) => None,
3129        };
3130        let frame = data.and_then(|d| d.frame.as_ref()).map(|p| FrameFacts {
3131            interval_ms: p.interval_ms(&r.annotations),
3132            largest_bytes: crate::frame::Layout::of_resource(c, r)
3133                .ok()
3134                .flatten()
3135                .map(|l| l.largest_payload_bytes()),
3136            keyframe_every: p.keyframe_every,
3137        });
3138        let packed = data.is_some_and(|d| d.type_.is_packed());
3139        let longest_bytes = match (&frame, data) {
3140            (Some(f), _) => f.largest_bytes,
3141            (None, Some(d)) if packed => c
3142                .packed_layout(&d.type_)
3143                .ok()
3144                .flatten()
3145                .map(|l| ENVELOPE_BYTES + l.max_bits().div_ceil(8)),
3146            _ => None,
3147        };
3148        Res {
3149            template: r.template.clone(),
3150            token: r.token,
3151            annotations: r.annotations.clone(),
3152            history: data.is_some_and(|d| d.history.is_some()),
3153            frame,
3154            packed,
3155            block: data.is_some_and(|d| d.congestion == crate::authoring::Congestion::Block),
3156            priority_data: data.is_none_or(|d| d.priority == crate::authoring::Priority::Data),
3157            express: data.is_some_and(|d| d.express),
3158            longest_bytes,
3159            link_v2: uses_v2(c),
3160            epoch: r.epoch.clone(),
3161            tombstone_only: tombstone_only(r.token, &r.template, &r.annotations, |p| {
3162                c.uses.iter().any(|u| u.to_string() == p)
3163            }),
3164            cardinality: r.cardinality.filter(|_| r.template.has_params()),
3165        }
3166    }
3167}
3168
3169/// Whether a resource of `token` at `template`, with resolved
3170/// `annotations`, in a revision whose `uses` lists the profiles `uses`
3171/// says, is a state whose deletes only a tombstone proves (v2 §2.11, 0.9):
3172///
3173/// - a per-key resource (core §4.2,
3174///   [`crate::collection::per_key_in`]): a state that declares
3175///   `freshness.ttl_s` above 0, of a revision that does not use
3176///   `freshness.v2`; one whose annotations hold `desired.target_param`,
3177///   of a revision that does not use `desired.v2` (0.23); a metric
3178///   resource of `telemetry.v1` or `telemetry.v2` (a key of its
3179///   vocabulary), of a revision that uses one; any state of a revision
3180///   that uses `redundancy.v1`;
3181/// - a template whose first chunk is a parameter, which has no snapshot
3182///   key (core §4.2). A `desired.v2` desired resource at such a template
3183///   keeps its floor so, as 0.23's "unless its template's first chunk is
3184///   a parameter" says (`v2/plan.json`'s case 50, beside case 49's no
3185///   floor).
3186///
3187/// Every other state is read by snapshot, whose complete answer omits a
3188/// member deleted beyond the window.
3189#[must_use]
3190pub fn tombstone_only(
3191    token: KindToken,
3192    template: &Template,
3193    annotations: &BTreeMap<String, Value>,
3194    uses: impl Fn(&str) -> bool,
3195) -> bool {
3196    is_state(token)
3197        && (crate::collection::per_key_in(token, annotations, uses)
3198            || crate::collection::snapshot_prefix(template).is_none())
3199}
3200
3201/// What the plan needs of the deployment (§2.3): the interfaces each listed
3202/// service implements, and the revisions given of each interface.
3203#[derive(Debug, Clone, Default)]
3204pub struct Deployment {
3205    /// A service's name → the interface ids it implements.
3206    pub implements: BTreeMap<String, Vec<String>>,
3207    /// An interface id → each revision given of it, as its resources. Two
3208    /// minors of one major are two revisions of one id: an annotation
3209    /// changed between them is a review (core §9.8), and two services of
3210    /// one deployment may run either (core §3.3). The plan reads them
3211    /// together, failing closed where they disagree (§2.3).
3212    pub interfaces: BTreeMap<String, Vec<Vec<Res>>>,
3213    /// The interface ids a revision given of which uses `freshness.v2`:
3214    /// their owners send a heartbeat covering them (`freshness.v2` §2.4),
3215    /// which crosses where a collection it covers does (§2.9).
3216    pub heartbeats: BTreeSet<String>,
3217    /// An interface id → the fingerprints of the revisions given of it as
3218    /// contracts, which link.v2's catalog check reads (v2 §2.18). A
3219    /// revision given as its resources alone has none.
3220    pub fingerprints: BTreeMap<String, BTreeSet<crate::canonical::Fingerprint>>,
3221    /// The catalog the far side decodes with (core §8.6), when the
3222    /// deployment gives it: a link.v2 plan then refuses a crossing revision
3223    /// it does not list (v2 §2.18).
3224    pub catalog: Option<crate::catalog::Catalog>,
3225    /// The interface ids a revision given of which uses either major of
3226    /// `redundancy` ([`crate::redundancy::is_governed`]): a device
3227    /// implementing one is `presence_required` (v2 §2.5, 0.29).
3228    pub governed: BTreeSet<String>,
3229    /// The principals the deployment binds by a usrpwd user name (core
3230    /// §11.1): a face the near router opens binds none of them, so a
3231    /// link.v2 plan refuses one whose far principal is (v2 §2.5).
3232    pub users: BTreeSet<String>,
3233    /// Whether the routers' `default_permission` is `allow` (core §11.2):
3234    /// a face the near router opens is then planned where its far principal
3235    /// is a user name, and warned of, since the face's subject, bound by its
3236    /// link protocols, carries the principal's denies whoever opened (v2
3237    /// §2.5). Under `deny`, the default, it is refused.
3238    pub default_allow: bool,
3239    /// The listed services, by name, whose owner heartbeats the deployment
3240    /// turns on (`freshness.v2` §2.4; §2.3, #1145). A `link.v1` plan warns
3241    /// of each that implements an interface whose heartbeat crosses a face
3242    /// (`owner_heartbeat_denied`, §2.9); a link.v2 plan reads none of it,
3243    /// its `link` owner heartbeat crossing where a heartbeat does.
3244    pub owner_heartbeats: BTreeSet<String>,
3245}
3246
3247impl Deployment {
3248    /// Adds a contract's resources as a revision of its interface id, its
3249    /// heartbeat when it uses `freshness.v2`, and its fingerprint.
3250    pub fn add_contract(&mut self, c: &Contract) {
3251        if freshness::uses_v2(c) {
3252            self.heartbeats.insert(c.iface.to_string());
3253        }
3254        if crate::redundancy::is_governed(c) {
3255            self.governed.insert(c.iface.to_string());
3256        }
3257        self.fingerprints
3258            .entry(c.iface.to_string())
3259            .or_default()
3260            .insert(crate::canonical::Fingerprint::of(c));
3261        self.add_revision(
3262            c.iface.to_string(),
3263            c.resources.iter().map(|r| Res::of(c, r)).collect(),
3264        );
3265    }
3266
3267    /// Adds one revision of `iface`, as its resources.
3268    pub fn add_revision(&mut self, iface: impl Into<String>, resources: Vec<Res>) {
3269        self.interfaces
3270            .entry(iface.into())
3271            .or_default()
3272            .push(resources);
3273    }
3274}
3275
3276/// An interface's resources as the plan reads them across its revisions
3277/// (§2.3): each resource any revision declares, paired by kind token and
3278/// template, first revision first. A resource several revisions declare is
3279/// exposed only where every one of them reads `link` (§2.2 fails closed),
3280/// and has a horizon only where every one gives it a horizon above 0, the
3281/// least of them (§2.12). What link.v2 weighs is judged revision by
3282/// revision (v2 §2.3, 0.6, F-469), and so never hangs on their order: a
3283/// resource is packed only where every revision types it packed, timed
3284/// where any declares a deadline, and its longest put, for
3285/// `block_over_batch`, the longest a revision that declares it `block`
3286/// writes. A frame's largest frame is the largest any revision writes
3287/// (§2.3). The set holds the indices of the resources the revisions
3288/// disagree on: one reads `link`, another does not.
3289fn merge(revisions: &[Vec<Res>]) -> (Vec<Res>, BTreeSet<usize>) {
3290    let mut out: Vec<Res> = Vec::new();
3291    let mut readings: Vec<Vec<&Res>> = Vec::new();
3292    for rev in revisions {
3293        for r in rev {
3294            match out
3295                .iter()
3296                .position(|x| x.token == r.token && x.template == r.template)
3297            {
3298                Some(i) => readings[i].push(r),
3299                None => {
3300                    out.push(r.clone());
3301                    readings.push(vec![r]);
3302                }
3303            }
3304        }
3305    }
3306    let mut disagree = BTreeSet::new();
3307    for (i, rs) in readings.iter().enumerate() {
3308        let links = rs
3309            .iter()
3310            .filter(|r| exposure(kind_of(r.token), &r.annotations) == Exposure::Link)
3311            .count();
3312        // A frame's `history` is warned of where any revision declares it
3313        // (§2.8); its `frame` table is one in every revision of a major,
3314        // since a change to it is breaking (core §9.8), but for
3315        // `keyframe_every`, a review, of which the least binds (v2 §2.7).
3316        out[i].history = rs.iter().any(|r| r.history);
3317        if out[i].epoch.is_none() {
3318            out[i].epoch = rs.iter().find_map(|r| r.epoch.clone());
3319        }
3320        if let Some(f) = &mut out[i].frame {
3321            f.keyframe_every = rs
3322                .iter()
3323                .filter_map(|r| r.frame.map(|f| f.keyframe_every))
3324                .min()
3325                .unwrap_or(f.keyframe_every);
3326            // Each revision's largest frame, with its own record type and
3327            // `keyframe_every`: the largest of them.
3328            f.largest_bytes = rs
3329                .iter()
3330                .filter_map(|r| r.frame.and_then(|f| f.largest_bytes))
3331                .max();
3332        }
3333        // Each revision judged alone (v2 §2.3): a raw type in one draws
3334        // `not_packed`, a deadline in one makes it timed, and a `block`
3335        // one's longest put draws `block_over_batch`. A packed type grows
3336        // by a minor (core §7.6), so the longest is any revision's where
3337        // none is `block`.
3338        out[i].packed = rs.iter().all(|r| r.packed);
3339        if !timed(&out[i].annotations)
3340            && let Some(d) = rs
3341                .iter()
3342                .find_map(|r| r.annotations.get(crate::timing::DEADLINE_MS))
3343        {
3344            out[i]
3345                .annotations
3346                .insert(crate::timing::DEADLINE_MS.to_owned(), d.clone());
3347        }
3348        let block = rs.iter().any(|r| r.block);
3349        out[i].block = block;
3350        // The widest QoS any revision puts with (link.v1 §2.8): an owner
3351        // of either minor may run.
3352        out[i].priority_data = rs.iter().all(|r| r.priority_data);
3353        out[i].express = rs.iter().any(|r| r.express);
3354        out[i].tombstone_only = rs.iter().any(|r| r.tombstone_only);
3355        // An owner heartbeat's longest put (v2 §2.16) is the longest any
3356        // revision writes: no ceiling where one states none.
3357        out[i].cardinality = if rs.iter().any(|r| r.cardinality.is_none()) {
3358            None
3359        } else {
3360            rs.iter().filter_map(|r| r.cardinality).max()
3361        };
3362        out[i].longest_bytes = rs
3363            .iter()
3364            .filter(|r| r.block || !block)
3365            .filter_map(|r| r.longest_bytes)
3366            .max();
3367        if links > 0 && links < rs.len() {
3368            disagree.insert(i);
3369            out[i]
3370                .annotations
3371                .insert(EXPOSURE.to_owned(), Value::String("host".to_owned()));
3372        }
3373        let ttls: Vec<Option<std::time::Duration>> = rs.iter().map(|r| horizon(r).ttl()).collect();
3374        if ttls.windows(2).any(|w| w[0] != w[1]) {
3375            match ttls.into_iter().collect::<Option<Vec<_>>>() {
3376                Some(all) => {
3377                    let least = all.into_iter().min().unwrap_or_default();
3378                    out[i]
3379                        .annotations
3380                        .insert(freshness::TTL_S.to_owned(), Value::from(least.as_secs()));
3381                }
3382                None => {
3383                    out[i].annotations.remove(freshness::TTL_S);
3384                }
3385            }
3386        }
3387    }
3388    (out, disagree)
3389}
3390
3391// ── The plan (§2.3–§2.12) ────────────────────────────────────────────────
3392
3393/// One deny (§2.3).
3394#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3395pub struct Deny {
3396    pub id: String,
3397    pub flows: Vec<&'static str>,
3398    pub messages: Vec<&'static str>,
3399    pub key_exprs: Vec<String>,
3400}
3401
3402/// One downsampling rule (§2.8).
3403#[derive(Debug, Clone, PartialEq, Serialize)]
3404pub struct Rule {
3405    pub key_expr: String,
3406    pub freq: f64,
3407}
3408
3409/// A face's downsampling block (§2.8).
3410#[derive(Debug, Clone, PartialEq, Serialize)]
3411pub struct Downsampling {
3412    pub id: String,
3413    pub link_protocols: Vec<String>,
3414    pub flows: Vec<&'static str>,
3415    pub messages: Vec<&'static str>,
3416    pub rules: Vec<Rule>,
3417}
3418
3419/// One `gateway.south` filter (§2.5).
3420#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3421pub struct Filter {
3422    #[serde(skip_serializing_if = "Vec::is_empty")]
3423    pub modes: Vec<String>,
3424    #[serde(skip_serializing_if = "Vec::is_empty")]
3425    pub region_names: Vec<String>,
3426}
3427
3428/// One south subregion (§2.5).
3429#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3430pub struct South {
3431    pub filters: Vec<Filter>,
3432}
3433
3434/// The near router's `gateway` block (§2.5).
3435#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3436pub struct Gateway {
3437    pub south: Vec<South>,
3438}
3439
3440/// The attachment, as the plan carries it (§2.5; v2 §2.3).
3441#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3442#[serde(tag = "shape")]
3443pub enum AttachPlan {
3444    #[serde(rename = "client")]
3445    Client,
3446    #[serde(rename = "south-region")]
3447    SouthRegion { region: String, gateway: Gateway },
3448    /// A device face's (v2 §2.3): its devices, sorted by their bytes.
3449    #[serde(rename = "device")]
3450    Device { devices: Vec<String> },
3451}
3452
3453/// A listed owner of state's tombstone window floor (§2.11): under a
3454/// link.v2 policy, an owner of state whose deletes only a tombstone proves
3455/// ([`Res::tombstone_only`], v2 §2.11).
3456#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3457pub struct Window {
3458    pub service: String,
3459    pub min_s: u64,
3460}
3461
3462/// A listed service's liveness evidence across the face (§2.12).
3463#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3464pub struct Liveness {
3465    pub service: String,
3466    pub evidence: Vec<String>,
3467}
3468
3469/// One face's plan (§2.3).
3470#[derive(Debug, Clone, PartialEq, Serialize)]
3471pub struct FacePlan {
3472    pub name: String,
3473    pub far: String,
3474    pub attach: AttachPlan,
3475    pub deny: Vec<Deny>,
3476    pub downsampling: Option<Downsampling>,
3477    pub windows: Vec<Window>,
3478    pub liveness: Vec<Liveness>,
3479    /// A link.v2 face's reply timeout, the deployment's word to every
3480    /// caller across it (v2 §2.18); absent for a `link.v1` face.
3481    #[serde(skip_serializing_if = "Option::is_none")]
3482    pub reply_timeout_ms: Option<u64>,
3483    /// A link.v2 face's listed frames that cross it, each at its cadence,
3484    /// sorted by name: the deployment's word to the far side (v2 §2.7,
3485    /// §2.18). Absent for a face with no `frames`.
3486    #[serde(skip_serializing_if = "Option::is_none")]
3487    pub frames: Option<Vec<ListedFrame>>,
3488    pub findings: Vec<Finding>,
3489    /// What crosses the face, by name (§0): each resource of a listed
3490    /// interface whose pushes cross, overlapped ones set aside, each
3491    /// crossing heartbeat as `freshness.v2/stream/heartbeat/<iface>`
3492    /// (§2.9), and, on a link.v2 face, the `link` class's owner heartbeat
3493    /// key as `freshness.v2/stream/heartbeats/link` where it crosses (v2
3494    /// §2.9). A tool's scope across the face is read from it (observer
3495    /// §7.5). No router block carries it, so it is never serialized.
3496    #[serde(skip)]
3497    pub crossing: BTreeSet<String>,
3498}
3499
3500impl FacePlan {
3501    /// Whether resource `token`/`template` of `iface` crosses the face.
3502    #[must_use]
3503    pub fn crosses(&self, iface: &str, token: KindToken, template: &Template) -> bool {
3504        self.crossing
3505            .contains(&format!("{iface}/{}/{}", token.as_str(), template.as_str()))
3506    }
3507
3508    /// Whether the heartbeat covering `iface` crosses the face (§2.9).
3509    #[must_use]
3510    pub fn heartbeat_crosses(&self, iface: &str) -> bool {
3511        self.crossing.contains(&heartbeat_name(iface))
3512    }
3513
3514    /// Whether the owner heartbeat key of `class` crosses the face: the
3515    /// `link` class's on a link.v2 face a listed interface's heartbeat
3516    /// crosses (v2 §2.9), the `host` class's never, and neither on a
3517    /// `link.v1` face (§2.9).
3518    #[must_use]
3519    pub fn owner_heartbeat_crosses(&self, class: crate::heartbeat::Class) -> bool {
3520        self.crossing.contains(&owner_heartbeat_name(class))
3521    }
3522}
3523
3524/// A heartbeat's name in a plan, `freshness.v2/stream/heartbeat/<iface>`.
3525fn heartbeat_name(iface: &str) -> String {
3526    format!("{}/stream/heartbeat/{iface}", freshness::PROFILE_V2)
3527}
3528
3529/// An owner heartbeat key's name in a plan,
3530/// `freshness.v2/stream/heartbeats/<class>` (v2 §2.9).
3531#[must_use]
3532pub fn owner_heartbeat_name(class: crate::heartbeat::Class) -> String {
3533    format!("{}/stream/heartbeats/{class}", freshness::PROFILE_V2)
3534}
3535
3536/// A listed frame that crosses, as the plan carries it (v2 §2.18).
3537#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3538pub struct ListedFrame {
3539    /// Its name (§0).
3540    pub resource: String,
3541    #[serde(flatten)]
3542    pub cadence: FrameCadence,
3543}
3544
3545/// What [`plan_face`] found that the policy's other faces need: the
3546/// resources crossing it, the exposed frames it leaves unlisted, and the
3547/// interfaces with something crossing it (v2 §2.7, §2.18).
3548#[derive(Debug, Default)]
3549struct FaceFacts {
3550    crossing: BTreeSet<String>,
3551    unlisted: BTreeSet<String>,
3552    ifaces: BTreeSet<String>,
3553}
3554
3555/// A resource's name in a plan, `<iface>/<token>/<template>` (§0).
3556fn res_name(iface: &str, r: &Res) -> String {
3557    format!("{iface}/{}/{}", r.token.as_str(), r.template.as_str())
3558}
3559
3560/// Derives each face's plan (§2.3), faces sorted by name; or the
3561/// deployment's errors, which refuse it.
3562pub fn plan(policy: &FacePolicy, deployment: &Deployment) -> Result<Vec<FacePlan>, Vec<Finding>> {
3563    let mut errors = Vec::new();
3564    let mut listed: BTreeSet<&str> = BTreeSet::new();
3565    // The listed services and the devices, each read alike (v2 §2.5): a
3566    // device is named in the deployment by its address, and a device the
3567    // deployment names none for is `service_unknown` there (v2 §2.3).
3568    let services = policy.owners();
3569    for s in &services {
3570        match deployment.implements.get(s.key) {
3571            None => errors.push(Finding::new(Code::ServiceUnknown, None, s.key)),
3572            Some(ifaces) => {
3573                for i in ifaces {
3574                    if deployment
3575                        .interfaces
3576                        .get(i)
3577                        .is_some_and(|revs| !revs.is_empty())
3578                    {
3579                        listed.insert(i);
3580                    } else {
3581                        errors.push(Finding::new(Code::ContractUnknown, None, i.clone()));
3582                    }
3583                    // An owner on a first hop implements neither (v2 §2.5,
3584                    // core §8.1).
3585                    if let Some(face) = s.device_face
3586                        && (i == ARCHIVE || deployment.governed.contains(i))
3587                    {
3588                        errors.push(Finding::new(Code::PresenceRequired, Some(face), i.clone()));
3589                    }
3590                }
3591            }
3592        }
3593    }
3594    // A face the near router opens binds no user name (v2 §2.5): refused
3595    // under `deny`, where the far principal's grants would bind nothing, and
3596    // warned of under `allow`, where its denies hold through the face's
3597    // subject and nobody across the face is authenticated.
3598    let mut unauthenticated: BTreeSet<&str> = BTreeSet::new();
3599    for (name, face) in &policy.faces {
3600        if face.opens == Opens::Near && deployment.users.contains(&face.far) {
3601            if deployment.default_allow {
3602                unauthenticated.insert(name.as_str());
3603            } else {
3604                errors.push(Finding::new(Code::NearOpensUser, Some(name), "opens"));
3605            }
3606        }
3607    }
3608    if !errors.is_empty() {
3609        sort_findings(&mut errors);
3610        return Err(errors);
3611    }
3612    // Each listed interface read once across its revisions (§2.3).
3613    let view: View = listed
3614        .iter()
3615        .map(|i| ((*i).to_owned(), merge(&deployment.interfaces[*i])))
3616        .collect();
3617    let v2 = policy.profile == Profile::V2;
3618    // link.v2's contract side, read per revision given (v2 §2.17).
3619    if v2 {
3620        for i in &listed {
3621            for r in deployment.interfaces[*i].iter().flatten() {
3622                let e = exposure(kind_of(r.token), &r.annotations);
3623                if packed_required(r.link_v2, r.token, &e, r.packed) {
3624                    errors.push(Finding::new(Code::PackedRequired, None, res_name(i, r)));
3625                }
3626            }
3627        }
3628    }
3629    let mut faces: Vec<(FacePlan, FaceFacts)> = policy
3630        .faces
3631        .iter()
3632        .map(|(name, face)| {
3633            plan_face(
3634                policy,
3635                deployment,
3636                &view,
3637                &services,
3638                &listed,
3639                name,
3640                face,
3641                &mut errors,
3642            )
3643        })
3644        .collect();
3645    for (p, _) in &mut faces {
3646        if unauthenticated.contains(p.name.as_str()) {
3647            p.findings.push(Finding::new(
3648                Code::NearOpensUnauthenticated,
3649                Some(&p.name),
3650                "opens",
3651            ));
3652            sort_findings(&mut p.findings);
3653        }
3654    }
3655    if v2 {
3656        // An exposed frame no face lets across (v2 §2.7).
3657        let crossing: BTreeSet<String> = faces
3658            .iter()
3659            .flat_map(|(_, f)| f.crossing.iter().cloned())
3660            .collect();
3661        for (p, f) in &mut faces {
3662            for n in f.unlisted.iter().filter(|n| !crossing.contains(*n)) {
3663                p.findings
3664                    .push(Finding::new(Code::FrameUnlisted, Some(&p.name), n.clone()));
3665            }
3666            sort_findings(&mut p.findings);
3667        }
3668        // Every crossing revision is one the far side can decode (v2 §2.18).
3669        if let Some(cat) = &deployment.catalog {
3670            let ifaces: BTreeSet<&String> = faces.iter().flat_map(|(_, f)| &f.ifaces).collect();
3671            for i in ifaces {
3672                let Ok(id) = i.parse::<crate::grammar::IfaceId>() else {
3673                    continue;
3674                };
3675                for fp in deployment.fingerprints.get(i).into_iter().flatten() {
3676                    if cat.index_of(&id, fp).is_none() {
3677                        errors.push(Finding::new(
3678                            Code::CatalogMissing,
3679                            None,
3680                            format!("{i}@{fp}"),
3681                        ));
3682                    }
3683                }
3684            }
3685        }
3686    }
3687    if !errors.is_empty() {
3688        sort_findings(&mut errors);
3689        return Err(errors);
3690    }
3691    Ok(faces.into_iter().map(|(p, _)| p).collect())
3692}
3693
3694/// Each listed interface's resources across its revisions, and the ones
3695/// they disagree on ([`merge`]).
3696type View = BTreeMap<String, (Vec<Res>, BTreeSet<usize>)>;
3697
3698#[allow(clippy::too_many_arguments)]
3699fn plan_face(
3700    policy: &FacePolicy,
3701    deployment: &Deployment,
3702    view: &View,
3703    services: &[Owner<'_>],
3704    listed: &BTreeSet<&str>,
3705    name: &str,
3706    face: &Face,
3707    errors: &mut Vec<Finding>,
3708) -> (FacePlan, FaceFacts) {
3709    let mut findings = Vec::new();
3710    let mut facts = FaceFacts::default();
3711    let v2 = policy.profile == Profile::V2;
3712    let resources_of = |iface: &str| -> &[Res] { &view[iface].0 };
3713    // A put of a payload in one batch, with its allowance (§2.8, #1136): at
3714    // the transport's sequence width, or zenoh's default, 32 bits, for a
3715    // link.v1 policy, which states none.
3716    let sequence = policy.transport.map_or(Sequence::Bit32, |t| t.sequence);
3717    let fits = |payload: u64, qos: PutQos| {
3718        fits_batch(
3719            payload,
3720            face.batch_bytes,
3721            qos,
3722            sequence,
3723            &face.link_protocols,
3724        )
3725    };
3726    // Whether each resource of each listed interface crosses (§2.7; v2
3727    // §2.7, §2.8).
3728    let crossing_of = |iface: &str, r: &Res| {
3729        let e = exposure(kind_of(r.token), &r.annotations);
3730        if v2 {
3731            let name = res_name(iface, r);
3732            let listed = if r.token == KindToken::Events {
3733                face.events.as_ref().map(|l| l.contains(&name))
3734            } else {
3735                face.frames.as_ref().map(|f| f.contains_key(&name))
3736            };
3737            crossing_v2(r.token, r.shape(), &e, face.expose, listed)
3738        } else {
3739            crossing(r.token, r.template.has_params(), &e, face.expose)
3740        }
3741    };
3742    // A listed frame's entry names a frame resource of a listed interface
3743    // (v2 §2.7).
3744    for entry in face.frames.iter().flat_map(BTreeMap::keys) {
3745        let known = listed.iter().any(|i| {
3746            resources_of(i)
3747                .iter()
3748                .any(|r| r.frame.is_some() && &res_name(i, r) == entry)
3749        });
3750        if !known {
3751            errors.push(Finding::new(Code::FrameUnknown, Some(name), entry.clone()));
3752        }
3753    }
3754    // A listed event's entry names an event resource of a listed
3755    // interface (v2 §2.7).
3756    for entry in face.events.iter().flatten() {
3757        let known = listed.iter().any(|i| {
3758            resources_of(i)
3759                .iter()
3760                .any(|r| r.token == KindToken::Events && &res_name(i, r) == entry)
3761        });
3762        if !known {
3763            errors.push(Finding::new(Code::EventUnknown, Some(name), entry.clone()));
3764        }
3765    }
3766    for iface in listed {
3767        let (resources, disagree) = &view[*iface];
3768        for (i, r) in resources.iter().enumerate() {
3769            match crossing_of(iface, r).reason {
3770                Reason::Templated => findings.push(Finding::new(
3771                    Code::TemplatedExposure,
3772                    Some(name),
3773                    res_name(iface, r),
3774                )),
3775                Reason::Timed => findings.push(Finding::new(
3776                    Code::TimedDownsampled,
3777                    Some(name),
3778                    res_name(iface, r),
3779                )),
3780                // An unlisted frame is warned of (v2 §2.7); an unlisted
3781                // event is not.
3782                Reason::Unlisted if r.frame.is_some() => {
3783                    facts.unlisted.insert(res_name(iface, r));
3784                }
3785                _ => {}
3786            }
3787            if face.expose == Expose::Link && disagree.contains(&i) {
3788                findings.push(Finding::new(
3789                    Code::ExposureDisagrees,
3790                    Some(name),
3791                    res_name(iface, r),
3792                ));
3793            }
3794        }
3795    }
3796
3797    // `zk` whole, or a device face's carve (v2 §2.6), then `adv` and
3798    // `admin`.
3799    let mut deny = if face.attach.is_device() {
3800        zk_carve()
3801    } else {
3802        vec![plane("zk", ZK_DENY)]
3803    };
3804    deny.extend([plane("adv", ADV_DENY), plane("admin", ADMIN_DENY)]);
3805    // Each template of a device's interface that declares `epoch`, on the
3806    // device's own face (v2 §2.5).
3807    for s in services.iter().filter(|s| s.device_face == Some(name)) {
3808        for iface in &deployment.implements[s.key] {
3809            for r in resources_of(iface).iter().filter(|r| r.epoch.is_some()) {
3810                findings.push(Finding::new(
3811                    Code::EpochOnDevice,
3812                    Some(name),
3813                    res_name(iface, r),
3814                ));
3815            }
3816        }
3817    }
3818    // The name (§0) of every overlapped resource.
3819    let mut overlapped: BTreeSet<String> = BTreeSet::new();
3820    // Each token's denies, computed with every stream last: a heartbeat
3821    // crosses where a collection it covers crosses, overlapped ones set
3822    // aside (§2.9), so the state tokens are carved first.
3823    let mut by_token: BTreeMap<usize, Vec<Deny>> = BTreeMap::new();
3824    let mut heartbeat_crosses: BTreeMap<String, bool> = BTreeMap::new();
3825    let order = [2usize, 3, 4, 0, 1];
3826    for t in order {
3827        let token = PUSH_TOKENS[t];
3828        if token == KindToken::Stream {
3829            heartbeat_crosses = heartbeats_of(deployment, listed, view, &|i: &str, r: &Res| {
3830                crossing_of(i, r).crosses() && !overlapped.contains(&res_name(i, r))
3831            });
3832        }
3833        // The listed interfaces' templates of the token, and, for
3834        // streams, each covered interface's heartbeat as a template of
3835        // `freshness.v2` of its own, in place of the profile's own
3836        // templated one (§2.9).
3837        // Each template with its own heartbeat's crossing, paired as one:
3838        // an interface id is a plain chunk, so every one parses, and one
3839        // that did not would drop out whole, never shift a pairing.
3840        let mut pseudo: Vec<(Template, bool)> = if token == KindToken::Stream {
3841            heartbeat_crosses
3842                .iter()
3843                .filter_map(|(i, crosses)| {
3844                    Template::parse(&format!("heartbeat/{i}"))
3845                        .ok()
3846                        .map(|t| (t, *crosses))
3847                })
3848                .collect()
3849        } else {
3850            Vec::new()
3851        };
3852        // The owner heartbeat keys with them (§2.9, v2 §2.9), whichever
3853        // revision of `freshness.v2`'s contract is given, and where none
3854        // is. A `link.v1` face lets neither class's cross, so the carve
3855        // holds the template `heartbeats/{class}`. A link.v2 face holds
3856        // the two keys: the `link` class's crosses exactly when a listed
3857        // interface's heartbeat does, the `host` class's never.
3858        if !pseudo.is_empty() {
3859            let link = heartbeat_crosses.values().any(|c| *c);
3860            let owner: Vec<(String, bool)> = if v2 {
3861                crate::heartbeat::Class::ALL
3862                    .into_iter()
3863                    .map(|c| {
3864                        (
3865                            format!("heartbeats/{c}"),
3866                            link && c == crate::heartbeat::Class::Link,
3867                        )
3868                    })
3869                    .collect()
3870            } else {
3871                vec![(crate::heartbeat::OWNER_RESOURCE.to_owned(), false)]
3872            };
3873            pseudo.extend(
3874                owner
3875                    .into_iter()
3876                    .filter_map(|(t, crosses)| Template::parse(&t).ok().map(|t| (t, crosses))),
3877            );
3878        }
3879        let mut groups: BTreeMap<String, Vec<Item<'_>>> = BTreeMap::new();
3880        for iface in listed {
3881            if !pseudo.is_empty() && *iface == freshness::PROFILE_V2 {
3882                continue;
3883            }
3884            groups.insert(
3885                (*iface).to_owned(),
3886                resources_of(iface)
3887                    .iter()
3888                    .filter(|r| r.token == token)
3889                    .map(|r| Item {
3890                        template: &r.template,
3891                        crosses: crossing_of(iface, r).crosses(),
3892                    })
3893                    .collect(),
3894            );
3895        }
3896        if !pseudo.is_empty() {
3897            groups.insert(
3898                freshness::PROFILE_V2.to_owned(),
3899                pseudo
3900                    .iter()
3901                    .map(|(template, crosses)| Item {
3902                        template,
3903                        crosses: *crosses,
3904                    })
3905                    .collect(),
3906            );
3907        }
3908        let any = groups.values().flatten().any(|i| i.crosses);
3909        if !any {
3910            by_token.insert(
3911                t,
3912                vec![push_deny(
3913                    token.as_str().to_owned(),
3914                    vec![format!("zk2/*/*/*/{}/**", token.as_str())],
3915                )],
3916            );
3917            continue;
3918        }
3919        let mut denies = Vec::new();
3920        for (iface, items) in &groups {
3921            let root = format!("zk2/*/*/{iface}/{}", token.as_str());
3922            let keys = if items.iter().any(|i| i.crosses) {
3923                let (keys, exact) = carve(&root, items);
3924                for c in items.iter().filter(|i| i.crosses) {
3925                    let hit = exact.iter().any(|&t| {
3926                        let t = items[t].template;
3927                        t.overlaps(c.template) && c.template.precedence(t) == Ordering::Greater
3928                    });
3929                    if hit {
3930                        let at = format!("{iface}/{}/{}", token.as_str(), c.template.as_str());
3931                        overlapped.insert(at.clone());
3932                        findings.push(Finding::new(Code::CarveOutOverlap, Some(name), at));
3933                    }
3934                }
3935                keys
3936            } else {
3937                vec![format!("{root}/**")]
3938            };
3939            if !keys.is_empty() {
3940                denies.push(push_deny(format!("{}:{iface}", token.as_str()), keys));
3941            }
3942        }
3943        by_token.insert(t, denies);
3944    }
3945    deny.extend(by_token.into_values().flatten());
3946
3947    // The resources that cross, overlapped ones set aside.
3948    let crosses = |iface: &str, r: &Res| {
3949        crossing_of(iface, r).crosses() && !overlapped.contains(&res_name(iface, r))
3950    };
3951
3952    // Downsampling (§2.8), the interval against the horizon (§2.12). A
3953    // device's stream is never downsampled on its own face, where its puts
3954    // arrive (v2 §2.8).
3955    let mut rules = Vec::new();
3956    if let Some(freq) = face.freq() {
3957        for s in services.iter().filter(|s| s.device_face != Some(name)) {
3958            for iface in &deployment.implements[s.key] {
3959                for r in resources_of(iface) {
3960                    // A frame is never downsampled (§2.8).
3961                    if is_stream(r.token) && r.frame.is_none() && crosses(iface, r) {
3962                        rules.push(Rule {
3963                            key_expr: format!(
3964                                "zk2/{}/{iface}/{}/{}",
3965                                s.address,
3966                                r.token.as_str(),
3967                                r.template.as_str()
3968                            ),
3969                            freq,
3970                        });
3971                    }
3972                }
3973            }
3974        }
3975        rules.sort_by(|a, b| a.key_expr.cmp(&b.key_expr));
3976        rules.dedup_by(|a, b| a.key_expr == b.key_expr);
3977        for iface in listed {
3978            for r in resources_of(iface) {
3979                if r.frame.is_some() {
3980                    continue;
3981                }
3982                if let (true, Some(ttl), Some(n)) = (
3983                    is_stream(r.token) && crosses(iface, r),
3984                    horizon(r).ttl(),
3985                    face.interval_s,
3986                ) && u128::from(n) * 2 > u128::from(ttl.as_secs())
3987                {
3988                    findings.push(Finding::new(
3989                        Code::IntervalOverHorizon,
3990                        Some(name),
3991                        res_name(iface, r),
3992                    ));
3993                }
3994            }
3995        }
3996    }
3997    // A crossing frame resource (§2.8, §2.12): its own cadence, against
3998    // the face's interval, its batch and its horizon, and its history. A
3999    // listed frame's cadence is its entry's `every_s` (v2 §2.8).
4000    let mut listed_frames = Vec::new();
4001    let mut cadences: Vec<u64> = Vec::new();
4002    for iface in listed {
4003        for r in resources_of(iface) {
4004            let Some(f) = r.frame.filter(|_| crosses(iface, r)) else {
4005                continue;
4006            };
4007            let at = || res_name(iface, r);
4008            let entry = face.frames.as_ref().and_then(|l| l.get(&at())).copied();
4009            let cadence_ms = entry.map_or(f.interval_ms, |e| Some(e.every_s * 1000));
4010            cadences.extend(cadence_ms);
4011            if let Some(e) = entry {
4012                listed_frames.push(ListedFrame {
4013                    resource: at(),
4014                    cadence: e,
4015                });
4016                // The owner may write full records more often than its contract says,
4017                // never less (v2 §2.7).
4018                if let Some(k) = e.keyframe_s
4019                    && u128::from(k) > u128::from(f.keyframe_every) * u128::from(e.every_s)
4020                {
4021                    errors.push(Finding::new(Code::KeyframeUnreachable, Some(name), at()));
4022                }
4023            }
4024            if let (Some(i), Some(n)) = (cadence_ms, face.interval_s)
4025                && u128::from(i) < u128::from(n) * 1000
4026            {
4027                findings.push(Finding::new(Code::FrameOverInterval, Some(name), at()));
4028            }
4029            // Its largest frame, with what zenoh writes beside it, in one
4030            // batch (§2.8, #1136).
4031            if f.largest_bytes.is_some_and(|b| !fits(b, r.qos())) {
4032                findings.push(Finding::new(Code::FrameOverBatch, Some(name), at()));
4033            }
4034            if r.history {
4035                findings.push(Finding::new(Code::HistoryOnFrame, Some(name), at()));
4036            }
4037            if let (Some(ttl), Some(i)) = (horizon(r).ttl(), cadence_ms)
4038                && u128::from(i) * 2 > ttl.as_millis()
4039            {
4040                findings.push(Finding::new(Code::IntervalOverHorizon, Some(name), at()));
4041            }
4042            if let (true, Some(ttl), Some(h)) = (v2, horizon(r).ttl(), face.horizon_s)
4043                && ttl.as_secs() < h
4044            {
4045                findings.push(Finding::new(Code::HorizonUnderFace, Some(name), at()));
4046            }
4047        }
4048    }
4049    // What crosses, by name: a tool's scope across the face (observer
4050    // §7.5).
4051    let mut crossing: BTreeSet<String> = listed
4052        .iter()
4053        .flat_map(|iface| {
4054            resources_of(iface)
4055                .iter()
4056                .filter(|r| crosses(iface, r))
4057                .map(|r| res_name(iface, r))
4058        })
4059        .collect();
4060    crossing.extend(
4061        heartbeat_crosses
4062            .iter()
4063            .filter(|(_, c)| **c)
4064            .map(|(i, _)| heartbeat_name(i)),
4065    );
4066    // The `link` class's owner heartbeat key crosses a link.v2 face exactly
4067    // when a listed interface's heartbeat does (v2 §2.9).
4068    let owner_link = v2 && heartbeat_crosses.values().any(|c| *c);
4069    let owner_at = || owner_heartbeat_name(crate::heartbeat::Class::Link);
4070    if owner_link {
4071        crossing.insert(owner_at());
4072    }
4073    // What else link.v2 weighs of each crossing resource (v2 §2.3, §2.16).
4074    if v2 {
4075        for iface in listed {
4076            for r in resources_of(iface).iter().filter(|r| crosses(iface, r)) {
4077                facts.crossing.insert(res_name(iface, r));
4078                facts.ifaces.insert((*iface).to_owned());
4079                if !r.packed {
4080                    findings.push(Finding::new(
4081                        Code::NotPacked,
4082                        Some(name),
4083                        res_name(iface, r),
4084                    ));
4085                }
4086                if r.block && r.longest_bytes.is_some_and(|b| !fits(b, r.qos())) {
4087                    findings.push(Finding::new(
4088                        Code::BlockOverBatch,
4089                        Some(name),
4090                        res_name(iface, r),
4091                    ));
4092                }
4093            }
4094        }
4095        // A crossing heartbeat: its horizon, the shortest of its
4096        // collections', and its period, half that (`freshness.v2` §2.4).
4097        for (iface, crosses) in &heartbeat_crosses {
4098            if !crosses {
4099                continue;
4100            }
4101            facts.ifaces.insert(iface.clone());
4102            let Some(ttl) = heartbeat_horizon(view, iface) else {
4103                continue;
4104            };
4105            cadences.push(ttl.as_secs() * 500);
4106            if face.horizon_s.is_some_and(|h| ttl.as_secs() < h) {
4107                findings.push(Finding::new(
4108                    Code::HorizonUnderFace,
4109                    Some(name),
4110                    heartbeat_name(iface),
4111                ));
4112            }
4113        }
4114        // The `link` owner heartbeat, where it crosses (v2 §2.9, §2.16):
4115        // one finding of each code for the face, whichever service draws
4116        // it, since every service's rides the one key.
4117        if owner_link {
4118            let (mut under, mut over) = (false, false);
4119            for s in services {
4120                let ifaces = &deployment.implements[s.key];
4121                // A heartbeat of each listed service that implements an
4122                // interface whose heartbeat crosses: its horizon, the
4123                // shortest of the service's `link` collections, and its
4124                // period, half that.
4125                if ifaces
4126                    .iter()
4127                    .any(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
4128                    && let Some(ttl) = owner_heartbeat_horizon(view, &heartbeat_crosses, ifaces)
4129                {
4130                    cadences.push(ttl.as_secs() * 500);
4131                    under |= face.horizon_s.is_some_and(|h| ttl.as_secs() < h);
4132                }
4133                // Its put is `drop`, and fragments the same: any listed
4134                // service's longest one against the batch.
4135                // At its key's QoS, `data` and `drop` (`freshness.v2`).
4136                over |=
4137                    owner_heartbeat_longest(view, &heartbeat_crosses, ifaces).is_some_and(|b| {
4138                        u64::try_from(b)
4139                            .ok()
4140                            .is_none_or(|b| !fits(b, PutQos::DATA_DROP))
4141                    });
4142            }
4143            if under {
4144                findings.push(Finding::new(Code::HorizonUnderFace, Some(name), owner_at()));
4145            }
4146            if over {
4147                findings.push(Finding::new(Code::BlockOverBatch, Some(name), owner_at()));
4148            }
4149        }
4150        // Data more often than the keep-alive interval spares the uplink
4151        // its keep-alives; at the interval itself each keep-alive races
4152        // the next batch, and goes first when that batch is late (v2
4153        // §2.16, #1108).
4154        if let (Some(t), Some(c)) = (&policy.transport, cadences.iter().min())
4155            && u128::from(*c) * u128::from(t.keep_alive) >= u128::from(t.lease_ms)
4156        {
4157            findings.push(Finding::new(
4158                Code::KeepAliveNotSuppressed,
4159                Some(name),
4160                TransportKey::KeepAlive.at(),
4161            ));
4162        }
4163    }
4164    listed_frames.sort_by(|a, b| a.resource.cmp(&b.resource));
4165    let downsampling = (!rules.is_empty()).then(|| Downsampling {
4166        id: name.to_owned(),
4167        link_protocols: face.link_protocols.clone(),
4168        flows: vec!["egress"],
4169        messages: vec!["put"],
4170        rules,
4171    });
4172
4173    // Windows (§2.11) and liveness (§2.12).
4174    let mut windows = Vec::new();
4175    let mut liveness = Vec::new();
4176    for s in services {
4177        let ifaces = &deployment.implements[s.key];
4178        let resources = || {
4179            ifaces
4180                .iter()
4181                .flat_map(|i| resources_of(i).iter().map(move |r| (i, r)))
4182        };
4183        // v2 §2.11 (0.9): a link.v2 policy floors only an owner of state
4184        // whose deletes only a tombstone proves; link.v1 every owner of
4185        // state.
4186        if resources().any(|(_, r)| is_state(r.token) && (!v2 || r.tombstone_only)) {
4187            windows.push(Window {
4188                service: s.address.clone(),
4189                min_s: face.max_outage_s,
4190            });
4191        }
4192        let mut evidence: Vec<String> = resources()
4193            .filter(|(i, r)| crosses(i, r) && horizon(r).ttl().is_some())
4194            .map(|(i, r)| res_name(i, r))
4195            .collect();
4196        // An owner that turns its owner heartbeats on behind a `link.v1`
4197        // face: none crosses, and an interface they cover sends no
4198        // heartbeat of its own, so its far readers may hear no confirmation
4199        // (§2.9, #1145). Once for the service: the plan cannot tell which
4200        // interfaces its catalog lets them cover.
4201        if !v2
4202            && deployment.owner_heartbeats.contains(s.key)
4203            && ifaces
4204                .iter()
4205                .any(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
4206        {
4207            findings.push(Finding::new(Code::OwnerHeartbeatDenied, Some(name), s.key));
4208        }
4209        // A crossing heartbeat is evidence too (§2.12): its horizon is the
4210        // shortest of the collections it covers (`freshness.v2` §2.4).
4211        evidence.extend(
4212            ifaces
4213                .iter()
4214                .filter(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
4215                .map(|i| heartbeat_name(i)),
4216        );
4217        // Whichever form the service sends (v2 §2.9): where the `link`
4218        // key crosses, it is evidence of each service that implements an
4219        // interface whose heartbeat crosses.
4220        if owner_link
4221            && ifaces
4222                .iter()
4223                .any(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
4224        {
4225            evidence.push(owner_at());
4226        }
4227        evidence.sort();
4228        evidence.dedup();
4229        liveness.push(Liveness {
4230            service: s.address.clone(),
4231            evidence,
4232        });
4233    }
4234
4235    sort_findings(&mut findings);
4236    let plan = FacePlan {
4237        name: name.to_owned(),
4238        far: face.far.clone(),
4239        attach: match &face.attach {
4240            Attach::Client => AttachPlan::Client,
4241            Attach::SouthRegion { region } => AttachPlan::SouthRegion {
4242                region: region.clone(),
4243                gateway: gateway(region),
4244            },
4245            Attach::Device { devices } => AttachPlan::Device {
4246                devices: devices.clone(),
4247            },
4248        },
4249        deny,
4250        downsampling,
4251        windows,
4252        liveness,
4253        reply_timeout_ms: face.reply_timeout_ms,
4254        frames: face.frames.as_ref().map(|_| listed_frames),
4255        findings,
4256        crossing,
4257    };
4258    (plan, facts)
4259}
4260
4261fn horizon(r: &Res) -> Horizon {
4262    freshness::horizon(kind_of(r.token), &r.annotations)
4263}
4264
4265/// A heartbeat's horizon: the shortest of the collections of `iface` it
4266/// covers (`freshness.v2` §2.9).
4267fn heartbeat_horizon(view: &View, iface: &str) -> Option<std::time::Duration> {
4268    view.get(iface)?
4269        .0
4270        .iter()
4271        .filter(|r| is_state(r.token))
4272        .filter_map(|r| horizon(r).ttl())
4273        .min()
4274}
4275
4276/// A resource the plan reads as a collection (core §7.5): a state with a
4277/// horizon above 0, the revisions read together (§2.3).
4278fn is_collection(r: &Res) -> bool {
4279    is_state(r.token) && horizon(r).ttl().is_some()
4280}
4281
4282/// Whether the plan reads a collection's class as `link` (`freshness.v2`
4283/// §2.4): its exposure, the revisions read together (§2.3), so one they
4284/// disagree on is `host`.
4285fn is_link(r: &Res) -> bool {
4286    exposure(kind_of(r.token), &r.annotations) == Exposure::Link
4287}
4288
4289/// The interfaces among `ifaces`, one service's, that a `link` owner
4290/// heartbeat of that service holds a group for (v2 §2.9, §2.16): each one
4291/// with a heartbeat (`heartbeats`, [`heartbeats_of`]'s) that has a `link`
4292/// collection, whether or not that collection crosses the face. An owner
4293/// covers an interface in place of its heartbeat (`freshness.v2` §2.4), so
4294/// one with no heartbeat has no group.
4295fn owner_heartbeat_groups<'a>(
4296    view: &'a View,
4297    heartbeats: &'a BTreeMap<String, bool>,
4298    ifaces: &'a [String],
4299) -> impl Iterator<Item = &'a [Res]> {
4300    let mut seen = BTreeSet::new();
4301    ifaces
4302        .iter()
4303        .filter(move |i| heartbeats.contains_key(i.as_str()) && seen.insert(i.as_str()))
4304        .filter_map(|i| view.get(i.as_str()))
4305        .map(|(resources, _)| resources.as_slice())
4306        .filter(|rs| rs.iter().any(|r| is_collection(r) && is_link(r)))
4307}
4308
4309/// A service's `link` owner heartbeat's horizon (v2 §2.9): the shortest
4310/// among the `link` collections of its listed interfaces.
4311fn owner_heartbeat_horizon(
4312    view: &View,
4313    heartbeats: &BTreeMap<String, bool>,
4314    ifaces: &[String],
4315) -> Option<std::time::Duration> {
4316    owner_heartbeat_groups(view, heartbeats, ifaces)
4317        .flatten()
4318        .filter(|r| is_collection(r) && is_link(r))
4319        .filter_map(|r| horizon(r).ttl())
4320        .min()
4321}
4322
4323/// A service's longest `link` owner heartbeat, a put's payload in bytes
4324/// (v2 §2.16): [`ENVELOPE_BYTES`] of envelope, then its body's bits
4325/// rounded up to whole bytes. `None` for a service with no group.
4326///
4327/// ```text
4328/// body      46 bits (the time, the count of groups), then each group
4329/// group     14 bits (index, tag) · size · a map bit per collection of the
4330///           interface · each `link` collection's longest section
4331/// section   one member: 33 bits; templated, of cardinality c:
4332///           33 + ⌈log₂(c + 1)⌉ + c, every member live, and the bitmap
4333/// size      core §7.5's integer over the bits after it: 8 bits below
4334///           128, 16 below 16,384, and so on
4335/// ```
4336fn owner_heartbeat_longest(
4337    view: &View,
4338    heartbeats: &BTreeMap<String, bool>,
4339    ifaces: &[String],
4340) -> Option<u128> {
4341    use crate::heartbeat::{GROUPS_BITS, INDEX_BITS, TIME_BITS};
4342    let mut body = u128::from(TIME_BITS + GROUPS_BITS);
4343    let mut groups = 0;
4344    for resources in owner_heartbeat_groups(view, heartbeats, ifaces) {
4345        let collections = || resources.iter().filter(|r| is_collection(r));
4346        let sections: u128 = collections().count() as u128
4347            + collections()
4348                .filter(|r| is_link(r))
4349                .map(|r| {
4350                    crate::heartbeat::longest_section_bits(
4351                        r.template
4352                            .has_params()
4353                            .then(|| r.cardinality.unwrap_or(u64::from(u32::MAX))),
4354                    )
4355                })
4356                .sum::<u128>();
4357        body += u128::from(INDEX_BITS + 4) + crate::heartbeat::size_bits(sections) + sections;
4358        groups += 1;
4359    }
4360    (groups > 0).then(|| u128::from(ENVELOPE_BYTES) + body.div_ceil(8))
4361}
4362
4363/// Each listed interface whose owners send a heartbeat covering it
4364/// (`freshness.v2` §2.4: a revision uses the profile, and it has a
4365/// collection, a state with a horizon above 0), and whether that heartbeat
4366/// crosses the face: where a collection it covers crosses (§2.9). Never
4367/// downsampled (§2.8): no rule is derived for it.
4368fn heartbeats_of(
4369    deployment: &Deployment,
4370    listed: &BTreeSet<&str>,
4371    view: &View,
4372    crosses: &dyn Fn(&str, &Res) -> bool,
4373) -> BTreeMap<String, bool> {
4374    let mut out = BTreeMap::new();
4375    for iface in listed {
4376        if !deployment.heartbeats.contains(*iface) {
4377            continue;
4378        }
4379        let collections: Vec<&Res> = view[*iface]
4380            .0
4381            .iter()
4382            .filter(|r| is_state(r.token) && horizon(r).ttl().is_some())
4383            .collect();
4384        if collections.is_empty() {
4385            continue;
4386        }
4387        out.insert(
4388            (*iface).to_owned(),
4389            collections.iter().any(|r| crosses(iface, r)),
4390        );
4391    }
4392    out
4393}
4394
4395fn plane(id: &str, key: &str) -> Deny {
4396    Deny {
4397        id: id.to_owned(),
4398        flows: FLOWS.to_vec(),
4399        messages: MESSAGES.to_vec(),
4400        key_exprs: vec![key.to_owned()],
4401    }
4402}
4403
4404/// The pairs of core §11.2's Own row, `(flow, message)`: what a far
4405/// principal's Own grant lets cross a device face on an instance key (v2
4406/// §2.6). Ingress `put`, `delete`, `declare_queryable`, `reply` and
4407/// `liveliness_token`; egress `query` and `declare_subscriber`.
4408pub const OWN_PAIRS: [(&str, &str); 7] = [
4409    ("ingress", "put"),
4410    ("ingress", "delete"),
4411    ("ingress", "declare_queryable"),
4412    ("ingress", "reply"),
4413    ("ingress", "liveliness_token"),
4414    ("egress", "query"),
4415    ("egress", "declare_subscriber"),
4416];
4417
4418/// A device face's `zk` keys (v2 §2.6): every `@zk` form of core §1.1 but
4419/// the instance subtree, denied on every pair.
4420pub const ZK_CARVED: [&str; 3] = [
4421    "zk2/*/*/@zk/alive/**",
4422    "zk2/*/*/@zk/member/**",
4423    "zk2/@zk/**",
4424];
4425
4426/// The instance subtree a device face lets cross on [`OWN_PAIRS`] alone
4427/// (v2 §2.6).
4428pub const ZK_INSTANCE: &str = "zk2/*/*/@zk/instance/**";
4429
4430/// The messages of `flow` outside core §11.2's Own row, in [`MESSAGES`]'
4431/// order.
4432fn outside_own(flow: &str) -> Vec<&'static str> {
4433    MESSAGES
4434        .iter()
4435        .copied()
4436        .filter(|m| !OWN_PAIRS.contains(&(flow, *m)))
4437        .collect()
4438}
4439
4440/// A device face's three denies in place of `zk` (v2 §2.6): `zk` on the
4441/// interface tokens, member tokens and contract keys, every pair; and the
4442/// instance subtree on the eleven pairs outside the Own row, one deny per
4443/// flow. So an instance key crosses on the Own row's seven pairs alone,
4444/// and whose instance keys is the far principal's grants' to decide.
4445#[must_use]
4446pub fn zk_carve() -> Vec<Deny> {
4447    let mut out = vec![Deny {
4448        id: "zk".to_owned(),
4449        flows: FLOWS.to_vec(),
4450        messages: MESSAGES.to_vec(),
4451        key_exprs: ZK_CARVED.iter().map(|k| (*k).to_owned()).collect(),
4452    }];
4453    for flow in FLOWS {
4454        out.push(Deny {
4455            id: format!("zk:instance:{flow}"),
4456            flows: vec![flow],
4457            messages: outside_own(flow),
4458            key_exprs: vec![ZK_INSTANCE.to_owned()],
4459        });
4460    }
4461    out
4462}
4463
4464fn push_deny(id: String, mut key_exprs: Vec<String>) -> Deny {
4465    key_exprs.sort();
4466    key_exprs.dedup();
4467    Deny {
4468        id,
4469        flows: FLOWS.to_vec(),
4470        messages: PUSH_MESSAGES.to_vec(),
4471        key_exprs,
4472    }
4473}
4474
4475/// The near router's `gateway` block for a far router in `region` (§2.5):
4476/// its own peers and clients south first, then the region.
4477#[must_use]
4478pub fn gateway(region: &str) -> Gateway {
4479    Gateway {
4480        south: vec![
4481            South {
4482                filters: vec![Filter {
4483                    modes: vec!["peer".to_owned(), "client".to_owned()],
4484                    region_names: Vec::new(),
4485                }],
4486            },
4487            South {
4488                filters: vec![Filter {
4489                    modes: Vec::new(),
4490                    region_names: vec![region.to_owned()],
4491                }],
4492            },
4493        ],
4494    }
4495}
4496
4497// ── The carve-out (§2.7) ─────────────────────────────────────────────────
4498
4499struct Item<'a> {
4500    template: &'a Template,
4501    crosses: bool,
4502}
4503
4504/// A segment's place in a pattern, and its group.
4505#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
4506enum Seg {
4507    Lit(String),
4508    Param,
4509    Rest,
4510}
4511
4512impl Seg {
4513    fn of(s: &Segment) -> Self {
4514        match s {
4515            Segment::Literal(l) => Seg::Lit(l.clone()),
4516            Segment::Param(_) => Seg::Param,
4517            Segment::Rest(_) => Seg::Rest,
4518        }
4519    }
4520
4521    fn kind(&self) -> u8 {
4522        match self {
4523            Seg::Lit(_) => 0,
4524            Seg::Param => 1,
4525            Seg::Rest => 2,
4526        }
4527    }
4528
4529    /// A segment's pattern (§0): `{p}` is `*`, `{p...}` is `*/**`.
4530    fn pattern(&self) -> &str {
4531        match self {
4532            Seg::Lit(l) => l,
4533            Seg::Param => "*",
4534            Seg::Rest => "*/**",
4535        }
4536    }
4537}
4538
4539/// `root`, the prefix's pattern, and `suffix`, with a `**` written once
4540/// before a `/**` that follows it.
4541fn key(root: &str, prefix: &[Seg], suffix: &str) -> String {
4542    let mut k = root.to_owned();
4543    for s in prefix {
4544        k.push('/');
4545        k.push_str(s.pattern());
4546    }
4547    k.push_str(suffix);
4548    while k.contains("/**/**") {
4549        k = k.replace("/**/**", "/**");
4550    }
4551    k
4552}
4553
4554/// The carve-out of one interface's templates of one token (§2.7): the
4555/// denies, and the indices of the templates denied by their own pattern in
4556/// step 3.3.
4557fn carve(root: &str, items: &[Item<'_>]) -> (Vec<String>, Vec<usize>) {
4558    let mut keys = Vec::new();
4559    let mut exact = Vec::new();
4560    let all: Vec<usize> = (0..items.len()).collect();
4561    carve_at(root, items, &[], &all, &mut keys, &mut exact);
4562    keys.sort();
4563    keys.dedup();
4564    (keys, exact)
4565}
4566
4567fn carve_at(
4568    root: &str,
4569    items: &[Item<'_>],
4570    prefix: &[Seg],
4571    here: &[usize],
4572    keys: &mut Vec<String>,
4573    exact: &mut Vec<usize>,
4574) {
4575    let d = prefix.len();
4576    let crosses = |i: &usize| items[*i].crosses;
4577    // 1. Nothing crosses: the subtree.
4578    if !here.iter().any(crosses) {
4579        keys.push(key(root, prefix, "/**"));
4580        return;
4581    }
4582    // 2. Everything crosses.
4583    if here.iter().all(crosses) {
4584        return;
4585    }
4586    let segs = |i: usize| items[i].template.segments();
4587    let (equal, longer): (Vec<usize>, Vec<usize>) = here.iter().partition(|&&i| segs(i).len() == d);
4588    // 3.1 The template equal to the prefix.
4589    if equal.iter().any(|i| !crosses(i)) {
4590        keys.push(key(root, prefix, ""));
4591    }
4592    // 3.2 Nothing longer crosses.
4593    if !longer.iter().any(crosses) {
4594        keys.push(key(root, prefix, "/*/**"));
4595        return;
4596    }
4597    // 3.3 More than one kind of next segment: template by template.
4598    let kinds: BTreeSet<u8> = longer
4599        .iter()
4600        .map(|&i| Seg::of(&segs(i)[d]).kind())
4601        .collect();
4602    if kinds.len() > 1 {
4603        for &i in &longer {
4604            if !items[i].crosses {
4605                let pattern: Vec<Seg> = segs(i).iter().map(Seg::of).collect();
4606                keys.push(key(root, &pattern, ""));
4607                exact.push(i);
4608            }
4609        }
4610        return;
4611    }
4612    // 3.4 Group by the next segment.
4613    let mut groups: BTreeMap<Seg, Vec<usize>> = BTreeMap::new();
4614    for &i in &longer {
4615        groups.entry(Seg::of(&segs(i)[d])).or_default().push(i);
4616    }
4617    for (seg, group) in groups {
4618        let mut p = prefix.to_vec();
4619        p.push(seg);
4620        carve_at(root, items, &p, &group, keys, exact);
4621    }
4622}
4623
4624// ── Windows (§2.11) ──────────────────────────────────────────────────────
4625
4626/// Each listed owner of state whose configured window (`windows`, by
4627/// address; [`DEFAULT_WINDOW_S`] when absent) is below a face's outage
4628/// (§2.11). Under a link.v2 policy, only an owner of state whose deletes
4629/// only a tombstone proves (v2 §2.11, [`Res::tombstone_only`]).
4630#[must_use]
4631pub fn check_windows(
4632    policy: &FacePolicy,
4633    deployment: &Deployment,
4634    windows: &BTreeMap<String, u64>,
4635) -> Vec<Finding> {
4636    let mut out = Vec::new();
4637    // The listed services and the devices (v2 §2.5).
4638    for s in policy.owners() {
4639        let Some(ifaces) = deployment.implements.get(s.key) else {
4640            continue;
4641        };
4642        // v2 §2.11 (0.9): under link.v2, only state whose deletes only a
4643        // tombstone proves, in any revision given.
4644        let v2 = policy.profile == Profile::V2;
4645        let owns_state = ifaces.iter().any(|i| {
4646            deployment.interfaces.get(i).is_some_and(|revs| {
4647                revs.iter()
4648                    .flatten()
4649                    .any(|r| is_state(r.token) && (!v2 || r.tombstone_only))
4650            })
4651        });
4652        if !owns_state {
4653            continue;
4654        }
4655        let addr = s.address;
4656        let w = windows.get(&addr).copied().unwrap_or(DEFAULT_WINDOW_S);
4657        for (name, face) in &policy.faces {
4658            if w < face.max_outage_s {
4659                out.push(Finding::new(
4660                    Code::WindowUnderOutage,
4661                    Some(name),
4662                    addr.clone(),
4663                ));
4664            }
4665        }
4666    }
4667    sort_findings(&mut out);
4668    out
4669}
4670
4671// ── A router's block (§2.15) ─────────────────────────────────────────────
4672
4673/// One deny of a router's block, as read.
4674#[derive(Debug, Clone, Default, PartialEq, Eq)]
4675pub struct BlockDeny {
4676    pub flows: Vec<String>,
4677    pub messages: Vec<String>,
4678    pub key_exprs: Vec<String>,
4679}
4680
4681/// One downsampling rule of a router's block, as read.
4682#[derive(Debug, Clone, PartialEq)]
4683pub struct BlockRule {
4684    pub key_expr: String,
4685    pub freq: f64,
4686}
4687
4688/// zenoh's `default_permission`, as a router's block runs it (core §11.2).
4689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4690pub enum Posture {
4691    Deny,
4692    Allow,
4693}
4694
4695/// One subject of a router's block, as read (§2.4, §2.15): zenoh 1.10.1's
4696/// `AclConfigSubjects`. A session matches it when it matches every property
4697/// the subject names, and one value of each.
4698#[derive(Debug, Clone, Default, PartialEq, Eq)]
4699pub struct BlockSubject {
4700    pub id: String,
4701    pub usernames: Vec<String>,
4702    pub cert_common_names: Vec<String>,
4703    /// `None` when the subject names no link protocol: it selects every one.
4704    /// An empty list, which zenoh 1.10.1 refuses to load (§2.15, 0.4), is
4705    /// read as `None`.
4706    pub link_protocols: Option<Vec<String>>,
4707    pub interfaces: Vec<String>,
4708    pub zids: Vec<String>,
4709}
4710
4711impl BlockSubject {
4712    /// Whether it is bound to a principal: a user name or a CN.
4713    fn bound(&self) -> bool {
4714        !self.usernames.is_empty() || !self.cert_common_names.is_empty()
4715    }
4716
4717    /// The link protocols it names; `None` for every one, an empty list
4718    /// included.
4719    fn protocols(&self) -> Option<&[String]> {
4720        self.link_protocols.as_deref().filter(|p| !p.is_empty())
4721    }
4722
4723    /// Whether it selects the link protocol `p`.
4724    fn selects(&self, p: &str) -> bool {
4725        self.protocols().is_none_or(|l| l.iter().any(|x| x == p))
4726    }
4727
4728    /// Whether it can match a session over `face` (§2.15): its link
4729    /// protocols are absent or name one of the face's. Interfaces and zids
4730    /// keep no session off a face: a zid is unauthenticated (core §11.3),
4731    /// and a face's link may report an interface.
4732    fn on_face(&self, face: &Face) -> bool {
4733        self.protocols()
4734            .is_none_or(|l| l.iter().any(|x| face.link_protocols.contains(x)))
4735    }
4736
4737    /// Whether it is the far principal's (§2.15, 0.4, 0.5): it names `far`
4738    /// alone in one of its two lists, and nothing in the other. zenoh
4739    /// matches one value of each property a subject names, so a subject
4740    /// naming user names and CNs matches only a session presenting one of
4741    /// each (measured, 0.5, F-121), which the block cannot attribute to one
4742    /// principal.
4743    fn far_alone(&self, far: &str) -> bool {
4744        let only = |v: &[String]| !v.is_empty() && v.iter().all(|x| x == far);
4745        match (self.usernames.is_empty(), self.cert_common_names.is_empty()) {
4746            (false, true) => only(&self.usernames),
4747            (true, false) => only(&self.cert_common_names),
4748            _ => false,
4749        }
4750    }
4751
4752    /// Whether it answers for the name `name` of the kind `kind` (§2.15,
4753    /// `narrowed_too_far`, 0.5): it names no interface and no zid, and
4754    /// either names no user name and no CN, or names `name` in the list of
4755    /// that kind and nothing in the other. A name no subject binds answers
4756    /// only to a subject bound to no principal.
4757    fn answers(&self, name: &str, kind: NameKind) -> bool {
4758        if !self.interfaces.is_empty() || !self.zids.is_empty() {
4759            return false;
4760        }
4761        if !self.bound() {
4762            return true;
4763        }
4764        let has = |v: &[String]| v.iter().any(|x| x == name);
4765        match kind {
4766            NameKind::User => self.cert_common_names.is_empty() && has(&self.usernames),
4767            NameKind::Cn => self.usernames.is_empty() && has(&self.cert_common_names),
4768            NameKind::Unbound => false,
4769        }
4770    }
4771}
4772
4773/// The kind of a name `narrowed_too_far` reads (§2.15, 0.5): a user name
4774/// or a CN, as the list naming it says, or a face's `far` that no subject
4775/// names in either list, whose kind the block cannot tell.
4776#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
4777enum NameKind {
4778    User,
4779    Cn,
4780    Unbound,
4781}
4782
4783/// One policy of a router's block, as read (§2.15, 0.4): the ids of the
4784/// subjects it lists. Its rules are not read here: which policies list a
4785/// subject is what the subject checks need.
4786#[derive(Debug, Clone, Default, PartialEq, Eq)]
4787pub struct BlockPolicy {
4788    pub subjects: Vec<String>,
4789}
4790
4791/// A block's posture, every subject it defines and every policy's subject
4792/// list, when they were read.
4793#[derive(Debug, Clone, PartialEq, Eq)]
4794pub struct BlockSubjects {
4795    pub posture: Posture,
4796    pub subjects: Vec<BlockSubject>,
4797    pub policies: Vec<BlockPolicy>,
4798}
4799
4800impl BlockSubjects {
4801    /// The indices of the policies that list the subject `id`.
4802    fn listing(&self, id: &str) -> BTreeSet<usize> {
4803        self.policies
4804            .iter()
4805            .enumerate()
4806            .filter(|(_, p)| p.subjects.iter().any(|s| s == id))
4807            .map(|(i, _)| i)
4808            .collect()
4809    }
4810}
4811
4812/// What a router runs for one face, as somebody read it (§2.15).
4813#[derive(Debug, Clone, Default, PartialEq)]
4814pub struct Block {
4815    /// The deployment's namespace, empty for none (core §1.6).
4816    pub namespace: String,
4817    /// The block's `enabled`, as read: `Some(false)` when access control is
4818    /// not enabled, which a tool reading a router's configuration also reads
4819    /// for an `enabled` absent from it, as zenoh 1.10.1 does (§2.15, 0.7,
4820    /// F-124); `None` when it was not read.
4821    pub enabled: Option<bool>,
4822    /// The denies of every policy that lists one subject that can match
4823    /// the far principal's sessions on the face (§2.15): a tool checks each
4824    /// such subject's denies alone, since any allow wins across subjects.
4825    pub deny: Vec<BlockDeny>,
4826    /// In the block's order.
4827    pub downsampling: Vec<BlockRule>,
4828    /// The block's posture, subjects and policies' subject lists, which
4829    /// [`check_subjects`] and [`check_narrowing`] read; `None` when they
4830    /// were not read.
4831    pub subjects: Option<BlockSubjects>,
4832}
4833
4834/// Checks a router's block for the face `face` (§2.15): `block_disabled`
4835/// when its access control is not enabled (0.7, F-124), beside every other
4836/// finding, which reads the block as written; `zk_not_denied`;
4837/// `wildcard_downsampling` and `intersecting_downsampling`. On a device
4838/// face (`device`, v2 §2.15) `zk_not_denied` reads §2.6's carve: a whole
4839/// `zk` passes, and so does the carve; on any other face the carve fails.
4840#[must_use]
4841pub fn check_block(face: &str, device: bool, block: &Block) -> Vec<Finding> {
4842    let mut out = Vec::new();
4843    if block.enabled == Some(false) {
4844        out.push(Finding::new(Code::BlockDisabled, Some(face), "enabled"));
4845    }
4846    let ns = block.namespace.trim_matches('/');
4847    let with_ns = |k: &str| {
4848        if ns.is_empty() {
4849            k.to_owned()
4850        } else {
4851            format!("{ns}/{k}")
4852        }
4853    };
4854    let denied = if device {
4855        ZK_CARVED
4856            .iter()
4857            .all(|k| zk_denied_on(&with_ns(k), &block.deny, |_, _| true))
4858            && zk_denied_on(&with_ns(ZK_INSTANCE), &block.deny, |f, m| {
4859                !OWN_PAIRS.contains(&(f, m))
4860            })
4861    } else {
4862        zk_denied_on(&with_ns(ZK_DENY), &block.deny, |_, _| true)
4863    };
4864    if !denied {
4865        out.push(Finding::new(Code::ZkNotDenied, Some(face), "@zk"));
4866    }
4867    let parsed: Vec<Option<&keyexpr>> = block
4868        .downsampling
4869        .iter()
4870        .map(|r| keyexpr::new(r.key_expr.as_str()).ok())
4871        .collect();
4872    for (j, r) in block.downsampling.iter().enumerate() {
4873        // `*`, `**` and `$*` each carry a `*` (zenoh-keyexpr's own test).
4874        if parsed[j].is_none_or(|k| k.as_str().contains('*')) {
4875            out.push(Finding::new(
4876                Code::WildcardDownsampling,
4877                Some(face),
4878                r.key_expr.clone(),
4879            ));
4880        }
4881        let hit = (0..j).any(|i| match (parsed[i], parsed[j]) {
4882            (Some(a), Some(b)) => a.intersects(b),
4883            _ => false,
4884        });
4885        if hit {
4886            out.push(Finding::new(
4887                Code::IntersectingDownsampling,
4888                Some(face),
4889                r.key_expr.clone(),
4890            ));
4891        }
4892    }
4893    sort_findings(&mut out);
4894    out
4895}
4896
4897/// Whether every pair of the nine messages and both flows that `pairs`
4898/// holds is denied on a key expression that includes `target` (§2.15; v2
4899/// §2.15).
4900fn zk_denied_on(target: &str, deny: &[BlockDeny], pairs: impl Fn(&str, &str) -> bool) -> bool {
4901    let Ok(target) = keyexpr::new(target) else {
4902        return false;
4903    };
4904    FLOWS.iter().all(|flow| {
4905        MESSAGES.iter().filter(|m| pairs(flow, m)).all(|m| {
4906            deny.iter().any(|d| {
4907                d.flows.iter().any(|f| f == flow)
4908                    && d.messages.iter().any(|x| x == m)
4909                    && d.key_exprs
4910                        .iter()
4911                        .any(|k| keyexpr::new(k.as_str()).is_ok_and(|k| k.includes(target)))
4912            })
4913        })
4914    })
4915}
4916
4917/// Checks a router's subjects against the face `name` they must keep to
4918/// its far principal (§2.4, §2.15):
4919/// - `near_subject_on_face`, each subject on the face bound by a user name
4920///   or a CN that is not the far principal's, whatever else it names
4921///   (0.4): zenoh ties no credential to a link, and matches one value of
4922///   each property, so a session over the face with another name the
4923///   subject binds matches it. The far principal's names it alone in one
4924///   list and nothing in the other (0.5): a subject naming user names and
4925///   CNs matches only a session presenting one of each, whose principal
4926///   the block cannot tell, and its policies are not the far principal's;
4927/// - `face_subject_beyond_face`, each face subject (on the face, bound by
4928///   no user name and no CN) whose link protocols are absent or name one
4929///   outside the face's: sessions off the face match it too (0.4);
4930/// - `face_subject_misplaced`, each face subject not listed in exactly the
4931///   policies that list a subject of the far principal's on the face, at
4932///   least one: it would grant every session over the face another
4933///   policy's rules, miss one of the far principal's denies, or, listed in
4934///   none, get the default (0.4);
4935/// - `face_subject_missing`, under `allow`, each link protocol of the face
4936///   that no face subject naming no interface and no zid names in its
4937///   `link_protocols`: a session over it that matches no other subject
4938///   gets the default, everything.
4939#[must_use]
4940pub fn check_subjects(name: &str, face: &Face, block: &BlockSubjects) -> Vec<Finding> {
4941    let mut out = Vec::new();
4942    let on_face: Vec<&BlockSubject> = block.subjects.iter().filter(|s| s.on_face(face)).collect();
4943    // The far principal's policies: those listing one of its subjects on
4944    // the face.
4945    let far_policies: BTreeSet<usize> = on_face
4946        .iter()
4947        .filter(|s| s.far_alone(&face.far))
4948        .flat_map(|s| block.listing(&s.id))
4949        .collect();
4950    for s in &on_face {
4951        let mut found = |code: Code| out.push(Finding::new(code, Some(name), s.id.clone()));
4952        if s.bound() {
4953            if !s.far_alone(&face.far) {
4954                found(Code::NearSubjectOnFace);
4955            }
4956            continue;
4957        }
4958        if s.protocols()
4959            .is_none_or(|l| l.iter().any(|x| !face.link_protocols.contains(x)))
4960        {
4961            found(Code::FaceSubjectBeyondFace);
4962        }
4963        let listed = block.listing(&s.id);
4964        if listed.is_empty() || listed != far_policies {
4965            found(Code::FaceSubjectMisplaced);
4966        }
4967    }
4968    if block.posture == Posture::Allow {
4969        for p in &face.link_protocols {
4970            let selected = block.subjects.iter().any(|s| {
4971                !s.bound()
4972                    && s.interfaces.is_empty()
4973                    && s.zids.is_empty()
4974                    && s.protocols().is_some_and(|l| l.contains(p))
4975            });
4976            if !selected {
4977                out.push(Finding::new(
4978                    Code::FaceSubjectMissing,
4979                    Some(name),
4980                    p.clone(),
4981                ));
4982            }
4983        }
4984    }
4985    sort_findings(&mut out);
4986    out
4987}
4988
4989/// Checks a router's subjects against every face of `policy` at once
4990/// (§2.4, §2.15, 0.4, 0.5): under `allow`, `narrowed_too_far` (no face,
4991/// `at` the name) for each name the block binds, read by kind: each user
4992/// name a subject names, as a user name; each CN, as a CN; and each face's
4993/// far principal that no subject names in either list, of a kind the block
4994/// cannot tell. Such a name is reported with a link protocol of §2.1's
4995/// list, outside every face whose far principal it is not, that no subject
4996/// answering for it selects: one naming no interface and no zid, and either
4997/// naming no user name and no CN, or naming the name in the list of its
4998/// kind and nothing in the other (0.5, F-121). zenoh matches one value of
4999/// each property a subject names, so a session with that name alone over
5000/// that link protocol matches no subject, and is allowed everything (core
5001/// §11.3): a far principal with no subject at all among them. One finding
5002/// per name, whichever kinds fail. Under `deny`, such a session gets
5003/// nothing, and there is nothing to report.
5004#[must_use]
5005pub fn check_narrowing(policy: &FacePolicy, block: &BlockSubjects) -> Vec<Finding> {
5006    let mut out = Vec::new();
5007    if block.posture != Posture::Allow {
5008        return out;
5009    }
5010    let mut names: BTreeSet<(&str, NameKind)> = BTreeSet::new();
5011    for s in &block.subjects {
5012        names.extend(s.usernames.iter().map(|u| (u.as_str(), NameKind::User)));
5013        names.extend(
5014            s.cert_common_names
5015                .iter()
5016                .map(|c| (c.as_str(), NameKind::Cn)),
5017        );
5018    }
5019    for f in policy.faces.values() {
5020        // Named in either list, by any subject, interfaces and zids
5021        // included: it is then read by the kinds those lists give it.
5022        let bound = block.subjects.iter().any(|s| {
5023            s.usernames
5024                .iter()
5025                .chain(&s.cert_common_names)
5026                .any(|x| *x == f.far)
5027        });
5028        if !bound {
5029            names.insert((f.far.as_str(), NameKind::Unbound));
5030        }
5031    }
5032    let mut bare_names: BTreeSet<&str> = BTreeSet::new();
5033    for (name, kind) in names {
5034        let kept: Vec<String> =
5035            narrowed(policy, |f| policy.faces[f].far == name).unwrap_or_else(|| {
5036                policy
5037                    .binding
5038                    .protocols()
5039                    .iter()
5040                    .map(|p| (*p).to_owned())
5041                    .collect()
5042            });
5043        let bare = kept.iter().any(|p| {
5044            !block
5045                .subjects
5046                .iter()
5047                .any(|s| s.answers(name, kind) && s.selects(p))
5048        });
5049        if bare {
5050            bare_names.insert(name);
5051        }
5052    }
5053    for name in bare_names {
5054        out.push(Finding::new(Code::NarrowedTooFar, None, name));
5055    }
5056    sort_findings(&mut out);
5057    out
5058}
5059
5060/// The link protocols a subject bound to a principal is selected by, on the
5061/// router of `policy` (§2.4): every one of the binding's closed list (v2
5062/// §2.4; §2.1's nine for a `link.v1` policy) outside the faces whose far
5063/// principal it is not (`is_far`, by the face's name), in the list's order.
5064/// `None` when no face excludes any: the subject names none. Empty when
5065/// every protocol is excluded: the principal could connect over none.
5066#[must_use]
5067pub fn narrowed(policy: &FacePolicy, is_far: impl Fn(&str) -> bool) -> Option<Vec<String>> {
5068    let excluded: BTreeSet<&str> = policy
5069        .faces
5070        .iter()
5071        .filter(|(name, _)| !is_far(name))
5072        .flat_map(|(_, f)| f.link_protocols.iter().map(String::as_str))
5073        .collect();
5074    (!excluded.is_empty()).then(|| {
5075        policy
5076            .binding
5077            .protocols()
5078            .iter()
5079            .filter(|p| !excluded.contains(*p))
5080            .map(|p| (*p).to_owned())
5081            .collect()
5082    })
5083}
5084
5085// ── Lint (§2.1, §2.3, §2.11, §2.15) ──────────────────────────────────────
5086
5087/// What a linter is given: the policy's text, and what else it has.
5088#[derive(Debug, Clone, Copy, Default)]
5089pub struct LintInput<'a> {
5090    pub text: &'a str,
5091    /// When given, the plan is derived, and its findings included.
5092    pub deployment: Option<&'a Deployment>,
5093    /// The windows the deployment configures, by address; needs the
5094    /// deployment.
5095    pub windows: Option<&'a BTreeMap<String, u64>>,
5096    /// A router's block, and the face it guards.
5097    pub block: Option<(&'a str, &'a Block)>,
5098}
5099
5100/// Every finding of a face policy and of what comes with it, sorted. The
5101/// plan, the windows and the block are checked only when the policy has no
5102/// error.
5103#[must_use]
5104pub fn lint(input: &LintInput<'_>) -> Vec<Finding> {
5105    let parsed = parse(input.text);
5106    let mut out = parsed.findings;
5107    let Some(policy) = parsed.policy else {
5108        return out;
5109    };
5110    if let Some(d) = input.deployment {
5111        match plan(&policy, d) {
5112            Ok(plans) => out.extend(plans.into_iter().flat_map(|p| p.findings)),
5113            Err(f) => out.extend(f),
5114        }
5115        if let Some(w) = input.windows {
5116            out.extend(check_windows(&policy, d, w));
5117        }
5118    }
5119    if let Some((face, block)) = input.block {
5120        let device = policy.faces.get(face).is_some_and(|f| f.attach.is_device());
5121        out.extend(check_block(face, device, block));
5122        if let Some(s) = &block.subjects {
5123            if let Some(f) = policy.faces.get(face) {
5124                out.extend(check_subjects(face, f, s));
5125            }
5126            out.extend(check_narrowing(&policy, s));
5127        }
5128    }
5129    sort_findings(&mut out);
5130    out
5131}
5132
5133#[cfg(test)]
5134mod tests {
5135    use super::*;
5136
5137    fn ke(s: &str) -> &keyexpr {
5138        keyexpr::new(s).unwrap()
5139    }
5140
5141    /// A binding reads from a tool's configuration by its policy name, and
5142    /// any other string is refused with the names it could have been.
5143    #[test]
5144    fn a_binding_deserializes_by_its_name() {
5145        for b in Binding::ALL {
5146            let read: Binding = serde_json::from_value(Value::from(b.as_str())).unwrap();
5147            assert_eq!(read, b);
5148            assert_eq!(serde_json::to_value(b).unwrap(), Value::from(b.as_str()));
5149        }
5150        let e = serde_json::from_value::<Binding>(Value::from("zenoh-1.10.0"))
5151            .unwrap_err()
5152            .to_string();
5153        assert!(
5154            e.contains("zenoh-1.10.0")
5155                && e.contains("`zenoh-1.10.1`")
5156                && e.contains("`zenoh-1.10.2`")
5157                && e.contains("`zm-1.10.2-r1`"),
5158            "{e}"
5159        );
5160        assert!(serde_json::from_value::<Binding>(Value::from(1)).is_err());
5161    }
5162
5163    /// A binding parses from a tool's flag by its policy name, and any
5164    /// other string is refused with the names it could have been, from the
5165    /// one list, [`Binding::NAMES`], in [`Binding::ALL`]'s order.
5166    #[test]
5167    fn a_binding_parses_by_its_name() {
5168        assert_eq!(Binding::NAMES, Binding::ALL.map(Binding::as_str));
5169        for b in Binding::ALL {
5170            assert_eq!(b.as_str().parse::<Binding>(), Ok(b));
5171            assert_eq!(b.to_string().parse::<Binding>(), Ok(b));
5172        }
5173        let e = "zenoh-1.10.0".parse::<Binding>().unwrap_err();
5174        assert_eq!(e, UnknownBinding("zenoh-1.10.0".to_owned()));
5175        assert_eq!(
5176            e.to_string(),
5177            "not a binding; one of: zenoh-1.10.1, zenoh-1.10.2, zm-1.10.2-r1, or zm-1.10.2-r<n> \
5178             for a later release of the fork"
5179        );
5180        assert!("".parse::<Binding>().is_err());
5181        assert!(
5182            "Zenoh-1.10.1".parse::<Binding>().is_err(),
5183            "names are exact"
5184        );
5185    }
5186
5187    /// A later release of the fork on zenoh 1.10.2 names the fork's
5188    /// binding (v2 §2.4; #1191): `zm-1.10.2-r2` parses, from a policy and
5189    /// from a flag, as `zm-1.10.2-r1`, with its protocols and defaults, and
5190    /// a policy naming it plans as one naming `r1` does. `r0`, a leading
5191    /// zero, no number, or anything after it is no binding.
5192    #[test]
5193    fn a_later_release_of_the_fork_names_its_binding() {
5194        for name in ["zm-1.10.2-r2", "zm-1.10.2-r10", "zm-1.10.2-r123"] {
5195            assert_eq!(Binding::parse(name), Some(Binding::Zm1_10_2R1), "{name}");
5196            assert_eq!(name.parse::<Binding>(), Ok(Binding::Zm1_10_2R1), "{name}");
5197            assert_eq!(
5198                serde_json::from_value::<Binding>(Value::from(name)).ok(),
5199                Some(Binding::Zm1_10_2R1),
5200                "{name}"
5201            );
5202        }
5203        for name in [
5204            "zm-1.10.2-r0",
5205            "zm-1.10.2-r01",
5206            "zm-1.10.2-r",
5207            "zm-1.10.2-r2x",
5208            "zm-1.10.2-r-2",
5209            "zm-1.10.3-r1",
5210            "zm-1.10.2",
5211        ] {
5212            assert_eq!(Binding::parse(name), None, "{name}");
5213        }
5214        let policy = |binding: &str| {
5215            format!(
5216                "profile  = \"link.v2\"\nsystem   = \"lab\"\nservices = [\"radio-a\"]\n\
5217                 binding  = \"{binding}\"\n\n[transport]\nlease_ms             = 240000\n\
5218                 keep_alive           = 4\nwait_before_close_ms = 240000\n\
5219                 sequence             = \"16bit\"\nbatch_bytes          = 222\n\n[face.radio]\n\
5220                 far              = \"ground\"\nattach           = \"client\"\n\
5221                 select           = {{ link_protocols = [\"unixsock-dgram\"] }}\n\
5222                 class            = \"constrained\"\nexpose           = \"link\"\n\
5223                 interval_s       = 60\nmax_outage_s     = 3600\nlink_bps         = 2400\n\
5224                 loss_ppm         = 0\narq              = true\nreply_timeout_ms = 15000\n"
5225            )
5226        };
5227        let r1 = parse(&policy("zm-1.10.2-r1"));
5228        let r2 = parse(&policy("zm-1.10.2-r2"));
5229        assert_eq!(
5230            r2.findings, r1.findings,
5231            "the same findings: none on unixsock-dgram"
5232        );
5233        let (r1, mut r2) = (r1.policy.expect("r1 reads"), r2.policy.expect("r2 reads"));
5234        assert_eq!(r2.binding, Binding::Zm1_10_2R1);
5235        // It keeps the name it was given, for what a plan writes (#1204).
5236        assert_eq!(r2.binding_name, "zm-1.10.2-r2");
5237        assert_eq!(r1.binding_name, "zm-1.10.2-r1");
5238        r2.binding_name = r1.binding_name.clone();
5239        assert_eq!(
5240            r2, r1,
5241            "but for its name, a policy naming r2 reads as one naming r1"
5242        );
5243    }
5244
5245    /// Stock 1.10.2 reads as 1.10.1 (v2 §2.4, §2.19; #1165): one list of
5246    /// link protocols, `unixsock-dgram` not among them, and one column of
5247    /// defaults, whose 5 s `wait_before_close` is not the fork's 10 s. A
5248    /// policy names it all the same, and its plan carries it.
5249    #[test]
5250    fn zenoh_1_10_2_is_a_binding_that_reads_as_1_10_1() {
5251        let (stock, next, fork) = (
5252            Binding::Zenoh1_10_1,
5253            Binding::Zenoh1_10_2,
5254            Binding::Zm1_10_2R1,
5255        );
5256        assert_eq!(Binding::ALL, [stock, next, fork], "v2 §2.4's order");
5257        assert_eq!(next.protocols(), stock.protocols());
5258        assert!(!next.protocols().contains(&"unixsock-dgram"));
5259        assert!(fork.protocols().contains(&"unixsock-dgram"));
5260        assert_eq!(next.defaults(), stock.defaults());
5261        assert_eq!(next.defaults().wait_before_close_ms, 5_000);
5262        assert_ne!(next.defaults(), fork.defaults());
5263        assert_eq!(
5264            Binding::default(),
5265            stock,
5266            "a link.v1 policy reads as 1.10.1"
5267        );
5268
5269        let policy = |protocol: &str| {
5270            format!(
5271                "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
5272                 binding = \"zenoh-1.10.2\"\n[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
5273                 wait_before_close_ms = 10000\nsequence = \"16bit\"\nbatch_bytes = 222\n\
5274                 [face.rf]\nfar = \"ground\"\nattach = \"client\"\n\
5275                 select = {{ link_protocols = [\"{protocol}\"] }}\n\
5276                 class = \"constrained\"\nexpose = \"none\"\nmax_outage_s = 3600\n\
5277                 link_bps = 2400\nloss_ppm = 0\narq = true\nreply_timeout_ms = 15000\n"
5278            )
5279        };
5280        let read = parse(&policy("unixsock-stream"));
5281        assert!(read.findings.is_empty(), "{:?}", read.findings);
5282        assert_eq!(read.policy.map(|p| p.binding), Some(next));
5283        let refused = parse(&policy("unixsock-dgram"));
5284        assert_eq!(
5285            refused.findings.iter().map(|f| f.code).collect::<Vec<_>>(),
5286            [Code::UnknownProtocol],
5287            "{:?}",
5288            refused.findings
5289        );
5290    }
5291
5292    /// The zenoh facts the plan rests on (§0, §2.6, §2.7).
5293    #[test]
5294    fn key_expression_facts() {
5295        // `**` matches zero chunks: a subtree deny includes its prefix, and
5296        // `zk2/**/@zk/**` the contract keys.
5297        assert!(ke("zk2/*/*/m.v1/stream/a/**").includes(ke("zk2/h/s/m.v1/stream/a")));
5298        assert!(ke(ZK_DENY).includes(ke("zk2/@zk/contract/m.v1/abc")));
5299        assert!(ke(ZK_DENY).includes(ke("zk2/h/s/@zk/instance/0123456789abcdef")));
5300        assert!(ke("**/@zk/**").includes(ke(ZK_DENY)));
5301        // A rest parameter takes one or more chunks: `*/**` leaves its prefix.
5302        assert!(!ke("zk2/*/*/m.v1/events/logs/*/**").includes(ke("zk2/h/s/m.v1/events/logs")));
5303        assert!(ke("zk2/*/*/m.v1/events/logs/*/**").includes(ke("zk2/h/s/m.v1/events/logs/a/b")));
5304        // `*` never matches a verbatim chunk, so a wholesale deny spells it.
5305        assert!(!ke("zk2/*/*/*/stream/**").includes(ke("zk2/h/s/m.v1/@stream/x")));
5306        assert!(ke("zk2/*/*/*/@stream/**").includes(ke("zk2/h/s/m.v1/@stream/x")));
5307        assert!(ke(ADV_DENY).includes(ke("zk2/h/s/m.v1/stream/x/@adv/pub/abc")));
5308    }
5309
5310    /// A device face's carve (v2 §2.6): an instance key crosses on the Own
5311    /// row's seven pairs and no other, and every other `@zk` key on none.
5312    #[test]
5313    fn the_carve_lets_an_instance_key_cross_on_the_own_pairs_alone() {
5314        let carve = zk_carve();
5315        let denied = |key: &str, flow: &str, m: &str| {
5316            carve.iter().any(|d| {
5317                d.flows.contains(&flow)
5318                    && d.messages.contains(&m)
5319                    && d.key_exprs.iter().any(|k| ke(k).includes(ke(key)))
5320            })
5321        };
5322        let instance = "zk2/lab/probe-a/@zk/instance/0123456789abcdef";
5323        let mut open = Vec::new();
5324        for flow in FLOWS {
5325            for m in MESSAGES {
5326                for key in [
5327                    "zk2/lab/probe-a/@zk/alive/probe.v1",
5328                    "zk2/lab/probe-a/@zk/member/0123456789abcdef/x",
5329                    "zk2/@zk/contract/probe.v1/abc",
5330                ] {
5331                    assert!(denied(key, flow, m), "{key} {flow} {m}");
5332                }
5333                if !denied(instance, flow, m) {
5334                    open.push((flow, m));
5335                }
5336            }
5337        }
5338        open.sort_unstable();
5339        let mut own = OWN_PAIRS.to_vec();
5340        own.sort_unstable();
5341        assert_eq!(open, own);
5342        // The carve names no address: whose instance keys is the grants'.
5343        assert!(
5344            carve
5345                .iter()
5346                .flat_map(|d| &d.key_exprs)
5347                .all(|k| k.starts_with("zk2/*/*/") || k == "zk2/@zk/**")
5348        );
5349    }
5350
5351    #[test]
5352    fn keys_collapse_a_trailing_rest() {
5353        assert_eq!(
5354            key("r", &[Seg::Lit("x".into()), Seg::Rest], "/**"),
5355            "r/x/*/**"
5356        );
5357        assert_eq!(key("r", &[], "/**"), "r/**");
5358        assert_eq!(key("r", &[Seg::Lit("a".into())], "/*/**"), "r/a/*/**");
5359    }
5360
5361    fn res(template: &str, annotations: Value) -> Res {
5362        Res::new(
5363            Template::parse(template).unwrap(),
5364            KindToken::Stream,
5365            serde_json::from_value(annotations).unwrap(),
5366        )
5367    }
5368
5369    /// Two revisions read together (§2.3, 0.3): exposed only where every
5370    /// one that declares a resource exposes it, a horizon only where every
5371    /// one gives one, the least; a resource one revision adds is its own.
5372    #[test]
5373    fn revisions_are_read_together_failing_closed() {
5374        let a = vec![
5375            res(
5376                "x",
5377                serde_json::json!({"link.exposure": "link", "freshness.ttl_s": 10}),
5378            ),
5379            res(
5380                "y",
5381                serde_json::json!({"link.exposure": "link", "freshness.ttl_s": 10}),
5382            ),
5383            res("w", serde_json::json!({"link.exposure": "LINK"})),
5384        ];
5385        let b = vec![
5386            res("x", serde_json::json!({"freshness.ttl_s": 4})),
5387            res(
5388                "y",
5389                serde_json::json!({"link.exposure": "link", "freshness.ttl_s": 0}),
5390            ),
5391            res("w", serde_json::json!({})),
5392            res("z", serde_json::json!({"link.exposure": "link"})),
5393        ];
5394        let (m, disagree) = merge(&[a, b]);
5395        let read = |t: &str| {
5396            let r = m.iter().find(|r| r.template.as_str() == t).unwrap();
5397            (exposure_of_res(r), horizon(r).ttl().map(|d| d.as_secs()))
5398        };
5399        assert_eq!(read("x"), (Exposure::Host, Some(4)));
5400        assert_eq!(read("y"), (Exposure::Link, None));
5401        assert_eq!(read("z"), (Exposure::Link, None));
5402        // Two readings of host, one invalid: no disagreement to report.
5403        assert_eq!(disagree, BTreeSet::from([0]));
5404    }
5405
5406    /// What link.v2 weighs, each revision judged alone, in either order
5407    /// (v2 §2.3, 0.6, F-469): one raw revision makes it not packed, one
5408    /// deadline timed, and the longest put is a `block` revision's.
5409    #[test]
5410    fn link_v2_judges_each_revision_alone() {
5411        let raw = res("s", serde_json::json!({"link.exposure": "link"}));
5412        let mut packed = raw.clone();
5413        packed.packed = true;
5414        packed.block = true;
5415        packed.longest_bytes = Some(300);
5416        let mut timed = raw.clone();
5417        timed.packed = true;
5418        timed.longest_bytes = Some(400);
5419        timed
5420            .annotations
5421            .insert(crate::timing::DEADLINE_MS.to_owned(), Value::from(2000));
5422        for revs in [
5423            [vec![raw.clone()], vec![packed.clone()], vec![timed.clone()]],
5424            [vec![timed.clone()], vec![packed.clone()], vec![raw.clone()]],
5425        ] {
5426            let (m, _) = merge(&revs);
5427            let r = &m[0];
5428            assert!(!r.packed, "one revision's raw type");
5429            assert!(r.shape().timed, "one revision's deadline");
5430            assert!(r.block);
5431            assert_eq!(r.longest_bytes, Some(300), "the block revision's");
5432        }
5433        let (m, _) = merge(&[vec![packed.clone()], vec![timed.clone()]]);
5434        assert!(m[0].packed, "packed in every revision");
5435        let (m, _) = merge(&[vec![timed.clone()], vec![raw]]);
5436        assert_eq!(m[0].longest_bytes, Some(400), "none block: the longest");
5437    }
5438
5439    fn exposure_of_res(r: &Res) -> Exposure {
5440        match exposure(kind_of(r.token), &r.annotations) {
5441            Exposure::Invalid(_) => Exposure::Host,
5442            e => e,
5443        }
5444    }
5445
5446    fn face(far: &str, protocols: &[&str]) -> Face {
5447        Face {
5448            far: far.to_owned(),
5449            attach: Attach::Client,
5450            link_protocols: protocols.iter().map(|p| (*p).to_owned()).collect(),
5451            expose: Expose::Link,
5452            interval_s: Some(1),
5453            max_outage_s: 1,
5454            batch_bytes: 1,
5455            link_bps: 1,
5456            lease_ms: DEFAULT_LEASE_MS,
5457            loss_ppm: None,
5458            arq: None,
5459            reply_timeout_ms: None,
5460            frames: None,
5461            events: None,
5462            horizon_s: None,
5463            opens: Opens::Far,
5464        }
5465    }
5466
5467    /// A subject keeps the closed list outside every face whose far
5468    /// principal it is not (§2.4, 0.3).
5469    #[test]
5470    fn a_subject_is_narrowed_off_the_faces_it_is_not_far_of() {
5471        let policy = |faces: Vec<(&str, Face)>| FacePolicy {
5472            profile: Profile::V1,
5473            system: "lab".into(),
5474            services: vec![],
5475            faces: faces.into_iter().map(|(n, f)| (n.to_owned(), f)).collect(),
5476            binding: Binding::Zenoh1_10_1,
5477            binding_name: Binding::Zenoh1_10_1.as_str().to_owned(),
5478            transport: None,
5479            catalog: None,
5480        };
5481        let two = policy(vec![
5482            ("radio", face("ground", &["unixsock-stream"])),
5483            ("sat", face("sat", &["serial", "unixpipe"])),
5484        ]);
5485        let of = |p: &str| narrowed(&two, |name| two.faces[name].far == p);
5486        assert_eq!(
5487            of("local").unwrap(),
5488            ["tcp", "udp", "tls", "quic", "vsock", "ws"]
5489        );
5490        assert_eq!(
5491            of("ground").unwrap(),
5492            [
5493                "tcp",
5494                "udp",
5495                "tls",
5496                "quic",
5497                "unixsock-stream",
5498                "vsock",
5499                "ws"
5500            ]
5501        );
5502        let one = policy(vec![("radio", face("ground", &["unixsock-stream"]))]);
5503        assert_eq!(narrowed(&one, |_| true), None);
5504        let all = policy(vec![("x", face("x", Binding::Zenoh1_10_1.protocols()))]);
5505        assert_eq!(narrowed(&all, |_| false), Some(Vec::new()));
5506        // The fork's list keeps `unixsock-dgram`, after `unixsock-stream`
5507        // (v2 §2.4).
5508        let fork = FacePolicy {
5509            binding: Binding::Zm1_10_2R1,
5510            binding_name: Binding::Zm1_10_2R1.as_str().to_owned(),
5511            ..policy(vec![("radio", face("ground", &["unixsock-stream"]))])
5512        };
5513        assert_eq!(
5514            narrowed(&fork, |_| false).unwrap(),
5515            [
5516                "tcp",
5517                "udp",
5518                "tls",
5519                "quic",
5520                "serial",
5521                "unixpipe",
5522                "unixsock-dgram",
5523                "vsock",
5524                "ws"
5525            ]
5526        );
5527    }
5528
5529    /// `keep_alive_flaps` over v2's Appendix B (v2 §2.16): at 5 % loss,
5530    /// 240 s with 4 keep-alives expects 0.36 false closes a day, 120 s with
5531    /// 2 expects 144; at no loss 2 never flaps, and 1 always does.
5532    #[test]
5533    fn the_keep_alive_lint_is_exact() {
5534        assert!(!flaps(240_000, 4, 50_000));
5535        assert!(!flaps(120_000, 4, 50_000));
5536        assert!(!flaps(1_080_000, 4, 50_000));
5537        assert!(flaps(120_000, 2, 50_000));
5538        assert!(flaps(60_000, 2, 50_000));
5539        assert!(!flaps(3_600_000, 2, 0));
5540        assert!(flaps(3_600_000, 1, 0));
5541        // 2 × 86,400 × 1,000 × 4 × 0.05^3 = lease_ms exactly: not above.
5542        assert!(!flaps(86_400, 4, 50_000));
5543        assert!(flaps(86_399, 4, 50_000));
5544        // The bounds, exactly: 255 keep-alives at 99.9999 % delivery.
5545        assert!(flaps(MAX_U32, MAX_KEEP_ALIVE, MAX_LOSS_PPM - 1));
5546        assert!(!flaps(MAX_U32, MAX_KEEP_ALIVE, 0));
5547    }
5548
5549    /// A good face beside a `[transport]` that is not one never makes a
5550    /// policy (v2 §2.1): the face takes its batch and lease from it, and the
5551    /// error `[transport]` pushed refuses the whole.
5552    #[test]
5553    fn a_bad_transport_refuses_a_good_face() {
5554        let face = "[face.rf]\nfar = \"ground\"\nattach = \"client\"\n\
5555                    select = { link_protocols = [\"unixsock-stream\"] }\n\
5556                    class = \"constrained\"\nexpose = \"none\"\nmax_outage_s = 3600\n\
5557                    link_bps = 2400\nloss_ppm = 0\narq = true\nreply_timeout_ms = 15000\n";
5558        let head = "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
5559                    binding = \"zenoh-1.10.1\"\n";
5560        let good = "[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
5561                    wait_before_close_ms = 10000\nsequence = \"16bit\"\n";
5562        let ok = parse(&format!("{head}{good}{face}"));
5563        assert!(ok.policy.is_some(), "{:?}", ok.findings);
5564        for (transport, code, at) in [
5565            ("", Code::TransportMissing, "transport"),
5566            ("transport = 1\n", Code::BadValue, "transport"),
5567            (
5568                &good.replace("lease_ms = 10000", "lease_ms = 0"),
5569                Code::BadValue,
5570                "transport.lease_ms",
5571            ),
5572            (
5573                &good.replace("lease_ms = 10000\n", ""),
5574                Code::MissingField,
5575                "transport.lease_ms",
5576            ),
5577            (
5578                &format!("{good}batch_bytes = 65536\n"),
5579                Code::BadValue,
5580                "transport.batch_bytes",
5581            ),
5582        ] {
5583            let p = parse(&format!("{head}{transport}{face}"));
5584            assert!(p.policy.is_none(), "{transport:?}");
5585            assert!(
5586                p.findings
5587                    .iter()
5588                    .any(|f| f.code == code && f.at == at && f.face.is_none()),
5589                "{transport:?}: {:?}",
5590                p.findings
5591            );
5592        }
5593    }
5594
5595    /// `wait_under_lease` reads both values as integers (v2 §2.19): a u64
5596    /// above i64::MAX and a negative i64 among them; a value of another type
5597    /// is `transport_differs`, which the check of every key reports.
5598    #[test]
5599    fn wait_under_lease_reads_integers_and_a_wrong_type_differs() {
5600        let p = parse(
5601            "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
5602             binding = \"zenoh-1.10.1\"\n[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
5603             wait_before_close_ms = 10000\nsequence = \"32bit\"\n[face.rf]\n\
5604             far = \"ground\"\nattach = \"client\"\n\
5605             select = { link_protocols = [\"unixsock-stream\"] }\nclass = \"constrained\"\n\
5606             expose = \"none\"\nmax_outage_s = 3600\nlink_bps = 1000000\nloss_ppm = 0\n\
5607             arq = true\nreply_timeout_ms = 15000\n",
5608        )
5609        .policy
5610        .expect("a policy");
5611        let wbc = TransportKey::WaitBeforeClose.path();
5612        let lease = TransportKey::Lease.path();
5613        let found = |pairs: &[(&str, Value)]| -> Vec<(&'static str, String)> {
5614            // A router that stamps nothing, as the generator writes it.
5615            let stated = StatedTransport(
5616                pairs
5617                    .iter()
5618                    .map(|(k, v)| ((*k).to_owned(), v.clone()))
5619                    .chain([("timestamping/enabled".to_owned(), Value::from(false))])
5620                    .collect(),
5621            );
5622            check_transport(&p, &stated, None)
5623                .into_iter()
5624                .map(|f| (f.code.as_str(), f.at))
5625                .collect()
5626        };
5627        let at = || "transport.wait_before_close_ms".to_owned();
5628        let differs = || ("transport_differs", at());
5629        let under = || ("wait_under_lease", at());
5630        assert_eq!(found(&[(wbc, Value::from(10_000_000u64))]), []);
5631        assert_eq!(found(&[(wbc, Value::from(u64::MAX))]), [differs()]);
5632        assert_eq!(found(&[(wbc, Value::from(-1i64))]), [differs(), under()]);
5633        assert_eq!(found(&[(wbc, Value::from("10000000"))]), [differs()]);
5634        assert_eq!(found(&[(wbc, Value::from(1.0e7))]), [differs()]);
5635        assert_eq!(
5636            found(&[
5637                (lease, Value::from("10000")),
5638                (wbc, Value::from(10_000_000u64))
5639            ]),
5640            [("transport_differs", "transport.lease_ms".to_owned())]
5641        );
5642    }
5643
5644    /// A `null` among the eight keys (v2 §2.19, 0.18): left out at
5645    /// `routing/interests/timeout`, which zenoh fills with its default, so
5646    /// the key is not stated and reads at the binding's; a value stated,
5647    /// and none zenoh runs, at each of the seven other keys.
5648    #[test]
5649    fn a_null_reads_as_left_out_at_the_interests_timeout_alone() {
5650        let policy = |interests_ms: u64| {
5651            parse(&format!(
5652                "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
5653                 binding = \"zenoh-1.10.1\"\n[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
5654                 wait_before_close_ms = 10000\nsequence = \"32bit\"\n\
5655                 interests_timeout_ms = {interests_ms}\n[face.rf]\n\
5656                 far = \"ground\"\nattach = \"client\"\n\
5657                 select = {{ link_protocols = [\"unixsock-stream\"] }}\nclass = \"constrained\"\n\
5658                 expose = \"none\"\nmax_outage_s = 3600\nlink_bps = 1000000\nloss_ppm = 0\n\
5659                 arq = true\nreply_timeout_ms = 15000\n"
5660            ))
5661            .policy
5662            .expect("a policy")
5663        };
5664        // The router's file, read from its tree: every key the policy's but
5665        // the one written `null`, and no stamp.
5666        let router = |null_at: TransportKey| {
5667            let mut tree = serde_json::json!({
5668                "transport": {
5669                    "link": {"tx": {
5670                        "lease": 10_000, "keep_alive": 4, "batch_size": 65_535,
5671                        "sequence_number_resolution": "32bit",
5672                        "queue": {"congestion_control": {"block": {
5673                            "wait_before_close": 10_000_000,
5674                        }}},
5675                    }},
5676                    "unicast": {"open_timeout": 10_000, "accept_timeout": 10_000},
5677                },
5678                "routing": {"interests": {"timeout": 10_000}},
5679                "timestamping": {"enabled": false},
5680            });
5681            let mut node = &mut tree;
5682            for part in null_at.path().split('/') {
5683                node = node.get_mut(part).expect("the path");
5684            }
5685            *node = Value::Null;
5686            StatedTransport::read(&tree)
5687        };
5688        let found = |p: &FacePolicy, r: &StatedTransport| -> Vec<(&'static str, String)> {
5689            check_transport(p, r, None)
5690                .into_iter()
5691                .map(|f| (f.code.as_str(), f.at))
5692                .collect()
5693        };
5694        let defaults = Binding::Zenoh1_10_1.defaults();
5695        let interests = TransportKey::InterestsTimeout;
5696
5697        // At the interests timeout: kept as written, not stated, the default.
5698        let r = router(interests);
5699        assert_eq!(r.0.get(interests.path()), Some(&Value::Null));
5700        assert!(r.null_left_out(interests));
5701        assert!(!r.states(interests));
5702        assert_eq!(r.runs(interests, &defaults), Value::from(10_000u64));
5703        // Under a policy at the default it is the policy's: no finding.
5704        assert_eq!(found(&policy(10_000), &r), []);
5705        // Under another it is the default, not the policy's.
5706        assert_eq!(
5707            found(&policy(40_000), &r),
5708            [("transport_differs", interests.at())]
5709        );
5710        // The fork's default there is the same, so it reads alike.
5711        assert_eq!(
5712            r.runs(interests, &Binding::Zm1_10_2R1.defaults()),
5713            Value::from(10_000u64)
5714        );
5715
5716        // At each other key: a value stated, which is no value zenoh runs.
5717        for key in TransportKey::ALL {
5718            if key == interests {
5719                continue;
5720            }
5721            let r = router(key);
5722            assert!(!r.null_left_out(key), "{}", key.key());
5723            assert!(r.states(key), "{}", key.key());
5724            assert_eq!(r.runs(key, &defaults), Value::Null, "{}", key.key());
5725            // `wait_under_lease` has no integer to read, and skips it.
5726            assert_eq!(
5727                found(&policy(10_000), &r),
5728                [("transport_differs", key.at())],
5729                "{}",
5730                key.key()
5731            );
5732        }
5733
5734        // Left out and `null` read alike, as a file that omits the key.
5735        let omitted = StatedTransport::default();
5736        assert!(!omitted.states(interests) && !omitted.null_left_out(interests));
5737        assert_eq!(
5738            omitted.runs(interests, &defaults),
5739            r.runs(interests, &defaults)
5740        );
5741    }
5742
5743    /// A router's timestamping read at its mode (v2 §2.19, core §4.1):
5744    /// a boolean whatever the mode, a value per mode, or zenoh 1.10.1's
5745    /// default where neither is stated, on for a router only; no mode is
5746    /// zenohd's `router`.
5747    #[test]
5748    fn a_routers_timestamping_is_read_at_its_mode() {
5749        let stamps = |mode: Option<&str>, enabled: Option<Value>| {
5750            let mut m = BTreeMap::new();
5751            if let Some(mode) = mode {
5752                m.insert("mode".to_owned(), Value::from(mode));
5753            }
5754            if let Some(e) = enabled {
5755                m.insert("timestamping/enabled".to_owned(), e);
5756            }
5757            StatedTransport(m).stamps()
5758        };
5759        assert!(stamps(None, None), "zenohd's router stamps by default");
5760        assert!(stamps(Some("router"), None));
5761        assert!(!stamps(Some("peer"), None));
5762        assert!(!stamps(Some("client"), None));
5763        assert!(stamps(Some("peer"), Some(Value::from(true))));
5764        assert!(!stamps(Some("router"), Some(Value::from(false))));
5765        let off = serde_json::json!({"router": false, "peer": false});
5766        assert!(!stamps(None, Some(off.clone())));
5767        assert!(!stamps(Some("peer"), Some(off)));
5768        // A per-mode value that leaves the router's mode out is its default.
5769        assert!(stamps(
5770            Some("router"),
5771            Some(serde_json::json!({"peer": false}))
5772        ));
5773        assert!(stamps(
5774            Some("peer"),
5775            Some(serde_json::json!({"peer": true}))
5776        ));
5777        // The generator's posture, read back: a router that stamps nothing.
5778        let written = StatedTransport::read(&serde_json::json!({
5779            "mode": "router",
5780            "timestamping": {"enabled": {"router": false, "peer": false}},
5781        }));
5782        assert!(!written.stamps());
5783        assert_eq!(TIMESTAMPING_OFF.len(), 2);
5784        // Both its paths, each off, whatever the order.
5785        for path in ["timestamping/enabled/router", "timestamping/enabled/peer"] {
5786            assert!(
5787                TIMESTAMPING_OFF.contains(&(path, false)),
5788                "{path} in {TIMESTAMPING_OFF:?}"
5789            );
5790        }
5791        // A `null`, as zenoh reads it: left out, at the mode's default.
5792        assert!(stamps(Some("router"), Some(serde_json::Value::Null)));
5793        assert!(stamps(
5794            Some("router"),
5795            Some(serde_json::json!({"router": null, "peer": false}))
5796        ));
5797        assert!(!stamps(
5798            Some("peer"),
5799            Some(serde_json::json!({"router": false, "peer": null}))
5800        ));
5801        let null_mode = StatedTransport::read(&serde_json::json!({
5802            "mode": null,
5803            "timestamping": {"enabled": {"peer": false}},
5804        }));
5805        assert!(null_mode.stamps(), "a `null` mode runs as a router");
5806        // A `mode` zenoh refuses, a string that is none of its three or no
5807        // string, reads as `router` too (link.v2 0.22 §2.19): never a mode
5808        // of its own, off by default and with no entry per mode.
5809        for refused in [
5810            serde_json::json!("bogus"),
5811            serde_json::json!("Router"),
5812            serde_json::json!(5),
5813        ] {
5814            let read = |enabled: Option<Value>| {
5815                let mut m = BTreeMap::from([("mode".to_owned(), refused.clone())]);
5816                if let Some(e) = enabled {
5817                    m.insert("timestamping/enabled".to_owned(), e);
5818                }
5819                StatedTransport(m).stamps()
5820            };
5821            assert!(read(None), "{refused}: a router's default, on");
5822            assert!(
5823                read(Some(serde_json::json!({"peer": false}))),
5824                "{refused}: the router's value left out"
5825            );
5826            assert!(
5827                !read(Some(serde_json::json!({"router": false, "peer": false}))),
5828                "{refused}: off at the mode read"
5829            );
5830            assert!(!read(Some(Value::from(false))), "{refused}");
5831            // Its own name is no mode `timestamping/enabled` is read at.
5832            assert!(
5833                read(Some(serde_json::json!({"bogus": false, "5": false}))),
5834                "{refused}"
5835            );
5836        }
5837    }
5838
5839    /// The keep-alive interval in words: exact, or "about" where the lease
5840    /// is no multiple of `keep_alive`.
5841    #[test]
5842    fn the_keep_alive_interval_says_when_it_rounds() {
5843        let t = |lease_ms, keep_alive| Transport {
5844            lease_ms,
5845            keep_alive,
5846            ..Binding::Zenoh1_10_1.defaults()
5847        };
5848        assert_eq!(t(240_000, 4).keep_alive_interval_words(), "60000 ms");
5849        assert_eq!(t(2_000, 3).keep_alive_interval_words(), "about 666 ms");
5850    }
5851
5852    /// A put's allowance is the bound measured on rf0's face (link.v1 §2.8,
5853    /// #1136; `docs/zk2/measurements/wire-baseline/results/bound-*`): on
5854    /// `unixsock-stream` at a 222-byte batch, the largest payload in one
5855    /// batch at 16 and 32 bits, by QoS, and one byte more fragmented.
5856    #[test]
5857    fn a_puts_allowance_is_the_measured_bound() {
5858        let lane = ["unixsock-stream".to_owned()];
5859        let block = PutQos {
5860            block: true,
5861            ..PutQos::DATA_DROP
5862        };
5863        let express = PutQos {
5864            express: true,
5865            ..PutQos::DATA_DROP
5866        };
5867        let low = PutQos {
5868            priority_data: false,
5869            ..PutQos::DATA_DROP
5870        };
5871        for (qos, bit16, bit32) in [
5872            (PutQos::DATA_DROP, 212, 210),
5873            (block, 210, 208),
5874            (express, 210, 208),
5875            (low, 208, 206),
5876        ] {
5877            for (sequence, largest) in [(Sequence::Bit16, bit16), (Sequence::Bit32, bit32)] {
5878                assert!(
5879                    fits_batch(largest, 222, qos, sequence, &lane),
5880                    "{qos:?} {sequence:?}"
5881                );
5882                assert!(!fits_batch(largest + 1, 222, qos, sequence, &lane));
5883            }
5884        }
5885        // A payload under 128 bytes has a 1-byte length; a datagram link
5886        // spends nothing on the batch's length; 8 and 64 bits.
5887        assert_eq!(allowance(100, PutQos::DATA_DROP, Sequence::Bit16, &lane), 9);
5888        assert_eq!(
5889            allowance(16_384, PutQos::DATA_DROP, Sequence::Bit16, &lane),
5890            11
5891        );
5892        let serial = ["serial".to_owned(), "ws".to_owned()];
5893        assert_eq!(
5894            allowance(200, PutQos::DATA_DROP, Sequence::Bit16, &serial),
5895            8
5896        );
5897        let mixed = ["serial".to_owned(), "udp".to_owned()];
5898        assert_eq!(
5899            allowance(200, PutQos::DATA_DROP, Sequence::Bit16, &mixed),
5900            10
5901        );
5902        assert_eq!(allowance(200, PutQos::DATA_DROP, Sequence::Bit8, &lane), 9);
5903        assert_eq!(
5904            allowance(200, PutQos::DATA_DROP, Sequence::Bit64, &lane),
5905            13
5906        );
5907    }
5908
5909    /// The window and the handshake's air (v2 §2.16): RF's 324 full
5910    /// batches a lease fit 16 bits' window and not 8 bits'.
5911    #[test]
5912    fn the_sequence_window_and_the_handshake_are_integer_arithmetic() {
5913        assert!(!window_filled(Sequence::Bit16, 222, 240_000, 2_400));
5914        assert!(window_filled(Sequence::Bit8, 222, 240_000, 2_400));
5915        assert!(under_handshake(10_000, 293));
5916        assert!(!under_handshake(40_000, 293));
5917        assert!(!under_handshake(2_560, 2_400));
5918        assert!(under_handshake(2_559, 2_400));
5919        assert!(!reply_short(15_000, 2_400, 222));
5920        assert!(reply_short(11_000, 2_400, 222));
5921    }
5922
5923    /// An empty `link_protocols`, which zenoh 1.10.1 refuses to load, is
5924    /// read as absent: the subject selects every link protocol (§2.15,
5925    /// 0.4).
5926    #[test]
5927    fn an_empty_link_protocol_list_reads_as_absent() {
5928        let radio = face("ground", &["unixsock-stream"]);
5929        let block = |links: Option<Vec<String>>| BlockSubjects {
5930            posture: Posture::Deny,
5931            subjects: vec![BlockSubject {
5932                id: "local".into(),
5933                usernames: vec!["local".into()],
5934                link_protocols: links,
5935                ..BlockSubject::default()
5936            }],
5937            policies: vec![BlockPolicy {
5938                subjects: vec!["local".into()],
5939            }],
5940        };
5941        let found = |links| check_subjects("radio", &radio, &block(links));
5942        assert_eq!(found(Some(Vec::new())), found(None));
5943        assert_eq!(found(None).len(), 1);
5944    }
5945
5946    #[test]
5947    fn the_batch_against_the_lease_is_integer_arithmetic() {
5948        assert!(within_lease(1000, 2400, 10_000));
5949        assert!(!within_lease(1024, 2400, 10_000));
5950        assert!(within_lease(65_535, MAX_U32, MAX_U32));
5951    }
5952
5953    /// The far side of a link.v2 face (v2 §2.20, §2.21): its reply timeout
5954    /// raises a shorter one, never a longer one; a face without ARQ
5955    /// re-declares; its session runs the eight `[transport]` keys; a
5956    /// `link.v1` policy and a face the policy does not name are refused.
5957    #[test]
5958    fn a_far_side_reads_its_face_of_a_link_v2_policy() {
5959        use std::time::Duration;
5960        let text = "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
5961                    binding = \"zenoh-1.10.1\"\n\
5962                    [transport]\nlease_ms = 240000\nkeep_alive = 4\n\
5963                    wait_before_close_ms = 240000\nsequence = \"16bit\"\nbatch_bytes = 222\n\
5964                    [face.rf]\nfar = \"ground\"\nattach = \"client\"\n\
5965                    select = { link_protocols = [\"unixsock-stream\"] }\n\
5966                    class = \"constrained\"\nexpose = \"none\"\nmax_outage_s = 3600\n\
5967                    link_bps = 2400\nloss_ppm = 50000\narq = false\nreply_timeout_ms = 15000\n";
5968        let parsed = parse(text);
5969        let policy = parsed.policy.expect("a policy");
5970        let far = policy.far_side("rf").expect("its face");
5971        assert_eq!(far.reply_timeout(), Duration::from_secs(15));
5972        assert_eq!(
5973            far.at_least(Duration::from_secs(1)),
5974            Duration::from_secs(15)
5975        );
5976        assert_eq!(
5977            far.at_least(Duration::from_secs(30)),
5978            Duration::from_secs(30)
5979        );
5980        assert!(
5981            far.redeclares(),
5982            "no ARQ: a silent subscription is declared again"
5983        );
5984        assert_eq!(
5985            FarSide::silence(Duration::from_secs(300)),
5986            Duration::from_secs(600)
5987        );
5988        let keys = far.session_keys();
5989        assert_eq!(keys.len(), 8);
5990        assert_eq!(
5991            keys[2],
5992            (TransportKey::WaitBeforeClose, Value::from(240_000_000u64)),
5993            "wait_before_close in µs"
5994        );
5995        assert!(matches!(
5996            policy.far_side("sbd"),
5997            Err(FarSideRefusal::NoFace { faces, .. }) if faces == ["rf"]
5998        ));
5999        let v1 = FacePolicy {
6000            profile: Profile::V1,
6001            transport: None,
6002            ..policy
6003        };
6004        assert_eq!(v1.far_side("rf"), Err(FarSideRefusal::NotV2));
6005    }
6006}