use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use serde::Serialize;
use serde_json::Value;
use zenoh_keyexpr::keyexpr;
use crate::authoring::Kind;
use crate::chunk::is_plain_chunk;
use crate::contract::{Contract, Resource};
use crate::freshness::{self, Horizon};
use crate::grammar::KindToken;
use crate::template::{Segment, Template};
pub const PROFILE: &str = "link.v1";
const ARCHIVE: &str = "archive.v1";
pub const NAME: &str = "link";
pub const EXPOSURE: &str = "link.exposure";
pub const VOCABULARY: &[&str] = &["exposure"];
pub const PROFILE_V2: &str = "link.v2";
#[must_use]
pub fn uses_v2(c: &Contract) -> bool {
c.uses.iter().any(|u| u.to_string() == PROFILE_V2)
}
pub const ENVELOPE_BYTES: u64 = 8;
pub const DEFAULT_LEASE_MS: u64 = 10_000;
pub const DEFAULT_WINDOW_S: u64 = 60;
const STOCK_PROTOCOLS: &[&str] = &[
"tcp",
"udp",
"tls",
"quic",
"serial",
"unixpipe",
"unixsock-stream",
"vsock",
"ws",
];
const ZM_1_10_2_R1_PROTOCOLS: &[&str] = &[
"tcp",
"udp",
"tls",
"quic",
"serial",
"unixpipe",
"unixsock-stream",
"unixsock-dgram",
"vsock",
"ws",
];
pub const MESSAGES: [&str; 9] = [
"put",
"delete",
"declare_subscriber",
"query",
"declare_queryable",
"reply",
"liveliness_token",
"declare_liveliness_subscriber",
"liveliness_query",
];
pub const PUSH_MESSAGES: [&str; 3] = ["put", "delete", "declare_subscriber"];
pub const FLOWS: [&str; 2] = ["egress", "ingress"];
pub const ZK_DENY: &str = "zk2/**/@zk/**";
pub const ADV_DENY: &str = "zk2/**/@adv/**";
pub const ADMIN_DENY: &str = "@/**";
pub const PUSH_TOKENS: [KindToken; 5] = [
KindToken::Stream,
KindToken::ExplicitStream,
KindToken::State,
KindToken::ExplicitState,
KindToken::Events,
];
const MAX_U32: u64 = u32::MAX as u64;
const MAX_BATCH: u64 = 65_535;
const MAX_REGION: usize = 32;
const MAX_KEEP_ALIVE: u64 = 255;
const MAX_LOSS_PPM: u64 = 1_000_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Profile {
#[default]
V1,
V2,
}
impl Profile {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::V1 => PROFILE,
Self::V2 => PROFILE_V2,
}
}
}
const FORK_RELEASE: &str = "zm-1.10.2-r";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Binding {
#[default]
Zenoh1_10_1,
Zenoh1_10_2,
Zm1_10_2R1,
}
impl Binding {
pub const ALL: [Binding; 3] = [
Binding::Zenoh1_10_1,
Binding::Zenoh1_10_2,
Binding::Zm1_10_2R1,
];
pub const NAMES: [&'static str; Binding::ALL.len()] = {
let mut names = [""; Binding::ALL.len()];
let mut i = 0;
while i < names.len() {
names[i] = Binding::ALL[i].as_str();
i += 1;
}
names
};
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Zenoh1_10_1 => "zenoh-1.10.1",
Self::Zenoh1_10_2 => "zenoh-1.10.2",
Self::Zm1_10_2R1 => "zm-1.10.2-r1",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Binding> {
Self::ALL.into_iter().find(|b| b.as_str() == s).or_else(|| {
let n = s.strip_prefix(FORK_RELEASE)?;
(!n.is_empty() && !n.starts_with('0') && n.bytes().all(|b| b.is_ascii_digit()))
.then_some(Binding::Zm1_10_2R1)
})
}
#[must_use]
pub fn protocols(self) -> &'static [&'static str] {
match self {
Self::Zenoh1_10_1 | Self::Zenoh1_10_2 => STOCK_PROTOCOLS,
Self::Zm1_10_2R1 => ZM_1_10_2_R1_PROTOCOLS,
}
}
#[must_use]
pub fn defaults(self) -> Transport {
Transport {
lease_ms: 10_000,
keep_alive: 4,
wait_before_close_ms: match self {
Self::Zenoh1_10_1 | Self::Zenoh1_10_2 => 5_000,
Self::Zm1_10_2R1 => 10_000,
},
sequence: Sequence::Bit32,
batch_bytes: MAX_BATCH,
open_timeout_ms: DEFAULT_TIMEOUT_MS,
accept_timeout_ms: DEFAULT_TIMEOUT_MS,
interests_timeout_ms: DEFAULT_TIMEOUT_MS,
}
}
}
impl fmt::Display for Binding {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl Serialize for Binding {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownBinding(pub String);
impl fmt::Display for UnknownBinding {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"not a binding; one of: {}, or {FORK_RELEASE}<n> for a later release of the fork",
Binding::NAMES.join(", ")
)
}
}
impl std::error::Error for UnknownBinding {}
impl std::str::FromStr for Binding {
type Err = UnknownBinding;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Binding::parse(s).ok_or_else(|| UnknownBinding(s.to_owned()))
}
}
impl<'de> serde::Deserialize<'de> for Binding {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let name = String::deserialize(d)?;
Binding::parse(&name)
.ok_or_else(|| serde::de::Error::unknown_variant(&name, &Binding::NAMES))
}
}
pub const DEFAULT_TIMEOUT_MS: u64 = 10_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Sequence {
Bit8,
Bit16,
Bit32,
Bit64,
}
impl Sequence {
pub const ALL: [Sequence; 4] = [
Sequence::Bit8,
Sequence::Bit16,
Sequence::Bit32,
Sequence::Bit64,
];
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Bit8 => "8bit",
Self::Bit16 => "16bit",
Self::Bit32 => "32bit",
Self::Bit64 => "64bit",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Sequence> {
Self::ALL.into_iter().find(|q| q.as_str() == s)
}
#[must_use]
pub fn window(self) -> u64 {
match self {
Self::Bit8 => 1 << 6,
Self::Bit16 => 1 << 13,
Self::Bit32 => 1 << 27,
Self::Bit64 => 1 << 31,
}
}
#[must_use]
pub fn max_bytes(self) -> u64 {
match self {
Self::Bit8 => 1,
Self::Bit16 => 2,
Self::Bit32 => 4,
Self::Bit64 => 5,
}
}
}
pub const UNSTREAMED_PROTOCOLS: [&str; 3] = ["serial", "ws", "unixsock-dgram"];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PutQos {
pub block: bool,
pub priority_data: bool,
pub express: bool,
}
impl PutQos {
pub const DATA_DROP: PutQos = PutQos {
block: false,
priority_data: true,
express: false,
};
}
#[must_use]
pub fn allowance(payload: u64, qos: PutQos, sequence: Sequence, protocols: &[String]) -> u64 {
let length = match payload {
0..128 => 1,
128..16_384 => 2,
_ => 3,
};
let push_qos = if qos.priority_data && !qos.block && !qos.express {
0
} else {
2
};
let frame_qos = if qos.priority_data { 0 } else { 2 };
let batch_length = if protocols
.iter()
.all(|p| UNSTREAMED_PROTOCOLS.contains(&p.as_str()))
{
0
} else {
2
};
3 + length + push_qos + 1 + sequence.max_bytes() + frame_qos + batch_length
}
#[must_use]
pub fn fits_batch(
payload: u64,
batch_bytes: u64,
qos: PutQos,
sequence: Sequence,
protocols: &[String],
) -> bool {
u128::from(payload) + u128::from(allowance(payload, qos, sequence, protocols))
<= u128::from(batch_bytes)
}
impl Serialize for Sequence {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Transport {
pub lease_ms: u64,
pub keep_alive: u64,
pub wait_before_close_ms: u64,
pub sequence: Sequence,
pub batch_bytes: u64,
pub open_timeout_ms: u64,
pub accept_timeout_ms: u64,
pub interests_timeout_ms: u64,
}
impl Transport {
#[must_use]
pub fn value(&self, key: TransportKey) -> Value {
match key {
TransportKey::Lease => Value::from(self.lease_ms),
TransportKey::KeepAlive => Value::from(self.keep_alive),
TransportKey::WaitBeforeClose => Value::from(self.wait_before_close_ms * 1_000),
TransportKey::Sequence => Value::from(self.sequence.as_str()),
TransportKey::BatchBytes => Value::from(self.batch_bytes),
TransportKey::OpenTimeout => Value::from(self.open_timeout_ms),
TransportKey::AcceptTimeout => Value::from(self.accept_timeout_ms),
TransportKey::InterestsTimeout => Value::from(self.interests_timeout_ms),
}
}
#[must_use]
pub fn keep_alive_interval_ms(&self) -> u64 {
self.lease_ms / self.keep_alive.max(1)
}
#[must_use]
pub fn keep_alive_interval_words(&self) -> String {
let exact = self.lease_ms.is_multiple_of(self.keep_alive.max(1));
format!(
"{}{} ms",
if exact { "" } else { "about " },
self.keep_alive_interval_ms()
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum TransportKey {
Lease,
KeepAlive,
WaitBeforeClose,
Sequence,
BatchBytes,
OpenTimeout,
AcceptTimeout,
InterestsTimeout,
}
impl TransportKey {
pub const ALL: [TransportKey; 8] = [
TransportKey::Lease,
TransportKey::KeepAlive,
TransportKey::WaitBeforeClose,
TransportKey::Sequence,
TransportKey::BatchBytes,
TransportKey::OpenTimeout,
TransportKey::AcceptTimeout,
TransportKey::InterestsTimeout,
];
#[must_use]
pub fn key(self) -> &'static str {
match self {
Self::Lease => "lease_ms",
Self::KeepAlive => "keep_alive",
Self::WaitBeforeClose => "wait_before_close_ms",
Self::Sequence => "sequence",
Self::BatchBytes => "batch_bytes",
Self::OpenTimeout => "open_timeout_ms",
Self::AcceptTimeout => "accept_timeout_ms",
Self::InterestsTimeout => "interests_timeout_ms",
}
}
#[must_use]
pub fn at(self) -> String {
format!("transport.{}", self.key())
}
#[must_use]
pub fn path(self) -> &'static str {
match self {
Self::Lease => "transport/link/tx/lease",
Self::KeepAlive => "transport/link/tx/keep_alive",
Self::WaitBeforeClose => {
"transport/link/tx/queue/congestion_control/block/wait_before_close"
}
Self::Sequence => "transport/link/tx/sequence_number_resolution",
Self::BatchBytes => "transport/link/tx/batch_size",
Self::OpenTimeout => "transport/unicast/open_timeout",
Self::AcceptTimeout => "transport/unicast/accept_timeout",
Self::InterestsTimeout => "routing/interests/timeout",
}
}
#[must_use]
pub fn of_path(path: &str) -> Option<TransportKey> {
Self::ALL.into_iter().find(|k| k.path() == path)
}
}
pub const TIMESTAMPING_OFF: [(&str, bool); 2] = [
("timestamping/enabled/router", false),
("timestamping/enabled/peer", false),
];
pub const POSTURE_PATHS: [&str; 2] = ["mode", "timestamping/enabled"];
const MODES: [&str; 3] = ["router", "peer", "client"];
#[derive(Debug, Clone, Default, PartialEq)]
pub struct StatedTransport(pub BTreeMap<String, Value>);
impl StatedTransport {
#[must_use]
pub fn read(config: &Value) -> StatedTransport {
let mut out = BTreeMap::new();
let paths = TransportKey::ALL
.into_iter()
.map(TransportKey::path)
.chain(POSTURE_PATHS);
for path in paths {
let v = path
.split('/')
.try_fold(config, |node, part| node.get(part));
if let Some(v) = v {
out.insert(path.to_owned(), v.clone());
}
}
StatedTransport(out)
}
#[must_use]
pub fn stamps(&self) -> bool {
let mode = match self.0.get("mode") {
Some(Value::String(mode)) if MODES.contains(&mode.as_str()) => mode.as_str(),
_ => "router",
};
let default = mode == "router";
let read = |value: Option<&Value>| match value {
Some(Value::Bool(b)) => *b,
_ => default,
};
match self.0.get("timestamping/enabled") {
Some(Value::Object(per_mode)) => read(per_mode.get(mode)),
value => read(value),
}
}
#[must_use]
pub fn null_left_out(&self, key: TransportKey) -> bool {
key == TransportKey::InterestsTimeout && matches!(self.0.get(key.path()), Some(Value::Null))
}
fn stated(&self, key: TransportKey) -> Option<&Value> {
self.0.get(key.path()).filter(|_| !self.null_left_out(key))
}
#[must_use]
pub fn states(&self, key: TransportKey) -> bool {
self.stated(key).is_some()
}
#[must_use]
pub fn runs(&self, key: TransportKey, defaults: &Transport) -> Value {
self.stated(key)
.cloned()
.unwrap_or_else(|| defaults.value(key))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Exposure {
Host,
Link,
Invalid(String),
Ignored,
}
impl Exposure {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Host => "host",
Self::Link => "link",
Self::Invalid(_) => "invalid",
Self::Ignored => "ignored",
}
}
}
#[must_use]
pub fn exposure(kind: Kind, annotations: &BTreeMap<String, Value>) -> Exposure {
if kind == Kind::Operation {
return Exposure::Ignored;
}
match annotations.get(EXPOSURE) {
None => Exposure::Host,
Some(Value::String(s)) if s == "host" => Exposure::Host,
Some(Value::String(s)) if s == "link" => Exposure::Link,
Some(v) => Exposure::Invalid(v.to_string()),
}
}
#[must_use]
pub fn exposure_of(r: &Resource) -> Exposure {
exposure(r.kind, &r.annotations)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Expose {
Link,
None,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pushes {
Downsampled,
Whole,
Denied,
None,
}
impl Pushes {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Downsampled => "downsampled",
Self::Whole => "whole",
Self::Denied => "denied",
Self::None => "none",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reason {
RequestsOnly,
Invalid,
Host,
FaceClosed,
Templated,
Unlisted,
Timed,
Exposed,
}
impl Reason {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::RequestsOnly => "requests_only",
Self::Invalid => "invalid",
Self::Host => "host",
Self::FaceClosed => "face_closed",
Self::Templated => "templated",
Self::Unlisted => "unlisted",
Self::Timed => "timed",
Self::Exposed => "exposed",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Crossing {
pub pushes: Pushes,
pub reason: Reason,
}
impl Crossing {
#[must_use]
pub fn crosses(self) -> bool {
matches!(self.pushes, Pushes::Downsampled | Pushes::Whole)
}
}
#[must_use]
pub fn crossing(
token: KindToken,
templated: bool,
exposure: &Exposure,
expose: Expose,
) -> Crossing {
let denied = |reason| Crossing {
pushes: Pushes::Denied,
reason,
};
if token == KindToken::Op {
return Crossing {
pushes: Pushes::None,
reason: Reason::RequestsOnly,
};
}
match exposure {
Exposure::Ignored => Crossing {
pushes: Pushes::None,
reason: Reason::RequestsOnly,
},
Exposure::Invalid(_) => denied(Reason::Invalid),
Exposure::Host => denied(Reason::Host),
Exposure::Link if expose == Expose::None => denied(Reason::FaceClosed),
Exposure::Link if is_stream(token) && templated => denied(Reason::Templated),
Exposure::Link if is_stream(token) => Crossing {
pushes: Pushes::Downsampled,
reason: Reason::Exposed,
},
Exposure::Link => Crossing {
pushes: Pushes::Whole,
reason: Reason::Exposed,
},
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Shape {
pub templated: bool,
pub frame: bool,
pub timed: bool,
}
impl Shape {
#[must_use]
pub fn of(
token: KindToken,
templated: bool,
frame: bool,
annotations: &BTreeMap<String, Value>,
) -> Self {
Shape {
templated,
frame,
timed: is_stream(token) && timed(annotations),
}
}
}
#[must_use]
pub fn timed(annotations: &BTreeMap<String, Value>) -> bool {
annotations.contains_key(crate::timing::DEADLINE_MS)
}
#[must_use]
pub fn crossing_v2(
token: KindToken,
shape: Shape,
exposure: &Exposure,
expose: Expose,
listed: Option<bool>,
) -> Crossing {
let c = crossing(token, shape.templated, exposure, expose);
let denied = |reason| Crossing {
pushes: Pushes::Denied,
reason,
};
if token == KindToken::Events && c.pushes == Pushes::Whole && listed == Some(false) {
return denied(Reason::Unlisted);
}
if c.pushes != Pushes::Downsampled {
return c;
}
if shape.frame {
if listed == Some(false) {
return denied(Reason::Unlisted);
}
return Crossing {
pushes: Pushes::Whole,
reason: Reason::Exposed,
};
}
if shape.timed {
return denied(Reason::Timed);
}
c
}
#[must_use]
pub fn packed_required(uses_v2: bool, token: KindToken, exposure: &Exposure, packed: bool) -> bool {
uses_v2 && token != KindToken::Op && *exposure == Exposure::Link && !packed
}
#[must_use]
pub fn contract_findings(c: &Contract) -> Vec<Finding> {
let v2 = uses_v2(c);
let mut out: Vec<Finding> = c
.resources
.iter()
.map(|r| Res::of(c, r))
.filter(|r| {
packed_required(
v2,
r.token,
&exposure(kind_of(r.token), &r.annotations),
r.packed,
)
})
.map(|r| {
Finding::new(
Code::PackedRequired,
None,
res_name(&c.iface.to_string(), &r),
)
})
.collect();
sort_findings(&mut out);
out
}
fn is_stream(token: KindToken) -> bool {
matches!(token, KindToken::Stream | KindToken::ExplicitStream)
}
fn is_state(token: KindToken) -> bool {
matches!(token, KindToken::State | KindToken::ExplicitState)
}
#[must_use]
pub fn kind_of(token: KindToken) -> Kind {
match token {
KindToken::Stream | KindToken::ExplicitStream => Kind::Stream,
KindToken::State | KindToken::ExplicitState => Kind::State,
KindToken::Events => Kind::Event,
KindToken::Op => Kind::Operation,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Code {
Toml,
UnknownField,
MissingField,
BadValue,
RouterAttach,
SelectInterfaces,
UnknownProtocol,
SharedProtocol,
BatchOverLease,
FarOfTwoFaces,
ServiceUnknown,
ContractUnknown,
TemplatedExposure,
CarveOutOverlap,
IntervalOverHorizon,
ExposureDisagrees,
FrameOverInterval,
FrameOverBatch,
HistoryOnFrame,
OwnerHeartbeatDenied,
WindowUnderOutage,
ZkNotDenied,
WildcardDownsampling,
IntersectingDownsampling,
BlockDisabled,
NearSubjectOnFace,
FaceSubjectMissing,
FaceSubjectBeyondFace,
FaceSubjectMisplaced,
NarrowedTooFar,
TransportMissing,
MovedField,
WaitUnderLease,
KeepAliveFlaps,
SequenceWindow,
OpenUnderHandshake,
ReplyTimeoutShort,
NoArq,
TransportDiffers,
PeerDiffers,
FaceTimestamping,
CatalogMismatch,
PackedRequired,
NotPacked,
FrameUnknown,
EventUnknown,
FrameUnlisted,
KeyframeUnreachable,
HorizonUnderFace,
BlockOverBatch,
KeepAliveNotSuppressed,
TimedDownsampled,
CatalogMissing,
DeviceListed,
PresenceRequired,
EpochOnDevice,
NearOpensUser,
NearOpensUnauthenticated,
}
impl Code {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Toml => "toml",
Self::UnknownField => "unknown_field",
Self::MissingField => "missing_field",
Self::BadValue => "bad_value",
Self::RouterAttach => "router_attach",
Self::SelectInterfaces => "select_interfaces",
Self::UnknownProtocol => "unknown_protocol",
Self::SharedProtocol => "shared_protocol",
Self::BatchOverLease => "batch_over_lease",
Self::FarOfTwoFaces => "far_of_two_faces",
Self::ServiceUnknown => "service_unknown",
Self::ContractUnknown => "contract_unknown",
Self::TemplatedExposure => "templated_exposure",
Self::CarveOutOverlap => "carve_out_overlap",
Self::IntervalOverHorizon => "interval_over_horizon",
Self::ExposureDisagrees => "exposure_disagrees",
Self::FrameOverInterval => "frame_over_interval",
Self::FrameOverBatch => "frame_over_batch",
Self::HistoryOnFrame => "history_on_frame",
Self::OwnerHeartbeatDenied => "owner_heartbeat_denied",
Self::WindowUnderOutage => "window_under_outage",
Self::ZkNotDenied => "zk_not_denied",
Self::WildcardDownsampling => "wildcard_downsampling",
Self::IntersectingDownsampling => "intersecting_downsampling",
Self::BlockDisabled => "block_disabled",
Self::NearSubjectOnFace => "near_subject_on_face",
Self::FaceSubjectMissing => "face_subject_missing",
Self::FaceSubjectBeyondFace => "face_subject_beyond_face",
Self::FaceSubjectMisplaced => "face_subject_misplaced",
Self::NarrowedTooFar => "narrowed_too_far",
Self::TransportMissing => "transport_missing",
Self::MovedField => "moved_field",
Self::WaitUnderLease => "wait_under_lease",
Self::KeepAliveFlaps => "keep_alive_flaps",
Self::SequenceWindow => "sequence_window",
Self::OpenUnderHandshake => "open_under_handshake",
Self::ReplyTimeoutShort => "reply_timeout_short",
Self::NoArq => "no_arq",
Self::TransportDiffers => "transport_differs",
Self::PeerDiffers => "peer_differs",
Self::FaceTimestamping => "face_timestamping",
Self::CatalogMismatch => "catalog_mismatch",
Self::PackedRequired => "packed_required",
Self::NotPacked => "not_packed",
Self::FrameUnknown => "frame_unknown",
Self::EventUnknown => "event_unknown",
Self::FrameUnlisted => "frame_unlisted",
Self::KeyframeUnreachable => "keyframe_unreachable",
Self::HorizonUnderFace => "horizon_under_face",
Self::BlockOverBatch => "block_over_batch",
Self::KeepAliveNotSuppressed => "keep_alive_not_suppressed",
Self::TimedDownsampled => "timed_downsampled",
Self::CatalogMissing => "catalog_missing",
Self::DeviceListed => "device_listed",
Self::PresenceRequired => "presence_required",
Self::EpochOnDevice => "epoch_on_device",
Self::NearOpensUser => "near_opens_user",
Self::NearOpensUnauthenticated => "near_opens_unauthenticated",
}
}
#[must_use]
pub fn severity(self) -> Severity {
match self {
Self::BatchOverLease
| Self::FarOfTwoFaces
| Self::TemplatedExposure
| Self::CarveOutOverlap
| Self::IntervalOverHorizon
| Self::ExposureDisagrees
| Self::FrameOverInterval
| Self::FrameOverBatch
| Self::HistoryOnFrame
| Self::OwnerHeartbeatDenied
| Self::KeepAliveFlaps
| Self::SequenceWindow
| Self::OpenUnderHandshake
| Self::ReplyTimeoutShort
| Self::NoArq
| Self::PeerDiffers
| Self::FaceTimestamping
| Self::NotPacked
| Self::FrameUnlisted
| Self::HorizonUnderFace
| Self::BlockOverBatch
| Self::KeepAliveNotSuppressed
| Self::TimedDownsampled
| Self::EpochOnDevice
| Self::NearOpensUnauthenticated => Severity::Warning,
_ => Severity::Error,
}
}
}
impl fmt::Display for Code {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl Serialize for Code {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Severity {
Error,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct Finding {
pub code: Code,
pub severity: Severity,
pub face: Option<String>,
pub at: String,
}
impl Finding {
#[must_use]
pub fn new(code: Code, face: Option<&str>, at: impl Into<String>) -> Self {
Finding {
code,
severity: code.severity(),
face: face.map(str::to_owned),
at: at.into(),
}
}
#[must_use]
pub fn is_error(&self) -> bool {
self.severity == Severity::Error
}
}
impl fmt::Display for Finding {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let sev = match self.severity {
Severity::Error => "error",
Severity::Warning => "warning",
};
match &self.face {
Some(face) => write!(f, "{sev} {} [face {face}] {}", self.code, self.at),
None => write!(f, "{sev} {} {}", self.code, self.at),
}
}
}
pub fn sort_findings(findings: &mut Vec<Finding>) {
findings.sort_by(|a, b| {
a.face
.cmp(&b.face)
.then_with(|| a.at.cmp(&b.at))
.then_with(|| a.code.as_str().cmp(b.code.as_str()))
});
findings.dedup();
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Attach {
Client,
SouthRegion { region: String },
Device { devices: Vec<String> },
}
impl Attach {
#[must_use]
pub fn devices(&self) -> &[String] {
match self {
Attach::Device { devices } => devices,
_ => &[],
}
}
#[must_use]
pub fn is_device(&self) -> bool {
matches!(self, Attach::Device { .. })
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Opens {
#[default]
Far,
Near,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Face {
pub far: String,
pub attach: Attach,
pub link_protocols: Vec<String>,
pub expose: Expose,
pub interval_s: Option<u64>,
pub max_outage_s: u64,
pub batch_bytes: u64,
pub link_bps: u64,
pub lease_ms: u64,
pub loss_ppm: Option<u64>,
pub arq: Option<bool>,
pub reply_timeout_ms: Option<u64>,
pub frames: Option<BTreeMap<String, FrameCadence>>,
pub events: Option<BTreeSet<String>>,
pub horizon_s: Option<u64>,
pub opens: Opens,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct FrameCadence {
pub every_s: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub keyframe_s: Option<u64>,
}
impl Face {
#[must_use]
pub fn batch_within_lease(&self) -> bool {
within_lease(self.batch_bytes, self.link_bps, self.lease_ms)
}
#[must_use]
pub fn freq(&self) -> Option<f64> {
self.interval_s
.map(|n| 1.0 / f64::from(u32::try_from(n).unwrap_or(u32::MAX)))
}
}
fn within_lease(batch_bytes: u64, link_bps: u64, lease_ms: u64) -> bool {
u128::from(batch_bytes) * 24_000 <= u128::from(lease_ms) * u128::from(link_bps)
}
fn flaps(lease_ms: u64, keep_alive: u64, loss_ppm: u64) -> bool {
use num_bigint::BigUint;
let n = u32::try_from(keep_alive.saturating_sub(1)).unwrap_or(u32::MAX);
let lhs = BigUint::from(172_800_000u64) * keep_alive * BigUint::from(loss_ppm).pow(n);
let rhs = BigUint::from(lease_ms) * BigUint::from(1_000_000u64).pow(n);
lhs > rhs
}
fn window_filled(sequence: Sequence, batch_bytes: u64, lease_ms: u64, link_bps: u64) -> bool {
u128::from(sequence.window()) * 8 * u128::from(batch_bytes) * 1_000
<= u128::from(lease_ms) * u128::from(link_bps)
}
fn under_handshake(timeout_ms: u64, link_bps: u64) -> bool {
u128::from(timeout_ms) * u128::from(link_bps) < 6_144_000
}
fn reply_short(reply_timeout_ms: u64, link_bps: u64, batch_bytes: u64) -> bool {
u128::from(reply_timeout_ms) * u128::from(link_bps) < 128_000 * u128::from(batch_bytes)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FacePolicy {
pub profile: Profile,
pub system: String,
pub services: Vec<String>,
pub faces: BTreeMap<String, Face>,
pub binding: Binding,
pub binding_name: String,
pub transport: Option<Transport>,
pub catalog: Option<String>,
}
impl FacePolicy {
#[must_use]
pub fn address(&self, service: &str) -> String {
format!("{}/{service}", self.system)
}
pub fn devices(&self) -> impl Iterator<Item = (&str, &str)> {
self.faces.iter().flat_map(|(name, f)| {
f.attach
.devices()
.iter()
.map(move |d| (name.as_str(), d.as_str()))
})
}
#[must_use]
pub fn device_face(&self, address: &str) -> Option<&str> {
debug_assert!(
self.devices().filter(|(_, d)| *d == address).count() <= 1,
"{address} on more than one device face: the linter's device_listed refuses it"
);
self.devices()
.find(|(_, d)| *d == address)
.map(|(name, _)| name)
}
#[must_use]
pub fn owners(&self) -> Vec<Owner<'_>> {
let mut out: Vec<Owner<'_>> = self
.services
.iter()
.map(|s| Owner {
address: self.address(s),
key: s.as_str(),
device_face: None,
})
.chain(self.devices().map(|(face, d)| Owner {
address: d.to_owned(),
key: d,
device_face: Some(face),
}))
.collect();
out.sort_by(|a, b| a.address.cmp(&b.address));
out
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Owner<'a> {
pub address: String,
pub key: &'a str,
pub device_face: Option<&'a str>,
}
impl FacePolicy {
pub fn far_side(&self, face: &str) -> Result<FarSide, FarSideRefusal> {
let (Profile::V2, Some(transport)) = (self.profile, self.transport) else {
return Err(FarSideRefusal::NotV2);
};
let Some(f) = self.faces.get(face) else {
return Err(FarSideRefusal::NoFace {
face: face.to_owned(),
faces: self.faces.keys().cloned().collect(),
});
};
let (Some(reply_timeout_ms), Some(arq)) = (f.reply_timeout_ms, f.arq) else {
return Err(FarSideRefusal::NotV2);
};
Ok(FarSide {
face: face.to_owned(),
reply_timeout_ms,
arq,
transport,
})
}
}
pub const SILENT_HORIZONS: u32 = 2;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FarSide {
pub face: String,
pub reply_timeout_ms: u64,
pub arq: bool,
pub transport: Transport,
}
impl FarSide {
#[must_use]
pub fn reply_timeout(&self) -> std::time::Duration {
std::time::Duration::from_millis(self.reply_timeout_ms)
}
#[must_use]
pub fn at_least(&self, timeout: std::time::Duration) -> std::time::Duration {
timeout.max(self.reply_timeout())
}
#[must_use]
pub fn redeclares(&self) -> bool {
!self.arq
}
#[must_use]
pub fn session_keys(&self) -> Vec<(TransportKey, Value)> {
TransportKey::ALL
.into_iter()
.map(|k| (k, self.transport.value(k)))
.collect()
}
#[must_use]
pub fn silence(horizon: std::time::Duration) -> std::time::Duration {
horizon.saturating_mul(SILENT_HORIZONS)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FarSideRefusal {
NotV2,
NoFace { face: String, faces: Vec<String> },
}
impl fmt::Display for FarSideRefusal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotV2 => f.write_str(
"a link.v1 policy states no reply timeout and no transport: a far side reads a \
link.v2 policy (link.v2 §2.20)",
),
Self::NoFace { face, faces } => write!(
f,
"the policy has no face {face:?}; its faces are {}",
faces.join(", ")
),
}
}
}
pub const REPAIRS: u32 = 3;
#[must_use]
pub fn repair_key(selector: &str, n: u32) -> Option<String> {
if n == 0 || n > REPAIRS {
return None;
}
let chunks: Vec<&str> = selector.split('/').collect();
let kind = (0..chunks.len()).find(|&z| {
chunks[z] == crate::grammar::GRAMMAR
&& z + 5 < chunks.len()
&& chunks[z + 3].parse::<crate::grammar::IfaceId>().is_ok()
&& chunks[z + 4].parse::<KindToken>().is_ok()
})? + 4;
let literal = chunks
.iter()
.position(|c| c.contains(['*', '$']))
.unwrap_or(chunks.len());
let at = literal.checked_sub(1).filter(|&i| i > kind)?;
if !is_plain_chunk(chunks[at]) {
return None;
}
let split = chunks[at].len().checked_sub(usize::try_from(n - 1).ok()?)?;
let chunk = format!("{}$*{}", &chunks[at][..split], &chunks[at][split..]);
let mut out = chunks.clone();
out[at] = &chunk;
let repair = out.join("/");
keyexpr::new(repair.as_str()).ok()?;
Some(repair)
}
#[must_use]
pub fn redeclare_horizon(c: &Contract, r: &Resource) -> Option<std::time::Duration> {
if matches!(r.kind, Kind::State) && freshness::uses_v2(c) {
return None;
}
freshness::horizon_of(r).ttl()
}
#[must_use]
pub fn redeclare_heartbeat_horizon(c: &Contract) -> Option<std::time::Duration> {
if !freshness::uses_v2(c) {
return None;
}
crate::heartbeat::Layout::of(c).horizon()
}
#[must_use]
pub fn redeclare_owner_heartbeat_horizon(
c: &Contract,
class: crate::heartbeat::Class,
) -> Option<std::time::Duration> {
if !freshness::uses_v2(c) {
return None;
}
crate::heartbeat::Layout::of(c).class_horizon(class)
}
#[derive(Debug, Clone)]
pub struct Parsed {
pub policy: Option<FacePolicy>,
pub findings: Vec<Finding>,
}
const TOP_KEYS_V1: &[&str] = &["system", "services", "face"];
const TOP_KEYS_V2: &[&str] = &[
"profile",
"system",
"services",
"binding",
"catalog",
"transport",
"face",
];
#[must_use]
pub fn parse(text: &str) -> Parsed {
let refuse = |f: Finding| Parsed {
policy: None,
findings: vec![f],
};
let table: toml::Table = match toml::from_str(text) {
Ok(t) => t,
Err(_) => return refuse(Finding::new(Code::Toml, None, "")),
};
if crate::toml10::first_beyond_toml10(text).is_some() {
return refuse(Finding::new(Code::Toml, None, ""));
}
let mut out = Vec::new();
let profile = match table.get("profile") {
None => Profile::V1,
Some(toml::Value::String(s)) if s == PROFILE_V2 => Profile::V2,
Some(_) => {
out.push(Finding::new(Code::BadValue, None, "profile"));
Profile::V2
}
};
let top = match profile {
Profile::V1 => TOP_KEYS_V1,
Profile::V2 => TOP_KEYS_V2,
};
for k in table.keys() {
if !top.contains(&k.as_str()) {
out.push(Finding::new(Code::UnknownField, None, k.clone()));
}
}
let system = match table.get("system") {
None => {
out.push(Finding::new(Code::MissingField, None, "system"));
None
}
Some(toml::Value::String(s)) if is_plain_chunk(s) => Some(s.clone()),
Some(_) => {
out.push(Finding::new(Code::BadValue, None, "system"));
None
}
};
let services = match table.get("services") {
None => {
out.push(Finding::new(Code::MissingField, None, "services"));
None
}
Some(v) => match plain_list(v) {
Some(l) => Some(l),
None => {
out.push(Finding::new(Code::BadValue, None, "services"));
None
}
},
};
let (binding, catalog, transport) = match profile {
Profile::V1 => (
Some((
Binding::Zenoh1_10_1,
Binding::Zenoh1_10_1.as_str().to_owned(),
)),
None,
None,
),
Profile::V2 => {
let binding = match table.get("binding") {
None => {
out.push(Finding::new(Code::MissingField, None, "binding"));
None
}
Some(toml::Value::String(s)) => {
let b = Binding::parse(s);
if b.is_none() {
out.push(Finding::new(Code::BadValue, None, "binding"));
}
b.map(|b| (b, s.clone()))
}
Some(_) => {
out.push(Finding::new(Code::BadValue, None, "binding"));
None
}
};
let catalog = match table.get("catalog") {
None => None,
Some(toml::Value::String(s)) if is_catalog_id(s) => Some(s.clone()),
Some(_) => {
out.push(Finding::new(Code::BadValue, None, "catalog"));
None
}
};
let transport = match table.get("transport") {
None => {
out.push(Finding::new(Code::TransportMissing, None, "transport"));
None
}
Some(toml::Value::Table(t)) => Some(parse_transport(t, &mut out)),
Some(_) => {
out.push(Finding::new(Code::BadValue, None, "transport"));
None
}
};
(binding, catalog, transport)
}
};
let ctx = FaceCtx {
profile,
protocols: binding.as_ref().map(|(b, _)| b.protocols()),
transport: transport.as_ref(),
};
let mut faces = BTreeMap::new();
match table.get("face") {
None => out.push(Finding::new(Code::MissingField, None, "face")),
Some(toml::Value::Table(t)) if t.is_empty() => {
out.push(Finding::new(Code::BadValue, None, "face"));
}
Some(toml::Value::Table(t)) => {
for (name, v) in t {
if !is_plain_chunk(name) {
out.push(Finding::new(Code::BadValue, Some(name), ""));
}
match v {
toml::Value::Table(ft) => {
if let Some(face) = parse_face(name, ft, &ctx, &mut out) {
faces.insert(name.clone(), face);
}
}
_ => out.push(Finding::new(Code::BadValue, Some(name), "")),
}
}
}
Some(_) => out.push(Finding::new(Code::BadValue, None, "face")),
}
if let Some(protocols) = ctx.protocols {
shared_protocols(&table, protocols, &mut out);
}
shared_far(&table, &mut out);
if profile == Profile::V2 {
device_listed(&table, system.as_deref(), services.as_deref(), &mut out);
}
sort_findings(&mut out);
let policy = if out.iter().any(Finding::is_error) {
None
} else {
Some(FacePolicy {
profile,
system: system.unwrap_or_default(),
services: services.unwrap_or_default(),
faces,
binding_name: binding.as_ref().map_or_else(
|| Binding::default().as_str().to_owned(),
|(_, n)| n.clone(),
),
binding: binding.map(|(b, _)| b).unwrap_or_default(),
transport: transport.as_ref().and_then(TransportDraft::complete),
catalog,
})
};
Parsed {
policy,
findings: out,
}
}
fn is_catalog_id(s: &str) -> bool {
s.len() == 8 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
#[derive(Debug, Clone, Default)]
struct TransportDraft {
lease_ms: Option<u64>,
keep_alive: Option<u64>,
wait_before_close_ms: Option<u64>,
sequence: Option<Sequence>,
batch_bytes: Option<u64>,
open_timeout_ms: Option<u64>,
accept_timeout_ms: Option<u64>,
interests_timeout_ms: Option<u64>,
}
impl TransportDraft {
fn complete(&self) -> Option<Transport> {
Some(Transport {
lease_ms: self.lease_ms?,
keep_alive: self.keep_alive?,
wait_before_close_ms: self.wait_before_close_ms?,
sequence: self.sequence?,
batch_bytes: self.batch_bytes?,
open_timeout_ms: self.open_timeout_ms?,
accept_timeout_ms: self.accept_timeout_ms?,
interests_timeout_ms: self.interests_timeout_ms?,
})
}
}
fn parse_transport(t: &toml::Table, out: &mut Vec<Finding>) -> TransportDraft {
let keys: Vec<&str> = TransportKey::ALL.iter().map(|k| k.key()).collect();
for k in t.keys() {
if !keys.contains(&k.as_str()) {
out.push(Finding::new(
Code::UnknownField,
None,
format!("transport.{k}"),
));
}
}
let mut int = |key: TransportKey, hi: u64, default: Option<u64>| match t.get(key.key()) {
None => {
if default.is_none() {
out.push(Finding::new(Code::MissingField, None, key.at()));
}
default
}
Some(v) => {
let n = int_in(v, 1, hi);
if n.is_none() {
out.push(Finding::new(Code::BadValue, None, key.at()));
}
n
}
};
let mut d = TransportDraft {
lease_ms: int(TransportKey::Lease, MAX_U32, None),
keep_alive: int(TransportKey::KeepAlive, MAX_KEEP_ALIVE, None),
wait_before_close_ms: int(TransportKey::WaitBeforeClose, MAX_U32, None),
sequence: None,
batch_bytes: int(TransportKey::BatchBytes, MAX_BATCH, Some(MAX_BATCH)),
open_timeout_ms: int(TransportKey::OpenTimeout, MAX_U32, Some(DEFAULT_TIMEOUT_MS)),
accept_timeout_ms: int(
TransportKey::AcceptTimeout,
MAX_U32,
Some(DEFAULT_TIMEOUT_MS),
),
interests_timeout_ms: int(
TransportKey::InterestsTimeout,
MAX_U32,
Some(DEFAULT_TIMEOUT_MS),
),
};
d.sequence = match t.get(TransportKey::Sequence.key()) {
None => {
out.push(Finding::new(
Code::MissingField,
None,
TransportKey::Sequence.at(),
));
None
}
Some(toml::Value::String(s)) => {
let q = Sequence::parse(s);
if q.is_none() {
out.push(Finding::new(
Code::BadValue,
None,
TransportKey::Sequence.at(),
));
}
q
}
Some(_) => {
out.push(Finding::new(
Code::BadValue,
None,
TransportKey::Sequence.at(),
));
None
}
};
if let (Some(lease), Some(wbc)) = (d.lease_ms, d.wait_before_close_ms)
&& wbc < lease
{
out.push(Finding::new(
Code::WaitUnderLease,
None,
TransportKey::WaitBeforeClose.at(),
));
}
d
}
fn plain_list(v: &toml::Value) -> Option<Vec<String>> {
let a = v.as_array()?;
let mut seen = BTreeSet::new();
let mut out = Vec::with_capacity(a.len());
for x in a {
let s = x.as_str().filter(|s| is_plain_chunk(s))?;
if !seen.insert(s) {
return None;
}
out.push(s.to_owned());
}
Some(out)
}
fn int_in(v: &toml::Value, lo: u64, hi: u64) -> Option<u64> {
let i = v.as_integer()?;
u64::try_from(i).ok().filter(|n| (lo..=hi).contains(n))
}
fn protocol_list(v: &toml::Value) -> Option<Vec<String>> {
let a = v.as_array()?;
if a.is_empty() {
return None;
}
let mut seen = BTreeSet::new();
let mut out = Vec::with_capacity(a.len());
for x in a {
let s = x.as_str()?;
if !seen.insert(s) {
return None;
}
out.push(s.to_owned());
}
Some(out)
}
const FACE_KEYS: &[&str] = &[
"far",
"attach",
"region",
"select",
"class",
"expose",
"interval_s",
"max_outage_s",
"batch_bytes",
"link_bps",
"lease_ms",
];
const FACE_KEYS_V2: &[&str] = &[
"far",
"attach",
"region",
"select",
"class",
"expose",
"interval_s",
"max_outage_s",
"link_bps",
"loss_ppm",
"arq",
"reply_timeout_ms",
"horizon_s",
"frames",
"events",
"devices",
"opens",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AttachKind {
Client,
South,
Device,
}
fn device_list(v: &toml::Value) -> Option<Vec<String>> {
let a = v.as_array()?;
if a.is_empty() {
return None;
}
let mut seen = BTreeSet::new();
for x in a {
let s = x.as_str()?;
let (system, service) = s.split_once('/')?;
if !is_plain_chunk(system) || !is_plain_chunk(service) || !seen.insert(s) {
return None;
}
}
Some(seen.into_iter().map(str::to_owned).collect())
}
fn parse_frames(
face: &str,
v: &toml::Value,
out: &mut Vec<Finding>,
) -> Option<BTreeMap<String, FrameCadence>> {
let at = Some(face);
let toml::Value::Table(t) = v else {
out.push(Finding::new(Code::BadValue, at, "frames"));
return None;
};
let mut ok = true;
let mut frames = BTreeMap::new();
for (k, v) in t {
let entry = format!("frames.{k}");
let mut bad = |out: &mut Vec<Finding>, code: Code, key: String| {
out.push(Finding::new(code, at, key));
ok = false;
};
let name = k.split_once('/').and_then(|(i, rest)| {
let iface: crate::grammar::IfaceId = i.parse().ok()?;
let template = Template::parse(rest).ok().filter(|t| !t.has_params())?;
Some(format!("{iface}/stream/{}", template.as_str()))
});
if name.is_none() {
bad(out, Code::BadValue, entry.clone());
}
let toml::Value::Table(e) = v else {
if name.is_some() {
bad(out, Code::BadValue, entry);
}
continue;
};
for key in e.keys() {
if key != "every_s" && key != "keyframe_s" {
bad(out, Code::UnknownField, format!("{entry}.{key}"));
}
}
let every_s = match e.get("every_s") {
None => {
bad(out, Code::MissingField, format!("{entry}.every_s"));
None
}
Some(v) => {
let n = int_in(v, 1, MAX_U32);
if n.is_none() {
bad(out, Code::BadValue, format!("{entry}.every_s"));
}
n
}
};
let keyframe_s = match e.get("keyframe_s") {
None => Some(None),
Some(v) => {
let n = int_in(v, 1, MAX_U32);
if n.is_none() {
bad(out, Code::BadValue, format!("{entry}.keyframe_s"));
}
n.map(Some)
}
};
if let (Some(name), Some(every_s), Some(keyframe_s)) = (name, every_s, keyframe_s) {
frames.insert(
name,
FrameCadence {
every_s,
keyframe_s,
},
);
}
}
ok.then_some(frames)
}
fn parse_events(face: &str, v: &toml::Value, out: &mut Vec<Finding>) -> Option<BTreeSet<String>> {
let read = || {
let mut names = BTreeSet::new();
for x in v.as_array()? {
let (i, rest) = x.as_str()?.split_once('/')?;
let iface: crate::grammar::IfaceId = i.parse().ok()?;
let template = Template::parse(rest).ok()?;
if !names.insert(format!("{iface}/events/{}", template.as_str())) {
return None;
}
}
Some(names)
};
let events = read();
if events.is_none() {
out.push(Finding::new(Code::BadValue, Some(face), "events"));
}
events
}
struct FaceCtx<'a> {
profile: Profile,
protocols: Option<&'static [&'static str]>,
transport: Option<&'a TransportDraft>,
}
fn parse_face(
name: &str,
t: &toml::Table,
ctx: &FaceCtx<'_>,
out: &mut Vec<Finding>,
) -> Option<Face> {
let at = Some(name);
let v2 = ctx.profile == Profile::V2;
let mut ok = true;
let mut bad = |out: &mut Vec<Finding>, code: Code, key: &str| {
out.push(Finding::new(code, at, key));
ok = false;
};
for k in t.keys() {
if v2 && (k == "batch_bytes" || k == "lease_ms") {
bad(out, Code::MovedField, k);
} else if !(if v2 { FACE_KEYS_V2 } else { FACE_KEYS }).contains(&k.as_str()) {
bad(out, Code::UnknownField, k);
}
}
let far = match t.get("far") {
None => {
bad(out, Code::MissingField, "far");
None
}
Some(toml::Value::String(s)) if !s.is_empty() => Some(s.clone()),
Some(_) => {
bad(out, Code::BadValue, "far");
None
}
};
let attach = match t.get("attach") {
None => {
bad(out, Code::MissingField, "attach");
None
}
Some(toml::Value::String(s)) if s == "client" => Some(AttachKind::Client),
Some(toml::Value::String(s)) if s == "south-region" => Some(AttachKind::South),
Some(toml::Value::String(s)) if v2 && s == "device" => Some(AttachKind::Device),
Some(toml::Value::String(s)) if s == "router" => {
bad(out, Code::RouterAttach, "attach");
None
}
Some(_) => {
bad(out, Code::BadValue, "attach");
None
}
};
let region = match t.get("region") {
None => None,
Some(toml::Value::String(s)) if !s.is_empty() && s.len() <= MAX_REGION => Some(s.clone()),
Some(_) => {
bad(out, Code::BadValue, "region");
None
}
};
match (attach, t.contains_key("region")) {
(Some(AttachKind::South), false) => bad(out, Code::MissingField, "region"),
(Some(AttachKind::Client | AttachKind::Device), true) => {
bad(out, Code::BadValue, "region");
}
_ => {}
}
let devices = match t.get("devices") {
Some(v) if v2 => {
let l = device_list(v);
if l.is_none() || matches!(attach, Some(AttachKind::Client | AttachKind::South)) {
bad(out, Code::BadValue, "devices");
}
l
}
_ => None,
};
if attach == Some(AttachKind::Device) && !t.contains_key("devices") {
bad(out, Code::MissingField, "devices");
}
let opens = match t.get("opens") {
Some(v) if v2 => match v.as_str() {
Some("far") => Some(Opens::Far),
Some("near") if !matches!(attach, Some(AttachKind::Client | AttachKind::Device)) => {
Some(Opens::Near)
}
_ => {
bad(out, Code::BadValue, "opens");
None
}
},
_ => Some(Opens::Far),
};
let link_protocols = match t.get("select") {
None => {
bad(out, Code::MissingField, "select");
None
}
Some(toml::Value::Table(s)) => {
for k in s.keys() {
if k == "interfaces" {
bad(out, Code::SelectInterfaces, "select.interfaces");
} else if k != "link_protocols" {
bad(out, Code::UnknownField, &format!("select.{k}"));
}
}
match s.get("link_protocols") {
None => {
bad(out, Code::MissingField, "select.link_protocols");
None
}
Some(v) => match protocol_list(v) {
None => {
bad(out, Code::BadValue, "select.link_protocols");
None
}
Some(l)
if ctx.protocols.is_some_and(|known| {
l.iter().any(|p| !known.contains(&p.as_str()))
}) =>
{
bad(out, Code::UnknownProtocol, "select.link_protocols");
None
}
Some(l) => Some(l),
},
}
}
Some(_) => {
bad(out, Code::BadValue, "select");
None
}
};
match t.get("class") {
None => bad(out, Code::MissingField, "class"),
Some(toml::Value::String(s)) if s == "constrained" => {}
Some(_) => bad(out, Code::BadValue, "class"),
}
let expose = match t.get("expose") {
None => {
bad(out, Code::MissingField, "expose");
None
}
Some(toml::Value::String(s)) if s == "link" => Some(Expose::Link),
Some(toml::Value::String(s)) if s == "none" => Some(Expose::None),
Some(_) => {
bad(out, Code::BadValue, "expose");
None
}
};
let interval_s = match t.get("interval_s") {
None => None,
Some(v) => match int_in(v, 1, MAX_U32) {
Some(n) => Some(n),
None => {
bad(out, Code::BadValue, "interval_s");
None
}
},
};
match (expose, t.contains_key("interval_s")) {
(Some(Expose::Link), false) => bad(out, Code::MissingField, "interval_s"),
(Some(Expose::None), true) => bad(out, Code::BadValue, "interval_s"),
_ => {}
}
let mut int = |key: &str, lo: u64, hi: u64, required: bool| match t.get(key) {
None => {
if required {
bad(out, Code::MissingField, key);
}
None
}
Some(v) => {
let n = int_in(v, lo, hi);
if n.is_none() {
bad(out, Code::BadValue, key);
}
n
}
};
let max_outage_s = int("max_outage_s", 1, MAX_U32, true);
let link_bps = int("link_bps", 1, MAX_U32, true);
if v2 {
let loss_ppm = int("loss_ppm", 0, MAX_LOSS_PPM, true);
let reply_timeout_ms = int("reply_timeout_ms", 1, MAX_U32, true);
let horizon_s = int("horizon_s", 1, MAX_U32, false);
let arq = match t.get("arq") {
None => {
bad(out, Code::MissingField, "arq");
None
}
Some(toml::Value::Boolean(b)) => Some(*b),
Some(_) => {
bad(out, Code::BadValue, "arq");
None
}
};
let frames = match t.get("frames") {
None => Some(None),
Some(v) => {
let f = parse_frames(name, v, out);
if f.is_none() {
ok = false;
}
f.map(Some)
}
};
let events = match t.get("events") {
None => Some(None),
Some(v) => {
let e = parse_events(name, v, out);
if e.is_none() {
ok = false;
}
e.map(Some)
}
};
if expose == Some(Expose::None) {
for key in ["frames", "events", "horizon_s"] {
if t.contains_key(key) {
out.push(Finding::new(Code::BadValue, at, key));
ok = false;
}
}
}
face_lints_v2(
name,
ctx.transport,
link_bps,
loss_ppm,
reply_timeout_ms,
arq,
out,
);
if !ok {
return None;
}
let tr = ctx.transport?;
return Some(Face {
far: far?,
attach: match attach? {
AttachKind::Client => Attach::Client,
AttachKind::South => Attach::SouthRegion { region: region? },
AttachKind::Device => Attach::Device { devices: devices? },
},
link_protocols: link_protocols?,
expose: expose?,
interval_s,
max_outage_s: max_outage_s?,
batch_bytes: tr.batch_bytes?,
link_bps: link_bps?,
lease_ms: tr.lease_ms?,
loss_ppm,
arq,
reply_timeout_ms,
frames: frames?,
events: events?,
horizon_s,
opens: opens?,
});
}
let batch_bytes = int("batch_bytes", 1, MAX_BATCH, true);
let lease_ms = int("lease_ms", 1, MAX_U32, false);
let lease = if t.contains_key("lease_ms") {
lease_ms
} else {
Some(DEFAULT_LEASE_MS)
};
if let (Some(b), Some(bps), Some(l)) = (batch_bytes, link_bps, lease)
&& !within_lease(b, bps, l)
{
out.push(Finding::new(Code::BatchOverLease, at, "batch_bytes"));
}
if !ok {
return None;
}
Some(Face {
far: far?,
attach: match attach? {
AttachKind::Client => Attach::Client,
AttachKind::South => Attach::SouthRegion { region: region? },
AttachKind::Device => return None,
},
link_protocols: link_protocols?,
expose: expose?,
interval_s,
max_outage_s: max_outage_s?,
batch_bytes: batch_bytes?,
link_bps: link_bps?,
lease_ms: if t.contains_key("lease_ms") {
lease_ms?
} else {
DEFAULT_LEASE_MS
},
loss_ppm: None,
arq: None,
reply_timeout_ms: None,
frames: None,
events: None,
horizon_s: None,
opens: Opens::Far,
})
}
fn face_lints_v2(
name: &str,
tr: Option<&TransportDraft>,
link_bps: Option<u64>,
loss_ppm: Option<u64>,
reply_timeout_ms: Option<u64>,
arq: Option<bool>,
out: &mut Vec<Finding>,
) {
let at = Some(name);
let tr = tr.cloned().unwrap_or_default();
let mut warn = |code: Code, key: String| out.push(Finding::new(code, at, key));
if let (Some(b), Some(bps), Some(l)) = (tr.batch_bytes, link_bps, tr.lease_ms)
&& !within_lease(b, bps, l)
{
warn(Code::BatchOverLease, TransportKey::BatchBytes.at());
}
if let (Some(l), Some(k), Some(p)) = (tr.lease_ms, tr.keep_alive, loss_ppm)
&& flaps(l, k, p)
{
warn(Code::KeepAliveFlaps, TransportKey::KeepAlive.at());
}
if let (Some(q), Some(b), Some(l), Some(bps)) =
(tr.sequence, tr.batch_bytes, tr.lease_ms, link_bps)
&& window_filled(q, b, l, bps)
{
warn(Code::SequenceWindow, TransportKey::Sequence.at());
}
for (key, timeout) in [
(TransportKey::OpenTimeout, tr.open_timeout_ms),
(TransportKey::AcceptTimeout, tr.accept_timeout_ms),
] {
if let (Some(t), Some(bps)) = (timeout, link_bps)
&& under_handshake(t, bps)
{
warn(Code::OpenUnderHandshake, key.at());
}
}
if let (Some(r), Some(bps), Some(b)) = (reply_timeout_ms, link_bps, tr.batch_bytes)
&& reply_short(r, bps, b)
{
warn(Code::ReplyTimeoutShort, "reply_timeout_ms".to_owned());
}
if arq == Some(false) {
warn(Code::NoArq, "arq".to_owned());
}
}
fn shared_protocols(table: &toml::Table, known: &[&str], out: &mut Vec<Finding>) {
let Some(toml::Value::Table(faces)) = table.get("face") else {
return;
};
let lists: Vec<(&String, Vec<String>)> = faces
.iter()
.filter_map(|(name, v)| {
let l = protocol_list(v.get("select")?.get("link_protocols")?)?;
l.iter()
.all(|p| known.contains(&p.as_str()))
.then_some((name, l))
})
.collect();
for (i, (name, l)) in lists.iter().enumerate() {
let shared = lists
.iter()
.enumerate()
.any(|(j, (_, m))| i != j && l.iter().any(|p| m.contains(p)));
if shared {
out.push(Finding::new(
Code::SharedProtocol,
Some(name),
"select.link_protocols",
));
}
}
}
fn shared_far(table: &toml::Table, out: &mut Vec<Finding>) {
let Some(toml::Value::Table(faces)) = table.get("face") else {
return;
};
let mut named: BTreeMap<&str, usize> = BTreeMap::new();
for v in faces.values() {
if let Some(toml::Value::String(far)) = v.get("far")
&& !far.is_empty()
{
*named.entry(far.as_str()).or_default() += 1;
}
}
for (far, n) in named {
if n > 1 {
out.push(Finding::new(Code::FarOfTwoFaces, None, far));
}
}
}
fn device_listed(
table: &toml::Table,
system: Option<&str>,
services: Option<&[String]>,
out: &mut Vec<Finding>,
) {
let Some(toml::Value::Table(faces)) = table.get("face") else {
return;
};
let lists: Vec<(&String, Vec<String>)> = faces
.iter()
.filter(|(_, v)| v.get("attach").and_then(toml::Value::as_str) == Some("device"))
.filter_map(|(name, v)| Some((name, device_list(v.get("devices")?)?)))
.collect();
let listed: BTreeSet<String> = match (system, services) {
(Some(sys), Some(services)) => services.iter().map(|s| format!("{sys}/{s}")).collect(),
_ => BTreeSet::new(),
};
for (i, (name, l)) in lists.iter().enumerate() {
let elsewhere = l.iter().any(|d| {
listed.contains(d)
|| lists
.iter()
.enumerate()
.any(|(j, (_, m))| i != j && m.contains(d))
});
if elsewhere {
out.push(Finding::new(Code::DeviceListed, Some(name), "devices"));
}
}
}
fn integer(v: &Value) -> Option<i128> {
v.as_u64()
.map(i128::from)
.or_else(|| v.as_i64().map(i128::from))
}
#[must_use]
pub fn same_value(a: &Value, b: &Value) -> bool {
match (a.as_u64(), b.as_u64()) {
(Some(x), Some(y)) => x == y,
_ => a == b,
}
}
#[must_use]
pub fn check_transport(
policy: &FacePolicy,
router: &StatedTransport,
peer: Option<&StatedTransport>,
) -> Vec<Finding> {
let mut out = Vec::new();
let Some(planned) = &policy.transport else {
return out;
};
let defaults = policy.binding.defaults();
for key in TransportKey::ALL {
if !same_value(&planned.value(key), &router.runs(key, &defaults)) {
out.push(Finding::new(Code::TransportDiffers, None, key.at()));
}
}
let lease_us = integer(&router.runs(TransportKey::Lease, &defaults)).map(|ms| ms * 1_000);
let wbc_us = integer(&router.runs(TransportKey::WaitBeforeClose, &defaults));
if let (Some(lease), Some(wbc)) = (lease_us, wbc_us)
&& wbc < lease
{
out.push(Finding::new(
Code::WaitUnderLease,
None,
TransportKey::WaitBeforeClose.at(),
));
}
if let Some(peer) = peer {
for key in [TransportKey::Lease, TransportKey::KeepAlive] {
if !same_value(&router.runs(key, &defaults), &peer.runs(key, &defaults)) {
out.push(Finding::new(Code::PeerDiffers, None, key.at()));
}
}
}
if router.stamps() {
out.push(Finding::new(Code::FaceTimestamping, None, "timestamping"));
}
sort_findings(&mut out);
out
}
pub fn catalog_id(text: &str) -> Result<String, crate::catalog::Refusal> {
crate::catalog::Catalog::parse(text).map(|c| c.id().hex())
}
#[must_use]
pub fn check_catalog(policy: &FacePolicy, held: &str) -> Vec<Finding> {
if policy.catalog.as_deref() == Some(held) {
Vec::new()
} else {
vec![Finding::new(Code::CatalogMismatch, None, "catalog")]
}
}
#[derive(Debug, Clone)]
pub struct Res {
pub template: Template,
pub token: KindToken,
pub annotations: BTreeMap<String, Value>,
pub history: bool,
pub frame: Option<FrameFacts>,
pub packed: bool,
pub block: bool,
pub priority_data: bool,
pub express: bool,
pub longest_bytes: Option<u64>,
pub link_v2: bool,
pub epoch: Option<String>,
pub tombstone_only: bool,
pub cardinality: Option<u64>,
}
impl Res {
#[must_use]
pub fn new(template: Template, token: KindToken, annotations: BTreeMap<String, Value>) -> Self {
Res {
history: false,
frame: None,
packed: false,
block: false,
priority_data: true,
express: false,
longest_bytes: None,
link_v2: false,
epoch: None,
tombstone_only: tombstone_only(token, &template, &annotations, |_| false),
cardinality: None,
template,
token,
annotations,
}
}
#[must_use]
pub fn shape(&self) -> Shape {
Shape::of(
self.token,
self.template.has_params(),
self.frame.is_some(),
&self.annotations,
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FrameFacts {
pub interval_ms: Option<u64>,
pub largest_bytes: Option<u64>,
pub keyframe_every: u32,
}
impl Res {
#[must_use]
pub fn qos(&self) -> PutQos {
PutQos {
block: self.block,
priority_data: self.priority_data,
express: self.express,
}
}
#[must_use]
pub fn of(c: &Contract, r: &Resource) -> Self {
let data = match &r.body {
crate::contract::Body::Data(d) => Some(d),
crate::contract::Body::Operation(_) => None,
};
let frame = data.and_then(|d| d.frame.as_ref()).map(|p| FrameFacts {
interval_ms: p.interval_ms(&r.annotations),
largest_bytes: crate::frame::Layout::of_resource(c, r)
.ok()
.flatten()
.map(|l| l.largest_payload_bytes()),
keyframe_every: p.keyframe_every,
});
let packed = data.is_some_and(|d| d.type_.is_packed());
let longest_bytes = match (&frame, data) {
(Some(f), _) => f.largest_bytes,
(None, Some(d)) if packed => c
.packed_layout(&d.type_)
.ok()
.flatten()
.map(|l| ENVELOPE_BYTES + l.max_bits().div_ceil(8)),
_ => None,
};
Res {
template: r.template.clone(),
token: r.token,
annotations: r.annotations.clone(),
history: data.is_some_and(|d| d.history.is_some()),
frame,
packed,
block: data.is_some_and(|d| d.congestion == crate::authoring::Congestion::Block),
priority_data: data.is_none_or(|d| d.priority == crate::authoring::Priority::Data),
express: data.is_some_and(|d| d.express),
longest_bytes,
link_v2: uses_v2(c),
epoch: r.epoch.clone(),
tombstone_only: tombstone_only(r.token, &r.template, &r.annotations, |p| {
c.uses.iter().any(|u| u.to_string() == p)
}),
cardinality: r.cardinality.filter(|_| r.template.has_params()),
}
}
}
#[must_use]
pub fn tombstone_only(
token: KindToken,
template: &Template,
annotations: &BTreeMap<String, Value>,
uses: impl Fn(&str) -> bool,
) -> bool {
is_state(token)
&& (crate::collection::per_key_in(token, annotations, uses)
|| crate::collection::snapshot_prefix(template).is_none())
}
#[derive(Debug, Clone, Default)]
pub struct Deployment {
pub implements: BTreeMap<String, Vec<String>>,
pub interfaces: BTreeMap<String, Vec<Vec<Res>>>,
pub heartbeats: BTreeSet<String>,
pub fingerprints: BTreeMap<String, BTreeSet<crate::canonical::Fingerprint>>,
pub catalog: Option<crate::catalog::Catalog>,
pub governed: BTreeSet<String>,
pub users: BTreeSet<String>,
pub default_allow: bool,
pub owner_heartbeats: BTreeSet<String>,
}
impl Deployment {
pub fn add_contract(&mut self, c: &Contract) {
if freshness::uses_v2(c) {
self.heartbeats.insert(c.iface.to_string());
}
if crate::redundancy::is_governed(c) {
self.governed.insert(c.iface.to_string());
}
self.fingerprints
.entry(c.iface.to_string())
.or_default()
.insert(crate::canonical::Fingerprint::of(c));
self.add_revision(
c.iface.to_string(),
c.resources.iter().map(|r| Res::of(c, r)).collect(),
);
}
pub fn add_revision(&mut self, iface: impl Into<String>, resources: Vec<Res>) {
self.interfaces
.entry(iface.into())
.or_default()
.push(resources);
}
}
fn merge(revisions: &[Vec<Res>]) -> (Vec<Res>, BTreeSet<usize>) {
let mut out: Vec<Res> = Vec::new();
let mut readings: Vec<Vec<&Res>> = Vec::new();
for rev in revisions {
for r in rev {
match out
.iter()
.position(|x| x.token == r.token && x.template == r.template)
{
Some(i) => readings[i].push(r),
None => {
out.push(r.clone());
readings.push(vec![r]);
}
}
}
}
let mut disagree = BTreeSet::new();
for (i, rs) in readings.iter().enumerate() {
let links = rs
.iter()
.filter(|r| exposure(kind_of(r.token), &r.annotations) == Exposure::Link)
.count();
out[i].history = rs.iter().any(|r| r.history);
if out[i].epoch.is_none() {
out[i].epoch = rs.iter().find_map(|r| r.epoch.clone());
}
if let Some(f) = &mut out[i].frame {
f.keyframe_every = rs
.iter()
.filter_map(|r| r.frame.map(|f| f.keyframe_every))
.min()
.unwrap_or(f.keyframe_every);
f.largest_bytes = rs
.iter()
.filter_map(|r| r.frame.and_then(|f| f.largest_bytes))
.max();
}
out[i].packed = rs.iter().all(|r| r.packed);
if !timed(&out[i].annotations)
&& let Some(d) = rs
.iter()
.find_map(|r| r.annotations.get(crate::timing::DEADLINE_MS))
{
out[i]
.annotations
.insert(crate::timing::DEADLINE_MS.to_owned(), d.clone());
}
let block = rs.iter().any(|r| r.block);
out[i].block = block;
out[i].priority_data = rs.iter().all(|r| r.priority_data);
out[i].express = rs.iter().any(|r| r.express);
out[i].tombstone_only = rs.iter().any(|r| r.tombstone_only);
out[i].cardinality = if rs.iter().any(|r| r.cardinality.is_none()) {
None
} else {
rs.iter().filter_map(|r| r.cardinality).max()
};
out[i].longest_bytes = rs
.iter()
.filter(|r| r.block || !block)
.filter_map(|r| r.longest_bytes)
.max();
if links > 0 && links < rs.len() {
disagree.insert(i);
out[i]
.annotations
.insert(EXPOSURE.to_owned(), Value::String("host".to_owned()));
}
let ttls: Vec<Option<std::time::Duration>> = rs.iter().map(|r| horizon(r).ttl()).collect();
if ttls.windows(2).any(|w| w[0] != w[1]) {
match ttls.into_iter().collect::<Option<Vec<_>>>() {
Some(all) => {
let least = all.into_iter().min().unwrap_or_default();
out[i]
.annotations
.insert(freshness::TTL_S.to_owned(), Value::from(least.as_secs()));
}
None => {
out[i].annotations.remove(freshness::TTL_S);
}
}
}
}
(out, disagree)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Deny {
pub id: String,
pub flows: Vec<&'static str>,
pub messages: Vec<&'static str>,
pub key_exprs: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Rule {
pub key_expr: String,
pub freq: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Downsampling {
pub id: String,
pub link_protocols: Vec<String>,
pub flows: Vec<&'static str>,
pub messages: Vec<&'static str>,
pub rules: Vec<Rule>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Filter {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub modes: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub region_names: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct South {
pub filters: Vec<Filter>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Gateway {
pub south: Vec<South>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "shape")]
pub enum AttachPlan {
#[serde(rename = "client")]
Client,
#[serde(rename = "south-region")]
SouthRegion { region: String, gateway: Gateway },
#[serde(rename = "device")]
Device { devices: Vec<String> },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Window {
pub service: String,
pub min_s: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Liveness {
pub service: String,
pub evidence: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct FacePlan {
pub name: String,
pub far: String,
pub attach: AttachPlan,
pub deny: Vec<Deny>,
pub downsampling: Option<Downsampling>,
pub windows: Vec<Window>,
pub liveness: Vec<Liveness>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reply_timeout_ms: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub frames: Option<Vec<ListedFrame>>,
pub findings: Vec<Finding>,
#[serde(skip)]
pub crossing: BTreeSet<String>,
}
impl FacePlan {
#[must_use]
pub fn crosses(&self, iface: &str, token: KindToken, template: &Template) -> bool {
self.crossing
.contains(&format!("{iface}/{}/{}", token.as_str(), template.as_str()))
}
#[must_use]
pub fn heartbeat_crosses(&self, iface: &str) -> bool {
self.crossing.contains(&heartbeat_name(iface))
}
#[must_use]
pub fn owner_heartbeat_crosses(&self, class: crate::heartbeat::Class) -> bool {
self.crossing.contains(&owner_heartbeat_name(class))
}
}
fn heartbeat_name(iface: &str) -> String {
format!("{}/stream/heartbeat/{iface}", freshness::PROFILE_V2)
}
#[must_use]
pub fn owner_heartbeat_name(class: crate::heartbeat::Class) -> String {
format!("{}/stream/heartbeats/{class}", freshness::PROFILE_V2)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ListedFrame {
pub resource: String,
#[serde(flatten)]
pub cadence: FrameCadence,
}
#[derive(Debug, Default)]
struct FaceFacts {
crossing: BTreeSet<String>,
unlisted: BTreeSet<String>,
ifaces: BTreeSet<String>,
}
fn res_name(iface: &str, r: &Res) -> String {
format!("{iface}/{}/{}", r.token.as_str(), r.template.as_str())
}
pub fn plan(policy: &FacePolicy, deployment: &Deployment) -> Result<Vec<FacePlan>, Vec<Finding>> {
let mut errors = Vec::new();
let mut listed: BTreeSet<&str> = BTreeSet::new();
let services = policy.owners();
for s in &services {
match deployment.implements.get(s.key) {
None => errors.push(Finding::new(Code::ServiceUnknown, None, s.key)),
Some(ifaces) => {
for i in ifaces {
if deployment
.interfaces
.get(i)
.is_some_and(|revs| !revs.is_empty())
{
listed.insert(i);
} else {
errors.push(Finding::new(Code::ContractUnknown, None, i.clone()));
}
if let Some(face) = s.device_face
&& (i == ARCHIVE || deployment.governed.contains(i))
{
errors.push(Finding::new(Code::PresenceRequired, Some(face), i.clone()));
}
}
}
}
}
let mut unauthenticated: BTreeSet<&str> = BTreeSet::new();
for (name, face) in &policy.faces {
if face.opens == Opens::Near && deployment.users.contains(&face.far) {
if deployment.default_allow {
unauthenticated.insert(name.as_str());
} else {
errors.push(Finding::new(Code::NearOpensUser, Some(name), "opens"));
}
}
}
if !errors.is_empty() {
sort_findings(&mut errors);
return Err(errors);
}
let view: View = listed
.iter()
.map(|i| ((*i).to_owned(), merge(&deployment.interfaces[*i])))
.collect();
let v2 = policy.profile == Profile::V2;
if v2 {
for i in &listed {
for r in deployment.interfaces[*i].iter().flatten() {
let e = exposure(kind_of(r.token), &r.annotations);
if packed_required(r.link_v2, r.token, &e, r.packed) {
errors.push(Finding::new(Code::PackedRequired, None, res_name(i, r)));
}
}
}
}
let mut faces: Vec<(FacePlan, FaceFacts)> = policy
.faces
.iter()
.map(|(name, face)| {
plan_face(
policy,
deployment,
&view,
&services,
&listed,
name,
face,
&mut errors,
)
})
.collect();
for (p, _) in &mut faces {
if unauthenticated.contains(p.name.as_str()) {
p.findings.push(Finding::new(
Code::NearOpensUnauthenticated,
Some(&p.name),
"opens",
));
sort_findings(&mut p.findings);
}
}
if v2 {
let crossing: BTreeSet<String> = faces
.iter()
.flat_map(|(_, f)| f.crossing.iter().cloned())
.collect();
for (p, f) in &mut faces {
for n in f.unlisted.iter().filter(|n| !crossing.contains(*n)) {
p.findings
.push(Finding::new(Code::FrameUnlisted, Some(&p.name), n.clone()));
}
sort_findings(&mut p.findings);
}
if let Some(cat) = &deployment.catalog {
let ifaces: BTreeSet<&String> = faces.iter().flat_map(|(_, f)| &f.ifaces).collect();
for i in ifaces {
let Ok(id) = i.parse::<crate::grammar::IfaceId>() else {
continue;
};
for fp in deployment.fingerprints.get(i).into_iter().flatten() {
if cat.index_of(&id, fp).is_none() {
errors.push(Finding::new(
Code::CatalogMissing,
None,
format!("{i}@{fp}"),
));
}
}
}
}
}
if !errors.is_empty() {
sort_findings(&mut errors);
return Err(errors);
}
Ok(faces.into_iter().map(|(p, _)| p).collect())
}
type View = BTreeMap<String, (Vec<Res>, BTreeSet<usize>)>;
#[allow(clippy::too_many_arguments)]
fn plan_face(
policy: &FacePolicy,
deployment: &Deployment,
view: &View,
services: &[Owner<'_>],
listed: &BTreeSet<&str>,
name: &str,
face: &Face,
errors: &mut Vec<Finding>,
) -> (FacePlan, FaceFacts) {
let mut findings = Vec::new();
let mut facts = FaceFacts::default();
let v2 = policy.profile == Profile::V2;
let resources_of = |iface: &str| -> &[Res] { &view[iface].0 };
let sequence = policy.transport.map_or(Sequence::Bit32, |t| t.sequence);
let fits = |payload: u64, qos: PutQos| {
fits_batch(
payload,
face.batch_bytes,
qos,
sequence,
&face.link_protocols,
)
};
let crossing_of = |iface: &str, r: &Res| {
let e = exposure(kind_of(r.token), &r.annotations);
if v2 {
let name = res_name(iface, r);
let listed = if r.token == KindToken::Events {
face.events.as_ref().map(|l| l.contains(&name))
} else {
face.frames.as_ref().map(|f| f.contains_key(&name))
};
crossing_v2(r.token, r.shape(), &e, face.expose, listed)
} else {
crossing(r.token, r.template.has_params(), &e, face.expose)
}
};
for entry in face.frames.iter().flat_map(BTreeMap::keys) {
let known = listed.iter().any(|i| {
resources_of(i)
.iter()
.any(|r| r.frame.is_some() && &res_name(i, r) == entry)
});
if !known {
errors.push(Finding::new(Code::FrameUnknown, Some(name), entry.clone()));
}
}
for entry in face.events.iter().flatten() {
let known = listed.iter().any(|i| {
resources_of(i)
.iter()
.any(|r| r.token == KindToken::Events && &res_name(i, r) == entry)
});
if !known {
errors.push(Finding::new(Code::EventUnknown, Some(name), entry.clone()));
}
}
for iface in listed {
let (resources, disagree) = &view[*iface];
for (i, r) in resources.iter().enumerate() {
match crossing_of(iface, r).reason {
Reason::Templated => findings.push(Finding::new(
Code::TemplatedExposure,
Some(name),
res_name(iface, r),
)),
Reason::Timed => findings.push(Finding::new(
Code::TimedDownsampled,
Some(name),
res_name(iface, r),
)),
Reason::Unlisted if r.frame.is_some() => {
facts.unlisted.insert(res_name(iface, r));
}
_ => {}
}
if face.expose == Expose::Link && disagree.contains(&i) {
findings.push(Finding::new(
Code::ExposureDisagrees,
Some(name),
res_name(iface, r),
));
}
}
}
let mut deny = if face.attach.is_device() {
zk_carve()
} else {
vec![plane("zk", ZK_DENY)]
};
deny.extend([plane("adv", ADV_DENY), plane("admin", ADMIN_DENY)]);
for s in services.iter().filter(|s| s.device_face == Some(name)) {
for iface in &deployment.implements[s.key] {
for r in resources_of(iface).iter().filter(|r| r.epoch.is_some()) {
findings.push(Finding::new(
Code::EpochOnDevice,
Some(name),
res_name(iface, r),
));
}
}
}
let mut overlapped: BTreeSet<String> = BTreeSet::new();
let mut by_token: BTreeMap<usize, Vec<Deny>> = BTreeMap::new();
let mut heartbeat_crosses: BTreeMap<String, bool> = BTreeMap::new();
let order = [2usize, 3, 4, 0, 1];
for t in order {
let token = PUSH_TOKENS[t];
if token == KindToken::Stream {
heartbeat_crosses = heartbeats_of(deployment, listed, view, &|i: &str, r: &Res| {
crossing_of(i, r).crosses() && !overlapped.contains(&res_name(i, r))
});
}
let mut pseudo: Vec<(Template, bool)> = if token == KindToken::Stream {
heartbeat_crosses
.iter()
.filter_map(|(i, crosses)| {
Template::parse(&format!("heartbeat/{i}"))
.ok()
.map(|t| (t, *crosses))
})
.collect()
} else {
Vec::new()
};
if !pseudo.is_empty() {
let link = heartbeat_crosses.values().any(|c| *c);
let owner: Vec<(String, bool)> = if v2 {
crate::heartbeat::Class::ALL
.into_iter()
.map(|c| {
(
format!("heartbeats/{c}"),
link && c == crate::heartbeat::Class::Link,
)
})
.collect()
} else {
vec![(crate::heartbeat::OWNER_RESOURCE.to_owned(), false)]
};
pseudo.extend(
owner
.into_iter()
.filter_map(|(t, crosses)| Template::parse(&t).ok().map(|t| (t, crosses))),
);
}
let mut groups: BTreeMap<String, Vec<Item<'_>>> = BTreeMap::new();
for iface in listed {
if !pseudo.is_empty() && *iface == freshness::PROFILE_V2 {
continue;
}
groups.insert(
(*iface).to_owned(),
resources_of(iface)
.iter()
.filter(|r| r.token == token)
.map(|r| Item {
template: &r.template,
crosses: crossing_of(iface, r).crosses(),
})
.collect(),
);
}
if !pseudo.is_empty() {
groups.insert(
freshness::PROFILE_V2.to_owned(),
pseudo
.iter()
.map(|(template, crosses)| Item {
template,
crosses: *crosses,
})
.collect(),
);
}
let any = groups.values().flatten().any(|i| i.crosses);
if !any {
by_token.insert(
t,
vec![push_deny(
token.as_str().to_owned(),
vec![format!("zk2/*/*/*/{}/**", token.as_str())],
)],
);
continue;
}
let mut denies = Vec::new();
for (iface, items) in &groups {
let root = format!("zk2/*/*/{iface}/{}", token.as_str());
let keys = if items.iter().any(|i| i.crosses) {
let (keys, exact) = carve(&root, items);
for c in items.iter().filter(|i| i.crosses) {
let hit = exact.iter().any(|&t| {
let t = items[t].template;
t.overlaps(c.template) && c.template.precedence(t) == Ordering::Greater
});
if hit {
let at = format!("{iface}/{}/{}", token.as_str(), c.template.as_str());
overlapped.insert(at.clone());
findings.push(Finding::new(Code::CarveOutOverlap, Some(name), at));
}
}
keys
} else {
vec![format!("{root}/**")]
};
if !keys.is_empty() {
denies.push(push_deny(format!("{}:{iface}", token.as_str()), keys));
}
}
by_token.insert(t, denies);
}
deny.extend(by_token.into_values().flatten());
let crosses = |iface: &str, r: &Res| {
crossing_of(iface, r).crosses() && !overlapped.contains(&res_name(iface, r))
};
let mut rules = Vec::new();
if let Some(freq) = face.freq() {
for s in services.iter().filter(|s| s.device_face != Some(name)) {
for iface in &deployment.implements[s.key] {
for r in resources_of(iface) {
if is_stream(r.token) && r.frame.is_none() && crosses(iface, r) {
rules.push(Rule {
key_expr: format!(
"zk2/{}/{iface}/{}/{}",
s.address,
r.token.as_str(),
r.template.as_str()
),
freq,
});
}
}
}
}
rules.sort_by(|a, b| a.key_expr.cmp(&b.key_expr));
rules.dedup_by(|a, b| a.key_expr == b.key_expr);
for iface in listed {
for r in resources_of(iface) {
if r.frame.is_some() {
continue;
}
if let (true, Some(ttl), Some(n)) = (
is_stream(r.token) && crosses(iface, r),
horizon(r).ttl(),
face.interval_s,
) && u128::from(n) * 2 > u128::from(ttl.as_secs())
{
findings.push(Finding::new(
Code::IntervalOverHorizon,
Some(name),
res_name(iface, r),
));
}
}
}
}
let mut listed_frames = Vec::new();
let mut cadences: Vec<u64> = Vec::new();
for iface in listed {
for r in resources_of(iface) {
let Some(f) = r.frame.filter(|_| crosses(iface, r)) else {
continue;
};
let at = || res_name(iface, r);
let entry = face.frames.as_ref().and_then(|l| l.get(&at())).copied();
let cadence_ms = entry.map_or(f.interval_ms, |e| Some(e.every_s * 1000));
cadences.extend(cadence_ms);
if let Some(e) = entry {
listed_frames.push(ListedFrame {
resource: at(),
cadence: e,
});
if let Some(k) = e.keyframe_s
&& u128::from(k) > u128::from(f.keyframe_every) * u128::from(e.every_s)
{
errors.push(Finding::new(Code::KeyframeUnreachable, Some(name), at()));
}
}
if let (Some(i), Some(n)) = (cadence_ms, face.interval_s)
&& u128::from(i) < u128::from(n) * 1000
{
findings.push(Finding::new(Code::FrameOverInterval, Some(name), at()));
}
if f.largest_bytes.is_some_and(|b| !fits(b, r.qos())) {
findings.push(Finding::new(Code::FrameOverBatch, Some(name), at()));
}
if r.history {
findings.push(Finding::new(Code::HistoryOnFrame, Some(name), at()));
}
if let (Some(ttl), Some(i)) = (horizon(r).ttl(), cadence_ms)
&& u128::from(i) * 2 > ttl.as_millis()
{
findings.push(Finding::new(Code::IntervalOverHorizon, Some(name), at()));
}
if let (true, Some(ttl), Some(h)) = (v2, horizon(r).ttl(), face.horizon_s)
&& ttl.as_secs() < h
{
findings.push(Finding::new(Code::HorizonUnderFace, Some(name), at()));
}
}
}
let mut crossing: BTreeSet<String> = listed
.iter()
.flat_map(|iface| {
resources_of(iface)
.iter()
.filter(|r| crosses(iface, r))
.map(|r| res_name(iface, r))
})
.collect();
crossing.extend(
heartbeat_crosses
.iter()
.filter(|(_, c)| **c)
.map(|(i, _)| heartbeat_name(i)),
);
let owner_link = v2 && heartbeat_crosses.values().any(|c| *c);
let owner_at = || owner_heartbeat_name(crate::heartbeat::Class::Link);
if owner_link {
crossing.insert(owner_at());
}
if v2 {
for iface in listed {
for r in resources_of(iface).iter().filter(|r| crosses(iface, r)) {
facts.crossing.insert(res_name(iface, r));
facts.ifaces.insert((*iface).to_owned());
if !r.packed {
findings.push(Finding::new(
Code::NotPacked,
Some(name),
res_name(iface, r),
));
}
if r.block && r.longest_bytes.is_some_and(|b| !fits(b, r.qos())) {
findings.push(Finding::new(
Code::BlockOverBatch,
Some(name),
res_name(iface, r),
));
}
}
}
for (iface, crosses) in &heartbeat_crosses {
if !crosses {
continue;
}
facts.ifaces.insert(iface.clone());
let Some(ttl) = heartbeat_horizon(view, iface) else {
continue;
};
cadences.push(ttl.as_secs() * 500);
if face.horizon_s.is_some_and(|h| ttl.as_secs() < h) {
findings.push(Finding::new(
Code::HorizonUnderFace,
Some(name),
heartbeat_name(iface),
));
}
}
if owner_link {
let (mut under, mut over) = (false, false);
for s in services {
let ifaces = &deployment.implements[s.key];
if ifaces
.iter()
.any(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
&& let Some(ttl) = owner_heartbeat_horizon(view, &heartbeat_crosses, ifaces)
{
cadences.push(ttl.as_secs() * 500);
under |= face.horizon_s.is_some_and(|h| ttl.as_secs() < h);
}
over |=
owner_heartbeat_longest(view, &heartbeat_crosses, ifaces).is_some_and(|b| {
u64::try_from(b)
.ok()
.is_none_or(|b| !fits(b, PutQos::DATA_DROP))
});
}
if under {
findings.push(Finding::new(Code::HorizonUnderFace, Some(name), owner_at()));
}
if over {
findings.push(Finding::new(Code::BlockOverBatch, Some(name), owner_at()));
}
}
if let (Some(t), Some(c)) = (&policy.transport, cadences.iter().min())
&& u128::from(*c) * u128::from(t.keep_alive) >= u128::from(t.lease_ms)
{
findings.push(Finding::new(
Code::KeepAliveNotSuppressed,
Some(name),
TransportKey::KeepAlive.at(),
));
}
}
listed_frames.sort_by(|a, b| a.resource.cmp(&b.resource));
let downsampling = (!rules.is_empty()).then(|| Downsampling {
id: name.to_owned(),
link_protocols: face.link_protocols.clone(),
flows: vec!["egress"],
messages: vec!["put"],
rules,
});
let mut windows = Vec::new();
let mut liveness = Vec::new();
for s in services {
let ifaces = &deployment.implements[s.key];
let resources = || {
ifaces
.iter()
.flat_map(|i| resources_of(i).iter().map(move |r| (i, r)))
};
if resources().any(|(_, r)| is_state(r.token) && (!v2 || r.tombstone_only)) {
windows.push(Window {
service: s.address.clone(),
min_s: face.max_outage_s,
});
}
let mut evidence: Vec<String> = resources()
.filter(|(i, r)| crosses(i, r) && horizon(r).ttl().is_some())
.map(|(i, r)| res_name(i, r))
.collect();
if !v2
&& deployment.owner_heartbeats.contains(s.key)
&& ifaces
.iter()
.any(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
{
findings.push(Finding::new(Code::OwnerHeartbeatDenied, Some(name), s.key));
}
evidence.extend(
ifaces
.iter()
.filter(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
.map(|i| heartbeat_name(i)),
);
if owner_link
&& ifaces
.iter()
.any(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
{
evidence.push(owner_at());
}
evidence.sort();
evidence.dedup();
liveness.push(Liveness {
service: s.address.clone(),
evidence,
});
}
sort_findings(&mut findings);
let plan = FacePlan {
name: name.to_owned(),
far: face.far.clone(),
attach: match &face.attach {
Attach::Client => AttachPlan::Client,
Attach::SouthRegion { region } => AttachPlan::SouthRegion {
region: region.clone(),
gateway: gateway(region),
},
Attach::Device { devices } => AttachPlan::Device {
devices: devices.clone(),
},
},
deny,
downsampling,
windows,
liveness,
reply_timeout_ms: face.reply_timeout_ms,
frames: face.frames.as_ref().map(|_| listed_frames),
findings,
crossing,
};
(plan, facts)
}
fn horizon(r: &Res) -> Horizon {
freshness::horizon(kind_of(r.token), &r.annotations)
}
fn heartbeat_horizon(view: &View, iface: &str) -> Option<std::time::Duration> {
view.get(iface)?
.0
.iter()
.filter(|r| is_state(r.token))
.filter_map(|r| horizon(r).ttl())
.min()
}
fn is_collection(r: &Res) -> bool {
is_state(r.token) && horizon(r).ttl().is_some()
}
fn is_link(r: &Res) -> bool {
exposure(kind_of(r.token), &r.annotations) == Exposure::Link
}
fn owner_heartbeat_groups<'a>(
view: &'a View,
heartbeats: &'a BTreeMap<String, bool>,
ifaces: &'a [String],
) -> impl Iterator<Item = &'a [Res]> {
let mut seen = BTreeSet::new();
ifaces
.iter()
.filter(move |i| heartbeats.contains_key(i.as_str()) && seen.insert(i.as_str()))
.filter_map(|i| view.get(i.as_str()))
.map(|(resources, _)| resources.as_slice())
.filter(|rs| rs.iter().any(|r| is_collection(r) && is_link(r)))
}
fn owner_heartbeat_horizon(
view: &View,
heartbeats: &BTreeMap<String, bool>,
ifaces: &[String],
) -> Option<std::time::Duration> {
owner_heartbeat_groups(view, heartbeats, ifaces)
.flatten()
.filter(|r| is_collection(r) && is_link(r))
.filter_map(|r| horizon(r).ttl())
.min()
}
fn owner_heartbeat_longest(
view: &View,
heartbeats: &BTreeMap<String, bool>,
ifaces: &[String],
) -> Option<u128> {
use crate::heartbeat::{GROUPS_BITS, INDEX_BITS, TIME_BITS};
let mut body = u128::from(TIME_BITS + GROUPS_BITS);
let mut groups = 0;
for resources in owner_heartbeat_groups(view, heartbeats, ifaces) {
let collections = || resources.iter().filter(|r| is_collection(r));
let sections: u128 = collections().count() as u128
+ collections()
.filter(|r| is_link(r))
.map(|r| {
crate::heartbeat::longest_section_bits(
r.template
.has_params()
.then(|| r.cardinality.unwrap_or(u64::from(u32::MAX))),
)
})
.sum::<u128>();
body += u128::from(INDEX_BITS + 4) + crate::heartbeat::size_bits(sections) + sections;
groups += 1;
}
(groups > 0).then(|| u128::from(ENVELOPE_BYTES) + body.div_ceil(8))
}
fn heartbeats_of(
deployment: &Deployment,
listed: &BTreeSet<&str>,
view: &View,
crosses: &dyn Fn(&str, &Res) -> bool,
) -> BTreeMap<String, bool> {
let mut out = BTreeMap::new();
for iface in listed {
if !deployment.heartbeats.contains(*iface) {
continue;
}
let collections: Vec<&Res> = view[*iface]
.0
.iter()
.filter(|r| is_state(r.token) && horizon(r).ttl().is_some())
.collect();
if collections.is_empty() {
continue;
}
out.insert(
(*iface).to_owned(),
collections.iter().any(|r| crosses(iface, r)),
);
}
out
}
fn plane(id: &str, key: &str) -> Deny {
Deny {
id: id.to_owned(),
flows: FLOWS.to_vec(),
messages: MESSAGES.to_vec(),
key_exprs: vec![key.to_owned()],
}
}
pub const OWN_PAIRS: [(&str, &str); 7] = [
("ingress", "put"),
("ingress", "delete"),
("ingress", "declare_queryable"),
("ingress", "reply"),
("ingress", "liveliness_token"),
("egress", "query"),
("egress", "declare_subscriber"),
];
pub const ZK_CARVED: [&str; 3] = [
"zk2/*/*/@zk/alive/**",
"zk2/*/*/@zk/member/**",
"zk2/@zk/**",
];
pub const ZK_INSTANCE: &str = "zk2/*/*/@zk/instance/**";
fn outside_own(flow: &str) -> Vec<&'static str> {
MESSAGES
.iter()
.copied()
.filter(|m| !OWN_PAIRS.contains(&(flow, *m)))
.collect()
}
#[must_use]
pub fn zk_carve() -> Vec<Deny> {
let mut out = vec![Deny {
id: "zk".to_owned(),
flows: FLOWS.to_vec(),
messages: MESSAGES.to_vec(),
key_exprs: ZK_CARVED.iter().map(|k| (*k).to_owned()).collect(),
}];
for flow in FLOWS {
out.push(Deny {
id: format!("zk:instance:{flow}"),
flows: vec![flow],
messages: outside_own(flow),
key_exprs: vec![ZK_INSTANCE.to_owned()],
});
}
out
}
fn push_deny(id: String, mut key_exprs: Vec<String>) -> Deny {
key_exprs.sort();
key_exprs.dedup();
Deny {
id,
flows: FLOWS.to_vec(),
messages: PUSH_MESSAGES.to_vec(),
key_exprs,
}
}
#[must_use]
pub fn gateway(region: &str) -> Gateway {
Gateway {
south: vec![
South {
filters: vec![Filter {
modes: vec!["peer".to_owned(), "client".to_owned()],
region_names: Vec::new(),
}],
},
South {
filters: vec![Filter {
modes: Vec::new(),
region_names: vec![region.to_owned()],
}],
},
],
}
}
struct Item<'a> {
template: &'a Template,
crosses: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Seg {
Lit(String),
Param,
Rest,
}
impl Seg {
fn of(s: &Segment) -> Self {
match s {
Segment::Literal(l) => Seg::Lit(l.clone()),
Segment::Param(_) => Seg::Param,
Segment::Rest(_) => Seg::Rest,
}
}
fn kind(&self) -> u8 {
match self {
Seg::Lit(_) => 0,
Seg::Param => 1,
Seg::Rest => 2,
}
}
fn pattern(&self) -> &str {
match self {
Seg::Lit(l) => l,
Seg::Param => "*",
Seg::Rest => "*/**",
}
}
}
fn key(root: &str, prefix: &[Seg], suffix: &str) -> String {
let mut k = root.to_owned();
for s in prefix {
k.push('/');
k.push_str(s.pattern());
}
k.push_str(suffix);
while k.contains("/**/**") {
k = k.replace("/**/**", "/**");
}
k
}
fn carve(root: &str, items: &[Item<'_>]) -> (Vec<String>, Vec<usize>) {
let mut keys = Vec::new();
let mut exact = Vec::new();
let all: Vec<usize> = (0..items.len()).collect();
carve_at(root, items, &[], &all, &mut keys, &mut exact);
keys.sort();
keys.dedup();
(keys, exact)
}
fn carve_at(
root: &str,
items: &[Item<'_>],
prefix: &[Seg],
here: &[usize],
keys: &mut Vec<String>,
exact: &mut Vec<usize>,
) {
let d = prefix.len();
let crosses = |i: &usize| items[*i].crosses;
if !here.iter().any(crosses) {
keys.push(key(root, prefix, "/**"));
return;
}
if here.iter().all(crosses) {
return;
}
let segs = |i: usize| items[i].template.segments();
let (equal, longer): (Vec<usize>, Vec<usize>) = here.iter().partition(|&&i| segs(i).len() == d);
if equal.iter().any(|i| !crosses(i)) {
keys.push(key(root, prefix, ""));
}
if !longer.iter().any(crosses) {
keys.push(key(root, prefix, "/*/**"));
return;
}
let kinds: BTreeSet<u8> = longer
.iter()
.map(|&i| Seg::of(&segs(i)[d]).kind())
.collect();
if kinds.len() > 1 {
for &i in &longer {
if !items[i].crosses {
let pattern: Vec<Seg> = segs(i).iter().map(Seg::of).collect();
keys.push(key(root, &pattern, ""));
exact.push(i);
}
}
return;
}
let mut groups: BTreeMap<Seg, Vec<usize>> = BTreeMap::new();
for &i in &longer {
groups.entry(Seg::of(&segs(i)[d])).or_default().push(i);
}
for (seg, group) in groups {
let mut p = prefix.to_vec();
p.push(seg);
carve_at(root, items, &p, &group, keys, exact);
}
}
#[must_use]
pub fn check_windows(
policy: &FacePolicy,
deployment: &Deployment,
windows: &BTreeMap<String, u64>,
) -> Vec<Finding> {
let mut out = Vec::new();
for s in policy.owners() {
let Some(ifaces) = deployment.implements.get(s.key) else {
continue;
};
let v2 = policy.profile == Profile::V2;
let owns_state = ifaces.iter().any(|i| {
deployment.interfaces.get(i).is_some_and(|revs| {
revs.iter()
.flatten()
.any(|r| is_state(r.token) && (!v2 || r.tombstone_only))
})
});
if !owns_state {
continue;
}
let addr = s.address;
let w = windows.get(&addr).copied().unwrap_or(DEFAULT_WINDOW_S);
for (name, face) in &policy.faces {
if w < face.max_outage_s {
out.push(Finding::new(
Code::WindowUnderOutage,
Some(name),
addr.clone(),
));
}
}
}
sort_findings(&mut out);
out
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BlockDeny {
pub flows: Vec<String>,
pub messages: Vec<String>,
pub key_exprs: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct BlockRule {
pub key_expr: String,
pub freq: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Posture {
Deny,
Allow,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BlockSubject {
pub id: String,
pub usernames: Vec<String>,
pub cert_common_names: Vec<String>,
pub link_protocols: Option<Vec<String>>,
pub interfaces: Vec<String>,
pub zids: Vec<String>,
}
impl BlockSubject {
fn bound(&self) -> bool {
!self.usernames.is_empty() || !self.cert_common_names.is_empty()
}
fn protocols(&self) -> Option<&[String]> {
self.link_protocols.as_deref().filter(|p| !p.is_empty())
}
fn selects(&self, p: &str) -> bool {
self.protocols().is_none_or(|l| l.iter().any(|x| x == p))
}
fn on_face(&self, face: &Face) -> bool {
self.protocols()
.is_none_or(|l| l.iter().any(|x| face.link_protocols.contains(x)))
}
fn far_alone(&self, far: &str) -> bool {
let only = |v: &[String]| !v.is_empty() && v.iter().all(|x| x == far);
match (self.usernames.is_empty(), self.cert_common_names.is_empty()) {
(false, true) => only(&self.usernames),
(true, false) => only(&self.cert_common_names),
_ => false,
}
}
fn answers(&self, name: &str, kind: NameKind) -> bool {
if !self.interfaces.is_empty() || !self.zids.is_empty() {
return false;
}
if !self.bound() {
return true;
}
let has = |v: &[String]| v.iter().any(|x| x == name);
match kind {
NameKind::User => self.cert_common_names.is_empty() && has(&self.usernames),
NameKind::Cn => self.usernames.is_empty() && has(&self.cert_common_names),
NameKind::Unbound => false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum NameKind {
User,
Cn,
Unbound,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BlockPolicy {
pub subjects: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockSubjects {
pub posture: Posture,
pub subjects: Vec<BlockSubject>,
pub policies: Vec<BlockPolicy>,
}
impl BlockSubjects {
fn listing(&self, id: &str) -> BTreeSet<usize> {
self.policies
.iter()
.enumerate()
.filter(|(_, p)| p.subjects.iter().any(|s| s == id))
.map(|(i, _)| i)
.collect()
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Block {
pub namespace: String,
pub enabled: Option<bool>,
pub deny: Vec<BlockDeny>,
pub downsampling: Vec<BlockRule>,
pub subjects: Option<BlockSubjects>,
}
#[must_use]
pub fn check_block(face: &str, device: bool, block: &Block) -> Vec<Finding> {
let mut out = Vec::new();
if block.enabled == Some(false) {
out.push(Finding::new(Code::BlockDisabled, Some(face), "enabled"));
}
let ns = block.namespace.trim_matches('/');
let with_ns = |k: &str| {
if ns.is_empty() {
k.to_owned()
} else {
format!("{ns}/{k}")
}
};
let denied = if device {
ZK_CARVED
.iter()
.all(|k| zk_denied_on(&with_ns(k), &block.deny, |_, _| true))
&& zk_denied_on(&with_ns(ZK_INSTANCE), &block.deny, |f, m| {
!OWN_PAIRS.contains(&(f, m))
})
} else {
zk_denied_on(&with_ns(ZK_DENY), &block.deny, |_, _| true)
};
if !denied {
out.push(Finding::new(Code::ZkNotDenied, Some(face), "@zk"));
}
let parsed: Vec<Option<&keyexpr>> = block
.downsampling
.iter()
.map(|r| keyexpr::new(r.key_expr.as_str()).ok())
.collect();
for (j, r) in block.downsampling.iter().enumerate() {
if parsed[j].is_none_or(|k| k.as_str().contains('*')) {
out.push(Finding::new(
Code::WildcardDownsampling,
Some(face),
r.key_expr.clone(),
));
}
let hit = (0..j).any(|i| match (parsed[i], parsed[j]) {
(Some(a), Some(b)) => a.intersects(b),
_ => false,
});
if hit {
out.push(Finding::new(
Code::IntersectingDownsampling,
Some(face),
r.key_expr.clone(),
));
}
}
sort_findings(&mut out);
out
}
fn zk_denied_on(target: &str, deny: &[BlockDeny], pairs: impl Fn(&str, &str) -> bool) -> bool {
let Ok(target) = keyexpr::new(target) else {
return false;
};
FLOWS.iter().all(|flow| {
MESSAGES.iter().filter(|m| pairs(flow, m)).all(|m| {
deny.iter().any(|d| {
d.flows.iter().any(|f| f == flow)
&& d.messages.iter().any(|x| x == m)
&& d.key_exprs
.iter()
.any(|k| keyexpr::new(k.as_str()).is_ok_and(|k| k.includes(target)))
})
})
})
}
#[must_use]
pub fn check_subjects(name: &str, face: &Face, block: &BlockSubjects) -> Vec<Finding> {
let mut out = Vec::new();
let on_face: Vec<&BlockSubject> = block.subjects.iter().filter(|s| s.on_face(face)).collect();
let far_policies: BTreeSet<usize> = on_face
.iter()
.filter(|s| s.far_alone(&face.far))
.flat_map(|s| block.listing(&s.id))
.collect();
for s in &on_face {
let mut found = |code: Code| out.push(Finding::new(code, Some(name), s.id.clone()));
if s.bound() {
if !s.far_alone(&face.far) {
found(Code::NearSubjectOnFace);
}
continue;
}
if s.protocols()
.is_none_or(|l| l.iter().any(|x| !face.link_protocols.contains(x)))
{
found(Code::FaceSubjectBeyondFace);
}
let listed = block.listing(&s.id);
if listed.is_empty() || listed != far_policies {
found(Code::FaceSubjectMisplaced);
}
}
if block.posture == Posture::Allow {
for p in &face.link_protocols {
let selected = block.subjects.iter().any(|s| {
!s.bound()
&& s.interfaces.is_empty()
&& s.zids.is_empty()
&& s.protocols().is_some_and(|l| l.contains(p))
});
if !selected {
out.push(Finding::new(
Code::FaceSubjectMissing,
Some(name),
p.clone(),
));
}
}
}
sort_findings(&mut out);
out
}
#[must_use]
pub fn check_narrowing(policy: &FacePolicy, block: &BlockSubjects) -> Vec<Finding> {
let mut out = Vec::new();
if block.posture != Posture::Allow {
return out;
}
let mut names: BTreeSet<(&str, NameKind)> = BTreeSet::new();
for s in &block.subjects {
names.extend(s.usernames.iter().map(|u| (u.as_str(), NameKind::User)));
names.extend(
s.cert_common_names
.iter()
.map(|c| (c.as_str(), NameKind::Cn)),
);
}
for f in policy.faces.values() {
let bound = block.subjects.iter().any(|s| {
s.usernames
.iter()
.chain(&s.cert_common_names)
.any(|x| *x == f.far)
});
if !bound {
names.insert((f.far.as_str(), NameKind::Unbound));
}
}
let mut bare_names: BTreeSet<&str> = BTreeSet::new();
for (name, kind) in names {
let kept: Vec<String> =
narrowed(policy, |f| policy.faces[f].far == name).unwrap_or_else(|| {
policy
.binding
.protocols()
.iter()
.map(|p| (*p).to_owned())
.collect()
});
let bare = kept.iter().any(|p| {
!block
.subjects
.iter()
.any(|s| s.answers(name, kind) && s.selects(p))
});
if bare {
bare_names.insert(name);
}
}
for name in bare_names {
out.push(Finding::new(Code::NarrowedTooFar, None, name));
}
sort_findings(&mut out);
out
}
#[must_use]
pub fn narrowed(policy: &FacePolicy, is_far: impl Fn(&str) -> bool) -> Option<Vec<String>> {
let excluded: BTreeSet<&str> = policy
.faces
.iter()
.filter(|(name, _)| !is_far(name))
.flat_map(|(_, f)| f.link_protocols.iter().map(String::as_str))
.collect();
(!excluded.is_empty()).then(|| {
policy
.binding
.protocols()
.iter()
.filter(|p| !excluded.contains(*p))
.map(|p| (*p).to_owned())
.collect()
})
}
#[derive(Debug, Clone, Copy, Default)]
pub struct LintInput<'a> {
pub text: &'a str,
pub deployment: Option<&'a Deployment>,
pub windows: Option<&'a BTreeMap<String, u64>>,
pub block: Option<(&'a str, &'a Block)>,
}
#[must_use]
pub fn lint(input: &LintInput<'_>) -> Vec<Finding> {
let parsed = parse(input.text);
let mut out = parsed.findings;
let Some(policy) = parsed.policy else {
return out;
};
if let Some(d) = input.deployment {
match plan(&policy, d) {
Ok(plans) => out.extend(plans.into_iter().flat_map(|p| p.findings)),
Err(f) => out.extend(f),
}
if let Some(w) = input.windows {
out.extend(check_windows(&policy, d, w));
}
}
if let Some((face, block)) = input.block {
let device = policy.faces.get(face).is_some_and(|f| f.attach.is_device());
out.extend(check_block(face, device, block));
if let Some(s) = &block.subjects {
if let Some(f) = policy.faces.get(face) {
out.extend(check_subjects(face, f, s));
}
out.extend(check_narrowing(&policy, s));
}
}
sort_findings(&mut out);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn ke(s: &str) -> &keyexpr {
keyexpr::new(s).unwrap()
}
#[test]
fn a_binding_deserializes_by_its_name() {
for b in Binding::ALL {
let read: Binding = serde_json::from_value(Value::from(b.as_str())).unwrap();
assert_eq!(read, b);
assert_eq!(serde_json::to_value(b).unwrap(), Value::from(b.as_str()));
}
let e = serde_json::from_value::<Binding>(Value::from("zenoh-1.10.0"))
.unwrap_err()
.to_string();
assert!(
e.contains("zenoh-1.10.0")
&& e.contains("`zenoh-1.10.1`")
&& e.contains("`zenoh-1.10.2`")
&& e.contains("`zm-1.10.2-r1`"),
"{e}"
);
assert!(serde_json::from_value::<Binding>(Value::from(1)).is_err());
}
#[test]
fn a_binding_parses_by_its_name() {
assert_eq!(Binding::NAMES, Binding::ALL.map(Binding::as_str));
for b in Binding::ALL {
assert_eq!(b.as_str().parse::<Binding>(), Ok(b));
assert_eq!(b.to_string().parse::<Binding>(), Ok(b));
}
let e = "zenoh-1.10.0".parse::<Binding>().unwrap_err();
assert_eq!(e, UnknownBinding("zenoh-1.10.0".to_owned()));
assert_eq!(
e.to_string(),
"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> \
for a later release of the fork"
);
assert!("".parse::<Binding>().is_err());
assert!(
"Zenoh-1.10.1".parse::<Binding>().is_err(),
"names are exact"
);
}
#[test]
fn a_later_release_of_the_fork_names_its_binding() {
for name in ["zm-1.10.2-r2", "zm-1.10.2-r10", "zm-1.10.2-r123"] {
assert_eq!(Binding::parse(name), Some(Binding::Zm1_10_2R1), "{name}");
assert_eq!(name.parse::<Binding>(), Ok(Binding::Zm1_10_2R1), "{name}");
assert_eq!(
serde_json::from_value::<Binding>(Value::from(name)).ok(),
Some(Binding::Zm1_10_2R1),
"{name}"
);
}
for name in [
"zm-1.10.2-r0",
"zm-1.10.2-r01",
"zm-1.10.2-r",
"zm-1.10.2-r2x",
"zm-1.10.2-r-2",
"zm-1.10.3-r1",
"zm-1.10.2",
] {
assert_eq!(Binding::parse(name), None, "{name}");
}
let policy = |binding: &str| {
format!(
"profile = \"link.v2\"\nsystem = \"lab\"\nservices = [\"radio-a\"]\n\
binding = \"{binding}\"\n\n[transport]\nlease_ms = 240000\n\
keep_alive = 4\nwait_before_close_ms = 240000\n\
sequence = \"16bit\"\nbatch_bytes = 222\n\n[face.radio]\n\
far = \"ground\"\nattach = \"client\"\n\
select = {{ link_protocols = [\"unixsock-dgram\"] }}\n\
class = \"constrained\"\nexpose = \"link\"\n\
interval_s = 60\nmax_outage_s = 3600\nlink_bps = 2400\n\
loss_ppm = 0\narq = true\nreply_timeout_ms = 15000\n"
)
};
let r1 = parse(&policy("zm-1.10.2-r1"));
let r2 = parse(&policy("zm-1.10.2-r2"));
assert_eq!(
r2.findings, r1.findings,
"the same findings: none on unixsock-dgram"
);
let (r1, mut r2) = (r1.policy.expect("r1 reads"), r2.policy.expect("r2 reads"));
assert_eq!(r2.binding, Binding::Zm1_10_2R1);
assert_eq!(r2.binding_name, "zm-1.10.2-r2");
assert_eq!(r1.binding_name, "zm-1.10.2-r1");
r2.binding_name = r1.binding_name.clone();
assert_eq!(
r2, r1,
"but for its name, a policy naming r2 reads as one naming r1"
);
}
#[test]
fn zenoh_1_10_2_is_a_binding_that_reads_as_1_10_1() {
let (stock, next, fork) = (
Binding::Zenoh1_10_1,
Binding::Zenoh1_10_2,
Binding::Zm1_10_2R1,
);
assert_eq!(Binding::ALL, [stock, next, fork], "v2 §2.4's order");
assert_eq!(next.protocols(), stock.protocols());
assert!(!next.protocols().contains(&"unixsock-dgram"));
assert!(fork.protocols().contains(&"unixsock-dgram"));
assert_eq!(next.defaults(), stock.defaults());
assert_eq!(next.defaults().wait_before_close_ms, 5_000);
assert_ne!(next.defaults(), fork.defaults());
assert_eq!(
Binding::default(),
stock,
"a link.v1 policy reads as 1.10.1"
);
let policy = |protocol: &str| {
format!(
"profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
binding = \"zenoh-1.10.2\"\n[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
wait_before_close_ms = 10000\nsequence = \"16bit\"\nbatch_bytes = 222\n\
[face.rf]\nfar = \"ground\"\nattach = \"client\"\n\
select = {{ link_protocols = [\"{protocol}\"] }}\n\
class = \"constrained\"\nexpose = \"none\"\nmax_outage_s = 3600\n\
link_bps = 2400\nloss_ppm = 0\narq = true\nreply_timeout_ms = 15000\n"
)
};
let read = parse(&policy("unixsock-stream"));
assert!(read.findings.is_empty(), "{:?}", read.findings);
assert_eq!(read.policy.map(|p| p.binding), Some(next));
let refused = parse(&policy("unixsock-dgram"));
assert_eq!(
refused.findings.iter().map(|f| f.code).collect::<Vec<_>>(),
[Code::UnknownProtocol],
"{:?}",
refused.findings
);
}
#[test]
fn key_expression_facts() {
assert!(ke("zk2/*/*/m.v1/stream/a/**").includes(ke("zk2/h/s/m.v1/stream/a")));
assert!(ke(ZK_DENY).includes(ke("zk2/@zk/contract/m.v1/abc")));
assert!(ke(ZK_DENY).includes(ke("zk2/h/s/@zk/instance/0123456789abcdef")));
assert!(ke("**/@zk/**").includes(ke(ZK_DENY)));
assert!(!ke("zk2/*/*/m.v1/events/logs/*/**").includes(ke("zk2/h/s/m.v1/events/logs")));
assert!(ke("zk2/*/*/m.v1/events/logs/*/**").includes(ke("zk2/h/s/m.v1/events/logs/a/b")));
assert!(!ke("zk2/*/*/*/stream/**").includes(ke("zk2/h/s/m.v1/@stream/x")));
assert!(ke("zk2/*/*/*/@stream/**").includes(ke("zk2/h/s/m.v1/@stream/x")));
assert!(ke(ADV_DENY).includes(ke("zk2/h/s/m.v1/stream/x/@adv/pub/abc")));
}
#[test]
fn the_carve_lets_an_instance_key_cross_on_the_own_pairs_alone() {
let carve = zk_carve();
let denied = |key: &str, flow: &str, m: &str| {
carve.iter().any(|d| {
d.flows.contains(&flow)
&& d.messages.contains(&m)
&& d.key_exprs.iter().any(|k| ke(k).includes(ke(key)))
})
};
let instance = "zk2/lab/probe-a/@zk/instance/0123456789abcdef";
let mut open = Vec::new();
for flow in FLOWS {
for m in MESSAGES {
for key in [
"zk2/lab/probe-a/@zk/alive/probe.v1",
"zk2/lab/probe-a/@zk/member/0123456789abcdef/x",
"zk2/@zk/contract/probe.v1/abc",
] {
assert!(denied(key, flow, m), "{key} {flow} {m}");
}
if !denied(instance, flow, m) {
open.push((flow, m));
}
}
}
open.sort_unstable();
let mut own = OWN_PAIRS.to_vec();
own.sort_unstable();
assert_eq!(open, own);
assert!(
carve
.iter()
.flat_map(|d| &d.key_exprs)
.all(|k| k.starts_with("zk2/*/*/") || k == "zk2/@zk/**")
);
}
#[test]
fn keys_collapse_a_trailing_rest() {
assert_eq!(
key("r", &[Seg::Lit("x".into()), Seg::Rest], "/**"),
"r/x/*/**"
);
assert_eq!(key("r", &[], "/**"), "r/**");
assert_eq!(key("r", &[Seg::Lit("a".into())], "/*/**"), "r/a/*/**");
}
fn res(template: &str, annotations: Value) -> Res {
Res::new(
Template::parse(template).unwrap(),
KindToken::Stream,
serde_json::from_value(annotations).unwrap(),
)
}
#[test]
fn revisions_are_read_together_failing_closed() {
let a = vec![
res(
"x",
serde_json::json!({"link.exposure": "link", "freshness.ttl_s": 10}),
),
res(
"y",
serde_json::json!({"link.exposure": "link", "freshness.ttl_s": 10}),
),
res("w", serde_json::json!({"link.exposure": "LINK"})),
];
let b = vec![
res("x", serde_json::json!({"freshness.ttl_s": 4})),
res(
"y",
serde_json::json!({"link.exposure": "link", "freshness.ttl_s": 0}),
),
res("w", serde_json::json!({})),
res("z", serde_json::json!({"link.exposure": "link"})),
];
let (m, disagree) = merge(&[a, b]);
let read = |t: &str| {
let r = m.iter().find(|r| r.template.as_str() == t).unwrap();
(exposure_of_res(r), horizon(r).ttl().map(|d| d.as_secs()))
};
assert_eq!(read("x"), (Exposure::Host, Some(4)));
assert_eq!(read("y"), (Exposure::Link, None));
assert_eq!(read("z"), (Exposure::Link, None));
assert_eq!(disagree, BTreeSet::from([0]));
}
#[test]
fn link_v2_judges_each_revision_alone() {
let raw = res("s", serde_json::json!({"link.exposure": "link"}));
let mut packed = raw.clone();
packed.packed = true;
packed.block = true;
packed.longest_bytes = Some(300);
let mut timed = raw.clone();
timed.packed = true;
timed.longest_bytes = Some(400);
timed
.annotations
.insert(crate::timing::DEADLINE_MS.to_owned(), Value::from(2000));
for revs in [
[vec![raw.clone()], vec![packed.clone()], vec![timed.clone()]],
[vec![timed.clone()], vec![packed.clone()], vec![raw.clone()]],
] {
let (m, _) = merge(&revs);
let r = &m[0];
assert!(!r.packed, "one revision's raw type");
assert!(r.shape().timed, "one revision's deadline");
assert!(r.block);
assert_eq!(r.longest_bytes, Some(300), "the block revision's");
}
let (m, _) = merge(&[vec![packed.clone()], vec![timed.clone()]]);
assert!(m[0].packed, "packed in every revision");
let (m, _) = merge(&[vec![timed.clone()], vec![raw]]);
assert_eq!(m[0].longest_bytes, Some(400), "none block: the longest");
}
fn exposure_of_res(r: &Res) -> Exposure {
match exposure(kind_of(r.token), &r.annotations) {
Exposure::Invalid(_) => Exposure::Host,
e => e,
}
}
fn face(far: &str, protocols: &[&str]) -> Face {
Face {
far: far.to_owned(),
attach: Attach::Client,
link_protocols: protocols.iter().map(|p| (*p).to_owned()).collect(),
expose: Expose::Link,
interval_s: Some(1),
max_outage_s: 1,
batch_bytes: 1,
link_bps: 1,
lease_ms: DEFAULT_LEASE_MS,
loss_ppm: None,
arq: None,
reply_timeout_ms: None,
frames: None,
events: None,
horizon_s: None,
opens: Opens::Far,
}
}
#[test]
fn a_subject_is_narrowed_off_the_faces_it_is_not_far_of() {
let policy = |faces: Vec<(&str, Face)>| FacePolicy {
profile: Profile::V1,
system: "lab".into(),
services: vec![],
faces: faces.into_iter().map(|(n, f)| (n.to_owned(), f)).collect(),
binding: Binding::Zenoh1_10_1,
binding_name: Binding::Zenoh1_10_1.as_str().to_owned(),
transport: None,
catalog: None,
};
let two = policy(vec![
("radio", face("ground", &["unixsock-stream"])),
("sat", face("sat", &["serial", "unixpipe"])),
]);
let of = |p: &str| narrowed(&two, |name| two.faces[name].far == p);
assert_eq!(
of("local").unwrap(),
["tcp", "udp", "tls", "quic", "vsock", "ws"]
);
assert_eq!(
of("ground").unwrap(),
[
"tcp",
"udp",
"tls",
"quic",
"unixsock-stream",
"vsock",
"ws"
]
);
let one = policy(vec![("radio", face("ground", &["unixsock-stream"]))]);
assert_eq!(narrowed(&one, |_| true), None);
let all = policy(vec![("x", face("x", Binding::Zenoh1_10_1.protocols()))]);
assert_eq!(narrowed(&all, |_| false), Some(Vec::new()));
let fork = FacePolicy {
binding: Binding::Zm1_10_2R1,
binding_name: Binding::Zm1_10_2R1.as_str().to_owned(),
..policy(vec![("radio", face("ground", &["unixsock-stream"]))])
};
assert_eq!(
narrowed(&fork, |_| false).unwrap(),
[
"tcp",
"udp",
"tls",
"quic",
"serial",
"unixpipe",
"unixsock-dgram",
"vsock",
"ws"
]
);
}
#[test]
fn the_keep_alive_lint_is_exact() {
assert!(!flaps(240_000, 4, 50_000));
assert!(!flaps(120_000, 4, 50_000));
assert!(!flaps(1_080_000, 4, 50_000));
assert!(flaps(120_000, 2, 50_000));
assert!(flaps(60_000, 2, 50_000));
assert!(!flaps(3_600_000, 2, 0));
assert!(flaps(3_600_000, 1, 0));
assert!(!flaps(86_400, 4, 50_000));
assert!(flaps(86_399, 4, 50_000));
assert!(flaps(MAX_U32, MAX_KEEP_ALIVE, MAX_LOSS_PPM - 1));
assert!(!flaps(MAX_U32, MAX_KEEP_ALIVE, 0));
}
#[test]
fn a_bad_transport_refuses_a_good_face() {
let face = "[face.rf]\nfar = \"ground\"\nattach = \"client\"\n\
select = { link_protocols = [\"unixsock-stream\"] }\n\
class = \"constrained\"\nexpose = \"none\"\nmax_outage_s = 3600\n\
link_bps = 2400\nloss_ppm = 0\narq = true\nreply_timeout_ms = 15000\n";
let head = "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
binding = \"zenoh-1.10.1\"\n";
let good = "[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
wait_before_close_ms = 10000\nsequence = \"16bit\"\n";
let ok = parse(&format!("{head}{good}{face}"));
assert!(ok.policy.is_some(), "{:?}", ok.findings);
for (transport, code, at) in [
("", Code::TransportMissing, "transport"),
("transport = 1\n", Code::BadValue, "transport"),
(
&good.replace("lease_ms = 10000", "lease_ms = 0"),
Code::BadValue,
"transport.lease_ms",
),
(
&good.replace("lease_ms = 10000\n", ""),
Code::MissingField,
"transport.lease_ms",
),
(
&format!("{good}batch_bytes = 65536\n"),
Code::BadValue,
"transport.batch_bytes",
),
] {
let p = parse(&format!("{head}{transport}{face}"));
assert!(p.policy.is_none(), "{transport:?}");
assert!(
p.findings
.iter()
.any(|f| f.code == code && f.at == at && f.face.is_none()),
"{transport:?}: {:?}",
p.findings
);
}
}
#[test]
fn wait_under_lease_reads_integers_and_a_wrong_type_differs() {
let p = parse(
"profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
binding = \"zenoh-1.10.1\"\n[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
wait_before_close_ms = 10000\nsequence = \"32bit\"\n[face.rf]\n\
far = \"ground\"\nattach = \"client\"\n\
select = { link_protocols = [\"unixsock-stream\"] }\nclass = \"constrained\"\n\
expose = \"none\"\nmax_outage_s = 3600\nlink_bps = 1000000\nloss_ppm = 0\n\
arq = true\nreply_timeout_ms = 15000\n",
)
.policy
.expect("a policy");
let wbc = TransportKey::WaitBeforeClose.path();
let lease = TransportKey::Lease.path();
let found = |pairs: &[(&str, Value)]| -> Vec<(&'static str, String)> {
let stated = StatedTransport(
pairs
.iter()
.map(|(k, v)| ((*k).to_owned(), v.clone()))
.chain([("timestamping/enabled".to_owned(), Value::from(false))])
.collect(),
);
check_transport(&p, &stated, None)
.into_iter()
.map(|f| (f.code.as_str(), f.at))
.collect()
};
let at = || "transport.wait_before_close_ms".to_owned();
let differs = || ("transport_differs", at());
let under = || ("wait_under_lease", at());
assert_eq!(found(&[(wbc, Value::from(10_000_000u64))]), []);
assert_eq!(found(&[(wbc, Value::from(u64::MAX))]), [differs()]);
assert_eq!(found(&[(wbc, Value::from(-1i64))]), [differs(), under()]);
assert_eq!(found(&[(wbc, Value::from("10000000"))]), [differs()]);
assert_eq!(found(&[(wbc, Value::from(1.0e7))]), [differs()]);
assert_eq!(
found(&[
(lease, Value::from("10000")),
(wbc, Value::from(10_000_000u64))
]),
[("transport_differs", "transport.lease_ms".to_owned())]
);
}
#[test]
fn a_null_reads_as_left_out_at_the_interests_timeout_alone() {
let policy = |interests_ms: u64| {
parse(&format!(
"profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
binding = \"zenoh-1.10.1\"\n[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
wait_before_close_ms = 10000\nsequence = \"32bit\"\n\
interests_timeout_ms = {interests_ms}\n[face.rf]\n\
far = \"ground\"\nattach = \"client\"\n\
select = {{ link_protocols = [\"unixsock-stream\"] }}\nclass = \"constrained\"\n\
expose = \"none\"\nmax_outage_s = 3600\nlink_bps = 1000000\nloss_ppm = 0\n\
arq = true\nreply_timeout_ms = 15000\n"
))
.policy
.expect("a policy")
};
let router = |null_at: TransportKey| {
let mut tree = serde_json::json!({
"transport": {
"link": {"tx": {
"lease": 10_000, "keep_alive": 4, "batch_size": 65_535,
"sequence_number_resolution": "32bit",
"queue": {"congestion_control": {"block": {
"wait_before_close": 10_000_000,
}}},
}},
"unicast": {"open_timeout": 10_000, "accept_timeout": 10_000},
},
"routing": {"interests": {"timeout": 10_000}},
"timestamping": {"enabled": false},
});
let mut node = &mut tree;
for part in null_at.path().split('/') {
node = node.get_mut(part).expect("the path");
}
*node = Value::Null;
StatedTransport::read(&tree)
};
let found = |p: &FacePolicy, r: &StatedTransport| -> Vec<(&'static str, String)> {
check_transport(p, r, None)
.into_iter()
.map(|f| (f.code.as_str(), f.at))
.collect()
};
let defaults = Binding::Zenoh1_10_1.defaults();
let interests = TransportKey::InterestsTimeout;
let r = router(interests);
assert_eq!(r.0.get(interests.path()), Some(&Value::Null));
assert!(r.null_left_out(interests));
assert!(!r.states(interests));
assert_eq!(r.runs(interests, &defaults), Value::from(10_000u64));
assert_eq!(found(&policy(10_000), &r), []);
assert_eq!(
found(&policy(40_000), &r),
[("transport_differs", interests.at())]
);
assert_eq!(
r.runs(interests, &Binding::Zm1_10_2R1.defaults()),
Value::from(10_000u64)
);
for key in TransportKey::ALL {
if key == interests {
continue;
}
let r = router(key);
assert!(!r.null_left_out(key), "{}", key.key());
assert!(r.states(key), "{}", key.key());
assert_eq!(r.runs(key, &defaults), Value::Null, "{}", key.key());
assert_eq!(
found(&policy(10_000), &r),
[("transport_differs", key.at())],
"{}",
key.key()
);
}
let omitted = StatedTransport::default();
assert!(!omitted.states(interests) && !omitted.null_left_out(interests));
assert_eq!(
omitted.runs(interests, &defaults),
r.runs(interests, &defaults)
);
}
#[test]
fn a_routers_timestamping_is_read_at_its_mode() {
let stamps = |mode: Option<&str>, enabled: Option<Value>| {
let mut m = BTreeMap::new();
if let Some(mode) = mode {
m.insert("mode".to_owned(), Value::from(mode));
}
if let Some(e) = enabled {
m.insert("timestamping/enabled".to_owned(), e);
}
StatedTransport(m).stamps()
};
assert!(stamps(None, None), "zenohd's router stamps by default");
assert!(stamps(Some("router"), None));
assert!(!stamps(Some("peer"), None));
assert!(!stamps(Some("client"), None));
assert!(stamps(Some("peer"), Some(Value::from(true))));
assert!(!stamps(Some("router"), Some(Value::from(false))));
let off = serde_json::json!({"router": false, "peer": false});
assert!(!stamps(None, Some(off.clone())));
assert!(!stamps(Some("peer"), Some(off)));
assert!(stamps(
Some("router"),
Some(serde_json::json!({"peer": false}))
));
assert!(stamps(
Some("peer"),
Some(serde_json::json!({"peer": true}))
));
let written = StatedTransport::read(&serde_json::json!({
"mode": "router",
"timestamping": {"enabled": {"router": false, "peer": false}},
}));
assert!(!written.stamps());
assert_eq!(TIMESTAMPING_OFF.len(), 2);
for path in ["timestamping/enabled/router", "timestamping/enabled/peer"] {
assert!(
TIMESTAMPING_OFF.contains(&(path, false)),
"{path} in {TIMESTAMPING_OFF:?}"
);
}
assert!(stamps(Some("router"), Some(serde_json::Value::Null)));
assert!(stamps(
Some("router"),
Some(serde_json::json!({"router": null, "peer": false}))
));
assert!(!stamps(
Some("peer"),
Some(serde_json::json!({"router": false, "peer": null}))
));
let null_mode = StatedTransport::read(&serde_json::json!({
"mode": null,
"timestamping": {"enabled": {"peer": false}},
}));
assert!(null_mode.stamps(), "a `null` mode runs as a router");
for refused in [
serde_json::json!("bogus"),
serde_json::json!("Router"),
serde_json::json!(5),
] {
let read = |enabled: Option<Value>| {
let mut m = BTreeMap::from([("mode".to_owned(), refused.clone())]);
if let Some(e) = enabled {
m.insert("timestamping/enabled".to_owned(), e);
}
StatedTransport(m).stamps()
};
assert!(read(None), "{refused}: a router's default, on");
assert!(
read(Some(serde_json::json!({"peer": false}))),
"{refused}: the router's value left out"
);
assert!(
!read(Some(serde_json::json!({"router": false, "peer": false}))),
"{refused}: off at the mode read"
);
assert!(!read(Some(Value::from(false))), "{refused}");
assert!(
read(Some(serde_json::json!({"bogus": false, "5": false}))),
"{refused}"
);
}
}
#[test]
fn the_keep_alive_interval_says_when_it_rounds() {
let t = |lease_ms, keep_alive| Transport {
lease_ms,
keep_alive,
..Binding::Zenoh1_10_1.defaults()
};
assert_eq!(t(240_000, 4).keep_alive_interval_words(), "60000 ms");
assert_eq!(t(2_000, 3).keep_alive_interval_words(), "about 666 ms");
}
#[test]
fn a_puts_allowance_is_the_measured_bound() {
let lane = ["unixsock-stream".to_owned()];
let block = PutQos {
block: true,
..PutQos::DATA_DROP
};
let express = PutQos {
express: true,
..PutQos::DATA_DROP
};
let low = PutQos {
priority_data: false,
..PutQos::DATA_DROP
};
for (qos, bit16, bit32) in [
(PutQos::DATA_DROP, 212, 210),
(block, 210, 208),
(express, 210, 208),
(low, 208, 206),
] {
for (sequence, largest) in [(Sequence::Bit16, bit16), (Sequence::Bit32, bit32)] {
assert!(
fits_batch(largest, 222, qos, sequence, &lane),
"{qos:?} {sequence:?}"
);
assert!(!fits_batch(largest + 1, 222, qos, sequence, &lane));
}
}
assert_eq!(allowance(100, PutQos::DATA_DROP, Sequence::Bit16, &lane), 9);
assert_eq!(
allowance(16_384, PutQos::DATA_DROP, Sequence::Bit16, &lane),
11
);
let serial = ["serial".to_owned(), "ws".to_owned()];
assert_eq!(
allowance(200, PutQos::DATA_DROP, Sequence::Bit16, &serial),
8
);
let mixed = ["serial".to_owned(), "udp".to_owned()];
assert_eq!(
allowance(200, PutQos::DATA_DROP, Sequence::Bit16, &mixed),
10
);
assert_eq!(allowance(200, PutQos::DATA_DROP, Sequence::Bit8, &lane), 9);
assert_eq!(
allowance(200, PutQos::DATA_DROP, Sequence::Bit64, &lane),
13
);
}
#[test]
fn the_sequence_window_and_the_handshake_are_integer_arithmetic() {
assert!(!window_filled(Sequence::Bit16, 222, 240_000, 2_400));
assert!(window_filled(Sequence::Bit8, 222, 240_000, 2_400));
assert!(under_handshake(10_000, 293));
assert!(!under_handshake(40_000, 293));
assert!(!under_handshake(2_560, 2_400));
assert!(under_handshake(2_559, 2_400));
assert!(!reply_short(15_000, 2_400, 222));
assert!(reply_short(11_000, 2_400, 222));
}
#[test]
fn an_empty_link_protocol_list_reads_as_absent() {
let radio = face("ground", &["unixsock-stream"]);
let block = |links: Option<Vec<String>>| BlockSubjects {
posture: Posture::Deny,
subjects: vec![BlockSubject {
id: "local".into(),
usernames: vec!["local".into()],
link_protocols: links,
..BlockSubject::default()
}],
policies: vec![BlockPolicy {
subjects: vec!["local".into()],
}],
};
let found = |links| check_subjects("radio", &radio, &block(links));
assert_eq!(found(Some(Vec::new())), found(None));
assert_eq!(found(None).len(), 1);
}
#[test]
fn the_batch_against_the_lease_is_integer_arithmetic() {
assert!(within_lease(1000, 2400, 10_000));
assert!(!within_lease(1024, 2400, 10_000));
assert!(within_lease(65_535, MAX_U32, MAX_U32));
}
#[test]
fn a_far_side_reads_its_face_of_a_link_v2_policy() {
use std::time::Duration;
let text = "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
binding = \"zenoh-1.10.1\"\n\
[transport]\nlease_ms = 240000\nkeep_alive = 4\n\
wait_before_close_ms = 240000\nsequence = \"16bit\"\nbatch_bytes = 222\n\
[face.rf]\nfar = \"ground\"\nattach = \"client\"\n\
select = { link_protocols = [\"unixsock-stream\"] }\n\
class = \"constrained\"\nexpose = \"none\"\nmax_outage_s = 3600\n\
link_bps = 2400\nloss_ppm = 50000\narq = false\nreply_timeout_ms = 15000\n";
let parsed = parse(text);
let policy = parsed.policy.expect("a policy");
let far = policy.far_side("rf").expect("its face");
assert_eq!(far.reply_timeout(), Duration::from_secs(15));
assert_eq!(
far.at_least(Duration::from_secs(1)),
Duration::from_secs(15)
);
assert_eq!(
far.at_least(Duration::from_secs(30)),
Duration::from_secs(30)
);
assert!(
far.redeclares(),
"no ARQ: a silent subscription is declared again"
);
assert_eq!(
FarSide::silence(Duration::from_secs(300)),
Duration::from_secs(600)
);
let keys = far.session_keys();
assert_eq!(keys.len(), 8);
assert_eq!(
keys[2],
(TransportKey::WaitBeforeClose, Value::from(240_000_000u64)),
"wait_before_close in µs"
);
assert!(matches!(
policy.far_side("sbd"),
Err(FarSideRefusal::NoFace { faces, .. }) if faces == ["rf"]
));
let v1 = FacePolicy {
profile: Profile::V1,
transport: None,
..policy
};
assert_eq!(v1.far_side("rf"), Err(FarSideRefusal::NotV2));
}
}