Skip to main content

dora_core/
topics.rs

1use std::net::{IpAddr, Ipv4Addr, SocketAddr};
2
3#[cfg(feature = "zenoh")]
4use tracing::warn;
5
6pub const LOCALHOST: IpAddr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
7pub const DORA_DAEMON_LOCAL_LISTEN_PORT_DEFAULT: u16 = 53291;
8/// Env var to override the daemon's local listener port for dynamic nodes.
9pub const DORA_DAEMON_LOCAL_LISTEN_PORT_ENV: &str = "DORA_DAEMON_LOCAL_LISTEN_PORT";
10pub const DORA_COORDINATOR_PORT_WS_DEFAULT: u16 = 6013;
11
12/// Comma-separated zenoh endpoints a spawned node should connect to, injected by
13/// the daemon: the daemon's own listener plus the listeners of the nodes this one
14/// consumes from (see [`DORA_ZENOH_LISTEN_ENV`]).
15///
16/// The daemon's listener is loopback for a single-machine deployment, but may be
17/// a routable address when the daemon is part of a cluster (see
18/// [`zenoh_bind_address_for`]). Either way it is on this node's own host, so the
19/// node can always reach it.
20///
21/// Lets nodes bootstrap zenoh peer discovery without multicast (dev containers,
22/// locked-down hosts, many CI runners), and — since zenoh 1.9 removed peer
23/// relaying — establishes the node↔node links the dataflow needs *explicitly*
24/// rather than leaving them to gossip's best-effort autoconnect.
25pub const DORA_ZENOH_CONNECT_ENV: &str = "DORA_ZENOH_CONNECT";
26
27/// Loopback zenoh endpoint a spawned node should listen on, injected by the
28/// daemon so this node's consumers can dial it directly (they receive it via
29/// their [`DORA_ZENOH_CONNECT_ENV`]).
30///
31/// Peers in zenoh 1.9 do not relay for each other, so a producer and consumer
32/// that never form a direct link simply cannot exchange data — no amount of
33/// waiting fixes it. Assigning each node a known listener makes those links
34/// deterministic instead of racy.
35///
36/// **Stays single-valued.** A node that also needs a routable listener gets it
37/// via [`DORA_ZENOH_LISTEN_EXTRA_ENV`] rather than as a second entry here,
38/// because a node binary built before that variable existed pushes this value
39/// into `listen/endpoints` verbatim as *one* locator. A comma-separated value
40/// would therefore be rejected wholesale by such a node, costing it the
41/// loopback listener too and partitioning it from its same-machine consumers.
42/// Keeping the old variable's shape means an older node degrades to
43/// loopback-only — same-machine links keep working, cross-machine ones fall
44/// back to the daemon path — instead of losing every link (dora-rs/dora#2742).
45pub const DORA_ZENOH_LISTEN_ENV: &str = "DORA_ZENOH_LISTEN";
46
47/// Additional zenoh endpoints a spawned node should listen on, beyond the
48/// loopback one in [`DORA_ZENOH_LISTEN_ENV`]. Comma-separated; injected by the
49/// daemon only for a node that has a consumer under another daemon.
50///
51/// Split out from [`DORA_ZENOH_LISTEN_ENV`] for forward compatibility — see the
52/// note there. A node that does not know this variable simply ignores it.
53pub const DORA_ZENOH_LISTEN_EXTRA_ENV: &str = "DORA_ZENOH_LISTEN_EXTRA";
54
55/// Opt out of zenoh multicast scouting for this process, regardless of whether
56/// explicit connect endpoints replaced it.
57///
58/// Set to `off`, `0`, `false`, or `no` to disable. Any other value (including
59/// unset) leaves the default behaviour, where multicast is dropped only once
60/// [`DORA_ZENOH_CONNECT_ENV`] gives the session something to dial instead.
61///
62/// Exists for networks where the scouting socket itself is the problem: a busy
63/// DDS/ROS2 multicast graph can keep zenoh from binding its scouting group,
64/// which fails `zenoh::open` outright. Disabling scouting sidesteps that bind
65/// entirely — but it removes a discovery mechanism, so a session that has no
66/// connect endpoints *and* no multicast can reach nobody. Set it only where
67/// every link is established explicitly (the daemon injects
68/// [`DORA_ZENOH_CONNECT_ENV`] into the nodes it spawns, so those are covered).
69///
70/// The daemon sets this on the nodes it spawns when started with
71/// `--zenoh-no-multicast`, so a single flag covers the whole process tree.
72pub const DORA_ZENOH_MULTICAST_ENV: &str = "DORA_ZENOH_MULTICAST";
73
74/// Pid of the process whose death must end this node, injected **only** by a
75/// daemon that runs in-process with whoever started it: `Daemon::run_dataflow`
76/// and its callers — `dora run`, `dora daemon --run-dataflow`, and embedders
77/// that drive one dataflow to completion.
78///
79/// There, the one process is coordinator, daemon and node-parent at once, so
80/// its death is the end of the dataflow by definition. Every teardown path
81/// dora has is cooperative and so cannot survive `SIGKILL`, which is neither
82/// catchable nor blockable: no CLI- or daemon-side code runs after it. Nodes
83/// are deliberately spawned as process-group leaders (so a terminal `Ctrl-C`
84/// cannot kill them out from under the daemon), which also means an orphan
85/// keeps running with `ppid 1` in a group of its own — unreachable by both
86/// inherited signal delivery and a group-kill of the parent. Handing the node
87/// the pid lets it notice on its own (dora-rs/dora#2856).
88///
89/// Deliberately NOT set on the `dora up` + `dora start` path: there the parent
90/// is a long-lived daemon whose lifetime is decoupled from its nodes on
91/// purpose — a node survives a coordinator drop, a reconnect, and a watchdog
92/// disconnect while keeping its pid (dora-rs/dora#2029). Tying node lifetime
93/// to that parent would break exactly the property `daemon-reconnect-e2e`
94/// asserts.
95pub const DORA_RUN_PARENT_PID_ENV: &str = "DORA_RUN_PARENT_PID";
96
97/// Zenoh's own config-file override, honored by
98/// [`open_zenoh_session_with_listen`].
99///
100/// Takes precedence over every `DORA_ZENOH_*` variable: when it is set the
101/// session is built entirely from the named file, so the connect/listen plan
102/// and the multicast decision are never read. That makes it a full bypass of
103/// the daemon's node wiring, which is why the daemon refuses it from a
104/// descriptor's `env:` (#2944) while still honoring it from its own
105/// environment — the documented way to point a whole deployment at a custom
106/// zenoh config.
107#[cfg(feature = "zenoh")]
108pub const ZENOH_CONFIG_PATH_ENV: &str = zenoh::Config::DEFAULT_CONFIG_PATH_ENV;
109
110/// Whether a session may discover peers by multicast scouting.
111///
112/// Spelled as an enum rather than a bool because the concept flips polarity at
113/// every hop it crosses — `--zenoh-no-multicast`, `DORA_ZENOH_MULTICAST=off`,
114/// `scouting/multicast/enabled=false` — and an inverted bool would not fail a
115/// test, it would silently partition the dataflow.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
117pub enum MulticastScouting {
118    /// Scout unless explicit connect endpoints replace it. The default
119    /// everywhere; [`DORA_ZENOH_MULTICAST_ENV`] can still turn it off.
120    #[default]
121    Allowed,
122    /// The caller establishes every link explicitly and wants no scouting.
123    Disabled,
124}
125
126/// Whether [`DORA_ZENOH_MULTICAST_ENV`] asks for multicast scouting to be off.
127#[cfg(feature = "zenoh")]
128fn multicast_disabled_by_env() -> bool {
129    multicast_disabled_by_value(std::env::var(DORA_ZENOH_MULTICAST_ENV).ok().as_deref())
130}
131
132/// The effective decision for a process that also has its own request.
133///
134/// [`open_zenoh_session_with_listen`] ORs the caller's request with
135/// [`DORA_ZENOH_MULTICAST_ENV`], so a process that has to *forward* its
136/// decision — the daemon, to the nodes it spawns — must OR them the same way.
137/// Forwarding only its own flag drops the environment half, leaving nodes
138/// scouting by multicast in exactly the environments where the variable was
139/// set to stop them.
140#[cfg(feature = "zenoh")]
141pub fn multicast_disabled(requested_off: bool) -> bool {
142    requested_off || multicast_disabled_by_env()
143}
144
145/// Parse a [`DORA_ZENOH_MULTICAST_ENV`] value (`None` when the var is unset).
146///
147/// Split from [`multicast_disabled_by_env`] so it is testable without mutating
148/// the process environment, which is `unsafe` in edition 2024 and racy against
149/// other tests in the same binary.
150#[cfg(feature = "zenoh")]
151fn multicast_disabled_by_value(value: Option<&str>) -> bool {
152    matches!(
153        value.map(|v| v.trim().to_ascii_lowercase()).as_deref(),
154        Some("off" | "0" | "false" | "no")
155    )
156}
157
158/// Split a comma-separated endpoint list env var, ignoring empty entries.
159#[cfg(feature = "zenoh")]
160fn split_endpoints(value: &str) -> impl Iterator<Item = String> + '_ {
161    value
162        .split(',')
163        .map(str::trim)
164        .filter(|s| !s.is_empty())
165        .map(String::from)
166}
167
168/// Assemble a node's listen endpoints from the two env vars the daemon sets.
169///
170/// Split across two variables rather than one comma-separated value for
171/// forward compatibility — see [`DORA_ZENOH_LISTEN_EXTRA_ENV`]. Both are run
172/// through [`split_endpoints`] so a hand-set list in either keeps working, and
173/// so the loopback entry stays first: `listen/endpoints` order is what decides
174/// which locator a same-machine consumer picks, and loopback is the one whose
175/// transport can carry shared memory.
176#[cfg(feature = "zenoh")]
177fn listen_endpoints_from_env(listen: Option<&str>, extra: Option<&str>) -> Vec<String> {
178    listen
179        .into_iter()
180        .chain(extra)
181        .flat_map(split_endpoints)
182        .collect()
183}
184
185/// Path to a JSON5 file whose contents are layered on top of the zenoh config
186/// dora computes.
187///
188/// The additive counterpart to [`ZENOH_CONFIG_PATH_ENV`], which replaces the
189/// whole config — including the per-node connect/listen plan the daemon builds,
190/// so a router named there ends up relaying even same-machine traffic. An
191/// overlay keeps that plan and adds to it, which is what "point this deployment
192/// at my routers" actually means. Setting both is refused rather than merged.
193///
194/// Inherited by spawned nodes (like [`ZENOH_CONFIG_PATH_ENV`]) so one variable
195/// covers a whole process tree, and refused from a descriptor's `env:` for the
196/// same reason: it is deployment wiring, not per-node configuration.
197#[cfg(feature = "zenoh")]
198pub const DORA_ZENOH_CONFIG_OVERLAY_ENV: &str = "DORA_ZENOH_CONFIG_OVERLAY";
199
200/// Environment variable to override the unicast open timeout (in milliseconds) for Zenoh transports.
201#[cfg(feature = "zenoh")]
202pub const DORA_ZENOH_OPEN_TIMEOUT_MS_ENV: &str = "DORA_ZENOH_OPEN_TIMEOUT_MS";
203
204/// Default timeout (in milliseconds) to bound unicast transport opening (`transport/unicast/open_timeout`).
205///
206/// In Zenoh 1.9, `TransportManager::open_transport_unicast` wraps link opening and handshakes
207/// in `tokio::time::timeout(open_timeout, ...)`. During teardown, `Runtime::close` blocks on any
208/// in-flight dial because the cancellation token is only selected against the sleep between
209/// retries, not against the dial itself.
210///
211/// 1000 ms (1 s) bounds the teardown hang when an unreachable peer is being dialed without
212/// prematurely aborting connections on local networks.
213///
214/// Note on asymmetry: `accept_timeout` stays at Zenoh's default (10 s) while `open_timeout`
215/// drops to 1 s. This asymmetry is intentional: accepting an inbound connection does not
216/// actively block local teardown on a hung remote dial, whereas an in-flight outgoing open does.
217///
218/// Note on overlays: users of [`DORA_ZENOH_CONFIG_OVERLAY_ENV`] inherit this default but can
219/// override it in their JSON5 overlay since `overlay.apply()` runs last.
220///
221/// A WAN peer behind ~200 ms RTT spends roughly three round-trips in TCP connect plus
222/// InitSyn/InitAck/OpenSyn/OpenAck, so 1 s leaves little headroom under packet loss.
223/// Operators can raise this via [`DORA_ZENOH_OPEN_TIMEOUT_MS_ENV`] or via a custom overlay.
224#[cfg(feature = "zenoh")]
225pub const DEFAULT_ZENOH_UNICAST_OPEN_TIMEOUT_MS: u64 = 1000;
226
227/// Parse the unicast open timeout in milliseconds, falling back to [`DEFAULT_ZENOH_UNICAST_OPEN_TIMEOUT_MS`]
228/// if absent or invalid.
229///
230/// Zero counts as invalid: zenoh wraps every dial in `tokio::time::timeout`, so a
231/// zero deadline fails any connection that is not established on its first poll.
232#[cfg(feature = "zenoh")]
233pub(crate) fn parse_zenoh_open_timeout(raw: Option<&str>) -> u64 {
234    match raw {
235        Some(val) => match val.trim().parse::<std::num::NonZeroU64>() {
236            Ok(parsed) => parsed.get(),
237            Err(err) => {
238                warn!(
239                    "invalid {DORA_ZENOH_OPEN_TIMEOUT_MS_ENV}={val:?} ({err}); \
240                     falling back to default {DEFAULT_ZENOH_UNICAST_OPEN_TIMEOUT_MS} ms"
241                );
242                DEFAULT_ZENOH_UNICAST_OPEN_TIMEOUT_MS
243            }
244        },
245        None => DEFAULT_ZENOH_UNICAST_OPEN_TIMEOUT_MS,
246    }
247}
248
249/// Retrieve the unicast open timeout in milliseconds from [`DORA_ZENOH_OPEN_TIMEOUT_MS_ENV`],
250/// or [`DEFAULT_ZENOH_UNICAST_OPEN_TIMEOUT_MS`] if not set.
251#[cfg(feature = "zenoh")]
252pub(crate) fn zenoh_unicast_open_timeout_ms() -> u64 {
253    let raw = std::env::var(DORA_ZENOH_OPEN_TIMEOUT_MS_ENV).ok();
254    parse_zenoh_open_timeout(raw.as_deref())
255}
256
257/// Operator-supplied zenoh settings to layer onto dora's computed config.
258///
259/// Split into the two endpoint lists, which **merge** with what dora computed,
260/// and everything else, which **replaces** it. Merging is what makes the
261/// overlay additive where it matters: naming a router under
262/// `connect.endpoints` adds a path to it without deleting the direct node links
263/// dora planned, which is exactly the difference from a wholesale
264/// [`ZENOH_CONFIG_PATH_ENV`].
265#[cfg(feature = "zenoh")]
266#[derive(Debug, Default, Clone)]
267pub struct ZenohOverlay {
268    /// Extra peers to dial, appended to dora's `connect/endpoints`.
269    pub connect_endpoints: Vec<String>,
270    /// Extra addresses to bind, appended to dora's `listen/endpoints`.
271    pub listen_endpoints: Vec<String>,
272    /// Every other setting, applied after dora's own inserts.
273    rest: serde_json::Map<String, serde_json::Value>,
274}
275
276#[cfg(feature = "zenoh")]
277impl ZenohOverlay {
278    /// Read the overlay named by [`DORA_ZENOH_CONFIG_OVERLAY_ENV`], if any.
279    ///
280    /// A named file that cannot be read or parsed is a hard error: the operator
281    /// asked for these settings, and a session silently opened without them is
282    /// the kind of "runs but talks to nobody" outcome that takes hours to
283    /// diagnose.
284    pub fn from_env() -> eyre::Result<Option<Self>> {
285        let Some(path) = std::env::var_os(DORA_ZENOH_CONFIG_OVERLAY_ENV) else {
286            return Ok(None);
287        };
288        Self::from_path(std::path::Path::new(&path)).map(Some)
289    }
290
291    /// Read the overlay file at `path`, with the same errors as [`Self::from_env`].
292    pub fn from_path(path: &std::path::Path) -> eyre::Result<Self> {
293        use eyre::Context;
294
295        let contents = std::fs::read_to_string(path).wrap_err_with(|| {
296            format!(
297                "failed to read the zenoh config overlay at `{}` named by {}",
298                path.display(),
299                DORA_ZENOH_CONFIG_OVERLAY_ENV
300            )
301        })?;
302        Self::parse(&contents)
303            .wrap_err_with(|| format!("invalid zenoh config overlay at `{}`", path.display()))
304    }
305
306    /// Parse an overlay from JSON5 — zenoh's own config dialect, so an operator
307    /// can paste a fragment of a zenoh config file, comments and all.
308    pub fn parse(json5_str: &str) -> eyre::Result<Self> {
309        use eyre::{Context, eyre};
310
311        let value: serde_json::Value = json5::from_str(json5_str)
312            .map_err(|err| eyre!("{err}"))
313            .wrap_err(
314                "overlay must be a JSON5 object of zenoh config keys, e.g. \
315                 `{ connect: { endpoints: [\"tcp/10.0.0.1:7447\"] } }`",
316            )?;
317        let serde_json::Value::Object(mut object) = value else {
318            eyre::bail!("overlay must be a JSON5 object, not a bare value");
319        };
320
321        let mut overlay = Self::default();
322        for (key, endpoints) in [
323            ("connect", &mut overlay.connect_endpoints),
324            ("listen", &mut overlay.listen_endpoints),
325        ] {
326            let Some(serde_json::Value::Object(section)) = object.get_mut(key) else {
327                continue;
328            };
329            // Taken out of `rest` so the merged list survives: re-inserting the
330            // section wholesale afterwards would overwrite it.
331            let Some(value) = section.remove("endpoints") else {
332                continue;
333            };
334            let serde_json::Value::Array(list) = value else {
335                eyre::bail!("`{key}.endpoints` must be an array of endpoint strings");
336            };
337            for entry in list {
338                match entry {
339                    serde_json::Value::String(endpoint) => endpoints.push(endpoint),
340                    other => eyre::bail!(
341                        "`{key}.endpoints` must contain endpoint strings, found `{other}`"
342                    ),
343                }
344            }
345            // An emptied section would otherwise be re-inserted as `{}`.
346            if section.is_empty() {
347                object.remove(key);
348            }
349        }
350        overlay.rest = object;
351        Ok(overlay)
352    }
353
354    /// Apply everything except the endpoint lists, which the caller has already
355    /// merged into its own.
356    ///
357    /// Each setting is inserted at its deepest path, so an overlay touching one
358    /// subkey leaves its siblings alone. A path zenoh rejects is retried one
359    /// level up, because some sections only accept a whole-object write —
360    /// `insert_json5("gateway/south", ..)` is refused where
361    /// `insert_json5("gateway", ..)` is accepted (dora-rs/dora#2721).
362    fn apply(&self, config: &mut zenoh::Config) -> eyre::Result<()> {
363        for (key, value) in &self.rest {
364            insert_overlay_value(config, key, value)?;
365        }
366        Ok(())
367    }
368}
369
370/// Insert one overlay value, descending into objects and falling back to a
371/// whole-object write when a subpath is rejected. See [`ZenohOverlay::apply`].
372#[cfg(feature = "zenoh")]
373fn insert_overlay_value(
374    config: &mut zenoh::Config,
375    path: &str,
376    value: &serde_json::Value,
377) -> eyre::Result<()> {
378    if let serde_json::Value::Object(fields) = value
379        && !fields.is_empty()
380    {
381        let mut written = true;
382        for (field, child) in fields {
383            if insert_overlay_value(config, &format!("{path}/{field}"), child).is_err() {
384                written = false;
385                break;
386            }
387        }
388        if written {
389            return Ok(());
390        }
391        // Falling through re-writes the fields that did land, with the same
392        // values — `value` still contains them — so a partial descent is not
393        // left half-applied.
394    }
395    config
396        .insert_json5(path, &value.to_string())
397        .map_err(|err| eyre::eyre!("failed to apply zenoh config overlay key `{path}`: {err}"))
398}
399
400#[cfg(feature = "zenoh")]
401pub async fn open_zenoh_session() -> eyre::Result<zenoh::Session> {
402    // Nodes and the coordinator have no in-process way to know, so
403    // [`DORA_ZENOH_MULTICAST_ENV`] (honored inside) is their only channel.
404    let (session, _) = open_zenoh_session_with_listen(ZenohSessionParams::default()).await?;
405    Ok(session)
406}
407
408/// How a dora process wants its zenoh session wired.
409///
410/// A struct rather than a parameter list because every field is optional and
411/// most callers set one of them: the positional form made
412/// `open_zenoh_session_with_listen(None, None, None, Allowed)` a common sight,
413/// where a misplaced `None` is a silent partition rather than a type error.
414/// [`Default`] gives "a plain peer with whatever the environment says", which
415/// is what nodes and the coordinator want.
416#[cfg(feature = "zenoh")]
417#[derive(Debug, Default, Clone, Copy)]
418pub struct ZenohSessionParams<'a> {
419    /// Endpoint this session listens on and advertises to its peers, e.g.
420    /// `tcp/127.0.0.1:43217` for a single-machine daemon or `tcp/10.0.2.100:5456`
421    /// for one in a cluster. Verified against `info().locators()` after open;
422    /// see the return value.
423    pub listen_endpoint: Option<&'a str>,
424    /// Shared rendezvous endpoint for daemon-to-daemon discovery when multicast
425    /// isn't available: added to *both* listen and connect endpoints, so the
426    /// first daemon to bind it becomes the gossip hub and the rest fall through
427    /// to connect-only.
428    pub inter_daemon_peer: Option<&'a str>,
429    /// Peers this session dials, in addition to whatever
430    /// [`DORA_ZENOH_CONNECT_ENV`] carries. This is how a deployment wires its
431    /// daemons into an explicit mesh instead of relying on gossip through a
432    /// single rendezvous: every daemon dials every other one, which is the
433    /// clique zenoh 1.9 requires of a peer region.
434    ///
435    /// Operator-supplied, and therefore *authoritative*: naming them is a
436    /// statement that this deployment does not rely on scouting, so they
437    /// replace multicast (see the `#1856` guard below).
438    pub connect_endpoints: &'a [String],
439    /// Peers this session dials that dora *discovered* rather than the operator
440    /// naming them — today, the endpoints the coordinator handed back at
441    /// registration.
442    ///
443    /// Dialed exactly like [`Self::connect_endpoints`], but deliberately
444    /// excluded from the decision to turn multicast scouting off. A discovered
445    /// list can be incomplete or stale in ways an operator-supplied one cannot:
446    /// a peer that has not yet reported its endpoint is missing from it, and a
447    /// peer that died moments ago is still in it until the coordinator notices.
448    /// Letting such a list disable scouting would make a partial answer *worse*
449    /// than no answer — it would strip the fallback that was working — so
450    /// discovery here is strictly additive: it adds links, and multicast stays
451    /// available to cover whatever it missed.
452    pub discovered_connect_endpoints: &'a [String],
453    /// Whether this session may scout by multicast. A request, not a command —
454    /// see the `#1856` guard below.
455    pub multicast: MulticastScouting,
456    /// Overlay file to apply, taking the place of
457    /// [`DORA_ZENOH_CONFIG_OVERLAY_ENV`]; `None` reads that variable. Lets a
458    /// caller configure the overlay without mutating the process environment.
459    pub config_overlay: Option<&'a std::path::Path>,
460}
461
462/// Computed Zenoh configuration and endpoint metadata built from session parameters and environment.
463#[cfg(feature = "zenoh")]
464#[derive(Debug)]
465pub(crate) struct BuiltZenohConfig {
466    pub config: zenoh::Config,
467    pub listen_inserted_into_configured: Option<String>,
468    pub listen_configured: bool,
469    pub env_listen_endpoints: Vec<String>,
470    pub multicast_scouting_off: bool,
471}
472
473/// Build the Zenoh configuration for a session based on parameters, environment variables, and optional overlay.
474///
475/// This shared helper builds the configuration deterministically without opening any network ports,
476/// allowing tests to inspect and verify the resulting config.
477#[cfg(feature = "zenoh")]
478pub(crate) fn build_zenoh_config(
479    params: &ZenohSessionParams<'_>,
480    overlay: Option<&ZenohOverlay>,
481) -> eyre::Result<BuiltZenohConfig> {
482    let ZenohSessionParams {
483        listen_endpoint,
484        inter_daemon_peer,
485        connect_endpoints,
486        discovered_connect_endpoints,
487        multicast,
488        config_overlay: _,
489    } = *params;
490
491    let mut zenoh_config = zenoh::Config::default();
492
493    // Bound unicast transport open timeout so unreachable peers don't hang teardown (#2776).
494    //
495    // In Zenoh 1.9, `TransportManager::open_transport_unicast` wraps link opening and handshakes
496    // in `tokio::time::timeout(open_timeout, ...)`. During teardown, `Runtime::close` blocks on any
497    // in-flight dial because the cancellation token is only selected against the sleep between
498    // retries, not against the dial itself. Setting `open_timeout` to 1 s bounds this teardown hang.
499    //
500    // Note on asymmetry: `accept_timeout` remains at Zenoh's default of 10 s while `open_timeout`
501    // drops to 1 s. This asymmetry is intentional: inbound connection accepts do not actively
502    // block local teardown on a hung outgoing dial.
503    //
504    // Note on configuration priority:
505    // - If `ZENOH_CONFIG` (`DEFAULT_CONFIG_PATH_ENV`) is set, it replaces the entire configuration
506    //   wholesale and this code path is never reached (compatible with dev-container setups).
507    // - Operators supplying a JSON5 overlay via `DORA_ZENOH_CONFIG_OVERLAY` inherit this default,
508    //   but can override it because `overlay.apply()` runs last.
509    // - Operators on high-latency WAN links (~200 ms RTT) can raise this via `DORA_ZENOH_OPEN_TIMEOUT_MS`
510    //   without needing a custom JSON5 overlay file.
511    let open_timeout_ms = zenoh_unicast_open_timeout_ms();
512    if let Err(err) = zenoh_config.insert_json5(
513        "transport/unicast/open_timeout",
514        &open_timeout_ms.to_string(),
515    ) {
516        warn!("failed to set zenoh `transport/unicast/open_timeout` to {open_timeout_ms}: {err}");
517    }
518
519    // NOTE: we used to set `routing/peer: { mode: "linkstate" }` here so
520    // that peers would relay for each other (e.g. two daemons on separate
521    // networks reaching each other through a public one). In zenoh 1.8 that
522    // worked: its `linkstate_peer` hat derived
523    // `peer_full_linkstate = routing.peer.mode == "linkstate"`. Zenoh 1.9
524    // dropped that hat; its `peer` hat hardcodes `full_linkstate: false`
525    // (release notes, under Bug fixes: "Disable `full_linkstate` in
526    // `peer::Hat::Network`"), so peers no longer relay. The setting became a
527    // silent no-op — `insert_json5` still returns `Ok`, so our own error
528    // branch never fired, and only zenoh's deprecation log hinted at it.
529    // Deleted rather than ported: there is no peer-side equivalent in 1.9.
530    //
531    // Consequences, and why this is not a regression here:
532    //   * Same-machine nodes are all loopback-addressable, so the links
533    //     the dataflow needs are established explicitly via
534    //     `connect/endpoints` below (see `DORA_ZENOH_CONNECT`) instead of
535    //     being left to gossip's best-effort autoconnect.
536    //   * Multi-machine/NAT setups, which is what linkstate was meant to
537    //     serve, supply their own config via `ZENOH_CONFIG_PATH` (handled
538    //     in the branch above) and can put a real router in the path.
539    //
540    // NOTE: we used to set `transport/unicast/lowlatency: true` here (and
541    // `qos/enabled: false` with it, since the low-latency transport is
542    // negotiated without QoS) to skip zenoh's batching/priority queues.
543    // Both are gone, because low-latency cannot fragment: a message has to
544    // fit one batch, and `batch_size` is capped at 64 KiB
545    // (`pub type BatchSize = u16`, so 65535 is the max, not just the
546    // default). Shared memory hid that — an SHM payload travels as a
547    // ~16-byte descriptor and never fragments — but SHM is per-host, so it
548    // cannot negotiate between machines. A >64 KiB message to another host
549    // therefore had *no* working path: the sender writes it with a 4-byte
550    // length prefix and no size check, `put()` returns `Ok`, and the peer
551    // rejects the frame ("Batch len is invalid") — silent loss, with the
552    // publisher believing it succeeded.
553    //
554    // Dropping both is not a latency regression — measured against the old
555    // config (release, `examples/benchmark`), p50 is neutral-to-better
556    // (64 B 65->55 µs, 512 B 66->58 µs, 16 KB 73->63 µs; only 8 B is ~7 µs
557    // worse) and throughput is up (4 KB +51%, 16 KB +41%), since bypassing
558    // batching cost a syscall per message.
559    //
560    // The two settings must be removed *together*: dropping `lowlatency`
561    // while leaving `qos/enabled: false` did cost ~25 µs p50 on small
562    // messages. Restoring QoS recovers it, because the publishers'
563    // `Priority::RealTime` finally takes effect — it was silently inert
564    // while QoS was off. Publishers also still set `express(true)`, which is
565    // what actually carries small-message latency here.
566    //
567    // We rely on zenoh's SHM transport (`transport/shared_memory/enabled`)
568    // being enabled, which is its default — do NOT set it to `false`: the
569    // API keeps working, but SHM buffers silently get serialized as plain
570    // bytes onto the wire (i.e. copied) instead of sent as a ~16-byte
571    // descriptor.
572
573    // Build the connect-endpoint list from three sources:
574    //   1. DORA_ZENOH_CONNECT env var — daemon-bootstrapped local
575    //      discovery for spawned nodes (#1778).
576    //   2. `connect_endpoints` — peers this process was told to dial,
577    //      i.e. the explicit daemon↔daemon mesh (`--zenoh-connect`).
578    //      Unlike (3) this is dial-only: a mesh member listens on its
579    //      own advertised endpoint, not on its peers'.
580    //   3. `inter_daemon_peer` — shared rendezvous for daemon-to-
581    //      daemon discovery (extends #1778 to the daemon↔daemon
582    //      hop). One daemon binds it as a listener, others connect
583    //      and gossip-discover their peers via it.
584    //   4. `discovered_connect_endpoints` — peers the coordinator
585    //      reported. Dialed like the rest, but see below: because a
586    //      discovered list can be incomplete or stale, it alone does
587    //      not disable scouting.
588    // Setting any of the *operator-supplied* ones disables multicast
589    // scouting, so we don't end up with mixed discovery modes.
590    let mut connect_eps: Vec<String> = Vec::new();
591    if let Ok(eps) = std::env::var(DORA_ZENOH_CONNECT_ENV) {
592        connect_eps.extend(split_endpoints(&eps));
593    }
594    connect_eps.extend(connect_endpoints.iter().cloned());
595    // Everything appended from here on is dialed but does not, on its
596    // own, justify dropping multicast — see `discovered_connect_endpoints`.
597    let authoritative_connect_eps = connect_eps.len();
598    // Discovered endpoints are checked here as well as by whoever handed
599    // them over. The coordinator validates what daemons report to it, so
600    // this is not the only guard — but it is the one that sits where the
601    // value is *used*, which keeps the property true for any future
602    // source of discovered endpoints and for a coordinator that is
603    // itself wrong. Operator-supplied endpoints are deliberately not
604    // filtered: someone who typed an endpoint on the command line is
605    // owed a zenoh error about it, not silence.
606    connect_eps.extend(discovered_connect_endpoints.iter().filter_map(|ep| {
607        match validate_zenoh_endpoint(ep) {
608            Ok(()) => Some(ep.clone()),
609            Err(err) => {
610                warn!("ignoring discovered zenoh endpoint: {err}");
611                None
612            }
613        }
614    }));
615    if let Some(peer) = inter_daemon_peer {
616        connect_eps.push(peer.to_string());
617    }
618    if let Some(overlay) = overlay {
619        connect_eps.extend(overlay.connect_endpoints.iter().cloned());
620    }
621    // A duplicate dial is not fatal, but it is a wasted connection
622    // attempt per duplicate and, when the peer is unreachable, a
623    // second retry loop against it — which is exactly what keeps the
624    // net runtime busy (#2776). Callers can legitimately overlap:
625    // `--zenoh-connect` may name the same endpoint the environment
626    // already carries. `retain` over a seen-set rather than `dedup`,
627    // which only collapses *adjacent* equals and would leave the
628    // env/param/rendezvous interleaving untouched.
629    let mut seen_connect = std::collections::HashSet::new();
630    // Counted before dedup: `retain` only ever removes later duplicates
631    // of an earlier entry, and the authoritative entries come first, so
632    // "were there any" is unaffected by it.
633    let has_authoritative_connect = authoritative_connect_eps > 0
634        || inter_daemon_peer.is_some()
635        || overlay
636            .as_ref()
637            .is_some_and(|o| !o.connect_endpoints.is_empty());
638    connect_eps.retain(|ep| seen_connect.insert(ep.clone()));
639    let mut connect_inserted = false;
640    if !connect_eps.is_empty() {
641        // Serialized, not interpolated. These strings are no longer all
642        // operator-supplied: the coordinator hands over endpoints that
643        // other daemons reported, so a `"` in one would otherwise end
644        // the JSON5 string and either break the whole array — costing
645        // this session every connect endpoint, legitimate ones included
646        // — or append endpoints of someone else's choosing to the dial
647        // list. `endpoint_array_json` escapes; `validate_zenoh_endpoint`
648        // rejects such a value on ingest. Both, deliberately.
649        let json = endpoint_array_json(&connect_eps);
650        match zenoh_config.insert_json5("connect/endpoints", &json) {
651            Ok(()) => connect_inserted = true,
652            Err(err) => {
653                warn!(
654                    "failed to set zenoh connect/endpoints to {json} ({err}); leaving multicast scouting enabled as fallback"
655                );
656            }
657        }
658    }
659    // Track whether listen/endpoints was accepted into THIS config.
660    // We don't promote it to `effective_listen_endpoint` until the
661    // configured open succeeds — the fallback default-config path
662    // below has no listener and must not advertise one (#1856).
663    // We only track the caller's own `listen_endpoint` (the per-daemon
664    // listener that gets advertised to spawned nodes), NOT
665    // `inter_daemon_peer` which is cluster-wide config — daemons that
666    // bind it act as the rendezvous, but advertising it back to nodes
667    // would be wrong (nodes would try to reach it through what may be a
668    // remote address, defeating the loopback shortcut) — and not the
669    // env-supplied node listeners either, which the daemon planned and
670    // already knows.
671    let mut listen_inserted_into_configured: Option<String> = None;
672    // Any accepted listener, including the cluster-wide rendezvous that
673    // is deliberately absent from `listen_inserted_into_configured`.
674    // Reachability, not advertisability, is what the #1856 guard needs.
675    let mut listen_configured = false;
676
677    // Build the listen-endpoint list (loopback for spawned nodes +
678    // optional inter-daemon rendezvous). With multiple entries,
679    // zenoh binds whichever ones it can; `listen/exit_on_failure:
680    // false` (set below when any listener is configured) lets the
681    // daemon proceed even if some don't bind — e.g. the second
682    // daemon to start on the same host with the same rendezvous
683    // port falls through to connect-only.
684    // A spawned node gets its listeners from the daemon via
685    // `DORA_ZENOH_LISTEN` (the daemon itself passes `listen_endpoint`
686    // directly). Without a known listener a node cannot be dialled, and
687    // since zenoh 1.9 peers do not relay, a consumer that cannot dial its
688    // producer never receives its data at all.
689    //
690    // A node with a consumer on another machine listens both on
691    // loopback (for its same-machine consumers, whose transport can
692    // then carry shared memory) and on a routable address (for the
693    // remote one). The two arrive in *separate* variables so an older
694    // node binary, which treats `DORA_ZENOH_LISTEN` as a single
695    // locator, still gets a valid one — see the doc on
696    // `DORA_ZENOH_LISTEN_EXTRA_ENV`. `split_endpoints` is applied to
697    // both so a hand-set list in either keeps working.
698    let env_listen_endpoints = listen_endpoints_from_env(
699        std::env::var(DORA_ZENOH_LISTEN_ENV).ok().as_deref(),
700        std::env::var(DORA_ZENOH_LISTEN_EXTRA_ENV).ok().as_deref(),
701    );
702
703    let mut listen_eps: Vec<String> = Vec::new();
704    if let Some(ep) = listen_endpoint {
705        listen_eps.push(ep.to_string());
706    }
707    listen_eps.extend(env_listen_endpoints.iter().cloned());
708    if let Some(peer) = inter_daemon_peer {
709        listen_eps.push(peer.to_string());
710    }
711    if let Some(overlay) = overlay {
712        listen_eps.extend(overlay.listen_endpoints.iter().cloned());
713    }
714    if !listen_eps.is_empty() {
715        let json = endpoint_array_json(&listen_eps);
716        let listen_inserted = match zenoh_config.insert_json5("listen/endpoints", &json) {
717            Ok(()) => {
718                listen_inserted_into_configured = listen_endpoint.map(String::from);
719                listen_configured = true;
720                true
721            }
722            Err(err) => {
723                warn!("failed to set zenoh listen/endpoints to {json}: {err}");
724                false
725            }
726        };
727        // Tolerate a race between OS port reservation and zenoh's
728        // own bind, AND the multi-daemon-same-rendezvous case where
729        // only one daemon wins the bind. The connect side still
730        // works, and child nodes get a clear error rather than the
731        // daemon exiting.
732        if listen_inserted
733            && let Err(err) = zenoh_config.insert_json5("listen/exit_on_failure", "false")
734        {
735            warn!("failed to set zenoh listen/exit_on_failure: {err}");
736        }
737    }
738
739    // Drop multicast scouting only once this session is reachable some
740    // other way — otherwise it has no endpoints to dial and no way to
741    // be found, which is the silent partition #1856 exists to prevent.
742    //
743    // Two things make it reachable. `connect_inserted`: explicit
744    // endpoints replaced scouting (the pre-existing rule). Or an
745    // accepted listener plus a caller that asked to stop scouting —
746    // `dora run` without dynamic nodes, or `--zenoh-no-multicast` on a
747    // network where the scouting bind itself fails; a listener means
748    // peers that hold the endpoint can dial in.
749    //
750    // Deliberately *not* honoring the request when neither holds: the
751    // reservation-failure paths in `build_daemon` log "falling back to
752    // multicast scouting only" and mean it. Treating the request as
753    // absolute would disarm that recovery and strand the daemon.
754    let requested_off = multicast_disabled(matches!(multicast, MulticastScouting::Disabled));
755    // Computed once and reused by the listener-did-not-bind diagnostic
756    // below, which used to test `connect_inserted` alone — a proxy that
757    // disagreed with this in both directions, telling a session with
758    // scouting off that it was "falling back to multicast scouting"
759    // (and vice versa). That is the same class of misdirection #2762
760    // fixed once already.
761    let multicast_scouting_off =
762        (connect_inserted && has_authoritative_connect) || (requested_off && listen_configured);
763    if multicast_scouting_off
764        && let Err(err) = zenoh_config.insert_json5("scouting/multicast/enabled", "false")
765    {
766        warn!("failed to disable zenoh scouting/multicast: {err}");
767    }
768
769    // Last, so an operator's setting wins over dora's default for the
770    // same key. The endpoint lists are already merged above rather than
771    // overwritten here — that is what makes the overlay additive.
772    // Overlay users inherit dora's defaults (like open_timeout) but can
773    // override them here.
774    if let Some(overlay) = overlay {
775        overlay.apply(&mut zenoh_config)?;
776    }
777
778    Ok(BuiltZenohConfig {
779        config: zenoh_config,
780        listen_inserted_into_configured,
781        listen_configured,
782        env_listen_endpoints,
783        multicast_scouting_off,
784    })
785}
786
787/// Like [`open_zenoh_session`], but takes the full [`ZenohSessionParams`]: a
788/// listen endpoint to bind and advertise (e.g. `tcp/127.0.0.1:43217`, or a
789/// routable address such as `tcp/10.0.2.100:5456` for a daemon in a cluster),
790/// extra peers to dial, and the multicast request. The daemon uses this so
791/// spawned nodes can connect via `DORA_ZENOH_CONNECT` without multicast
792/// scouting, and so that other daemons can dial it.
793///
794/// `connect_endpoints` are dialed in addition to whatever
795/// [`DORA_ZENOH_CONNECT_ENV`] carries, deduplicated against it. They are
796/// dial-only, which is what distinguishes an explicit mesh (each daemon
797/// listens on its own endpoint and dials its peers') from the rendezvous
798/// below (every daemon both listens on and dials the *same* endpoint).
799///
800/// `inter_daemon_peer` is an optional shared endpoint used as the
801/// rendezvous for daemon-to-daemon discovery when multicast isn't
802/// available. When set, it is added to both `listen/endpoints` and
803/// `connect/endpoints`: the first daemon to bind it serves as the
804/// gossip hub, and the rest fall through to connect-only via
805/// `listen/exit_on_failure: false`. Multicast scouting is disabled in
806/// that mode since we have explicit endpoints. This complements the
807/// per-spawned-node `DORA_ZENOH_CONNECT` fallback from #1778, which
808/// only covers daemon↔node, leaving daemon↔daemon dependent on
809/// multicast — broken in dev containers and many CI environments.
810///
811/// Returns `(session, effective_listen_endpoint)`. The second element is
812/// `Some(ep)` only when `listen_endpoint` was requested, zenoh accepted the
813/// `listen/endpoints` insert, and `session.info().locators()` confirms that
814/// it actually bound. It is `None` if `listen_endpoint` was `None`, the insert
815/// failed, the open path used the `ZENOH_CONFIG_PATH`-from-file branch, or the
816/// configured listener did not bind. Callers must inject the returned endpoint
817/// into peers (e.g. via `DORA_ZENOH_CONNECT`) instead of the value they passed
818/// in, so peers never receive a stale endpoint the listener did not actually
819/// bind (#1856, #1858). The `inter_daemon_peer` is intentionally NOT
820/// part of the returned endpoint — it is cluster-wide configuration
821/// shared by the caller (e.g. `dora cluster up`), not per-daemon
822/// state to advertise back to nodes.
823///
824/// `multicast` lets a caller that establishes every link explicitly opt out of
825/// scouting — see [`DORA_ZENOH_MULTICAST_ENV`], honored in addition to this
826/// argument. It is a request, not a command: it is ignored unless this session
827/// ends up reachable some other way (see the `#1856` guard below).
828#[cfg(feature = "zenoh")]
829pub async fn open_zenoh_session_with_listen(
830    params: ZenohSessionParams<'_>,
831) -> eyre::Result<(zenoh::Session, Option<String>)> {
832    use eyre::{Context, eyre};
833    use tracing::warn;
834
835    // Source-of-truth for the listener: stays `None` unless we actually
836    // accepted `listen/endpoints` into the config below. Callers use this
837    // (not their requested endpoint) to advertise the listener to peers.
838    let mut effective_listen_endpoint: Option<String> = None;
839
840    let overlay = match params.config_overlay {
841        Some(path) => Some(ZenohOverlay::from_path(path)?),
842        None => ZenohOverlay::from_env()?,
843    };
844
845    let zenoh_session = match std::env::var(zenoh::Config::DEFAULT_CONFIG_PATH_ENV) {
846        Ok(path) => {
847            if overlay.is_some() {
848                // Merging the two would be guesswork: the file replaces the
849                // config dora computed, so there is no dora-side endpoint list
850                // left for the overlay's to append to, and "append to whatever
851                // the file happened to set" is not a rule anyone could predict.
852                eyre::bail!(
853                    "both {} and {} are set. {} replaces the whole zenoh \
854                     configuration, while {} layers onto the one dora computes — \
855                     keep one. Prefer the overlay: it adds your endpoints \
856                     without discarding the direct node-to-node links the daemon \
857                     plans for this dataflow.",
858                    zenoh::Config::DEFAULT_CONFIG_PATH_ENV,
859                    DORA_ZENOH_CONFIG_OVERLAY_ENV,
860                    zenoh::Config::DEFAULT_CONFIG_PATH_ENV,
861                    DORA_ZENOH_CONFIG_OVERLAY_ENV,
862                );
863            }
864            let zenoh_config = zenoh::Config::from_file(&path)
865                .map_err(|e| eyre!(e))
866                .wrap_err_with(|| format!("failed to read zenoh config from {path}"))?;
867            zenoh::open(zenoh_config)
868                .await
869                .map_err(|e| eyre!(e))
870                .context("failed to open zenoh session")?
871        }
872        Err(std::env::VarError::NotPresent) => {
873            let built = build_zenoh_config(&params, overlay.as_ref())?;
874
875            match zenoh::open(built.config).await {
876                Ok(zenoh_session) => {
877                    // Verify the listener actually bound. `zenoh::open` returning
878                    // Ok is necessary but not sufficient — with
879                    // `listen/exit_on_failure: false` (set above), zenoh tolerates
880                    // a silently-failed listen bind. The most plausible cause is
881                    // the race between `reserve_loopback_zenoh_endpoint` dropping
882                    // its reservation socket and zenoh's own bind, during which
883                    // some other process could grab the port. Trusting `Ok` here
884                    // would advertise an endpoint nothing is listening on, and
885                    // spawned nodes would fail their `DORA_ZENOH_CONNECT` connect
886                    // attempts (#1858).
887                    //
888                    // `info().locators()` is the zenoh-canonical "what actually
889                    // bound" query (unstable API gated behind the workspace
890                    // `unstable` feature, already enabled in the root Cargo.toml
891                    // zenoh dependency).
892                    // Verify every endpoint we asked for, but only ever
893                    // *return* the caller's own: the env-supplied ones belong
894                    // to a node whose daemon planned them and already knows
895                    // them, so there they are a diagnostic, not a value to
896                    // propagate.
897                    let mut verify: Vec<&str> = built
898                        .listen_inserted_into_configured
899                        .iter()
900                        .map(String::as_str)
901                        .collect();
902                    if built.listen_configured {
903                        verify.extend(built.env_listen_endpoints.iter().map(String::as_str));
904                    }
905                    if !verify.is_empty() {
906                        let bound_locators: Vec<String> = zenoh_session
907                            .info()
908                            .locators()
909                            .await
910                            .into_iter()
911                            .map(|l| l.as_str().to_string())
912                            .collect();
913                        // Strip zenoh's endpoint-string separators before
914                        // comparing. Per `zenoh-protocol::core::endpoint`,
915                        // `?` separates metadata and `#` separates config
916                        // (e.g. `tcp/127.0.0.1:43217?prio=high#iface=lo0`).
917                        // `Locator::from(EndPoint)` already truncates `#`,
918                        // but a `?`-metadata suffix would survive into
919                        // `info().locators()`'s output. Strip both, then
920                        // exact-match — substring `contains` would
921                        // false-positive on port-prefix collisions (e.g.
922                        // requested `:5000` matching bound `:50000`), which
923                        // is exactly the mismatch this check exists to
924                        // catch. NOTE: the comparison is against the
925                        // requested string verbatim, so a caller must request
926                        // the same canonical `tcp/<addr>:<port>` form that
927                        // zenoh reports back. `reserve_zenoh_endpoint` emits
928                        // that form, but only for a *concrete* address: a
929                        // wildcard request (`tcp/0.0.0.0:<port>`) can never
930                        // match, because zenoh binds every interface and
931                        // reports the concrete one. Callers must therefore
932                        // reject wildcards up front (the daemon does) rather
933                        // than reach this check, which would read the mismatch
934                        // as "the listener did not bind" and silently fall back
935                        // to multicast scouting.
936                        for requested in verify {
937                            let bound = bound_locators
938                                .iter()
939                                .any(|l| l.split(['?', '#']).next() == Some(requested));
940                            if bound {
941                                if built.listen_inserted_into_configured.as_deref()
942                                    == Some(requested)
943                                {
944                                    effective_listen_endpoint = Some(requested.to_string());
945                                }
946                            } else if built.multicast_scouting_off {
947                                // Scouting is off for this session, so there is
948                                // NO discovery fallback:
949                                // peers already told to dial `{requested}` (e.g. via
950                                // the per-node `DORA_ZENOH_CONNECT` plan from #2716)
951                                // cannot reach this now-listener-less session, and it
952                                // cannot be scouted either — that edge is silently
953                                // partitioned. Do not claim "multicast scouting only"
954                                // here; that fallback does not exist in this mode and
955                                // the old message pointed debuggers the wrong way
956                                // (#2762).
957                                warn!(
958                                    "zenoh session opened but listener for `{requested}` \
959                                     did not bind (actually bound: {bound_locators:?}); \
960                                     multicast scouting is disabled for this session \
961                                     (explicit connect endpoints are set), so peers told \
962                                     to dial `{requested}` have no fallback path to reach \
963                                     it (#2762)"
964                                );
965                            } else {
966                                warn!(
967                                    "zenoh session opened but listener for `{requested}` \
968                                     did not bind (actually bound: {bound_locators:?}); \
969                                     falling back to multicast scouting for discovery"
970                                );
971                            }
972                        }
973                    }
974                    zenoh_session
975                }
976                Err(err) => {
977                    warn!(
978                        "failed to open tuned zenoh session ({err}), retrying with default config"
979                    );
980                    // Default fallback has no listener; `effective_listen_endpoint`
981                    // stays `None` so peers don't try to reach a bind that isn't
982                    // there (#1856).
983                    let zenoh_config = zenoh::Config::default();
984                    zenoh::open(zenoh_config)
985                        .await
986                        .map_err(|e| eyre!(e))
987                        .context("failed to open zenoh session")?
988                }
989            }
990        }
991        Err(std::env::VarError::NotUnicode(_)) => eyre::bail!(
992            "{} env variable is not valid unicode",
993            zenoh::Config::DEFAULT_CONFIG_PATH_ENV
994        ),
995    };
996    Ok((zenoh_session, effective_listen_endpoint))
997}
998
999/// Render endpoints as a JSON array for `insert_json5`, escaping each one.
1000///
1001/// `serde_json` output is valid JSON5, and escaping is what keeps a hostile or
1002/// merely malformed endpoint from reshaping the array around it.
1003#[cfg(feature = "zenoh")]
1004fn endpoint_array_json(endpoints: &[String]) -> String {
1005    serde_json::Value::Array(
1006        endpoints
1007            .iter()
1008            .map(|e| serde_json::Value::String(e.clone()))
1009            .collect(),
1010    )
1011    .to_string()
1012}
1013
1014/// Whether `endpoint` is safe to accept from the network as a zenoh locator.
1015///
1016/// Applied to the endpoint a daemon reports to the coordinator, which is the
1017/// first value to reach dora's zenoh config from off-machine — everything
1018/// before it came from the operator's own command line. The coordinator hands
1019/// it to every daemon that registers later, so an unchecked value would travel
1020/// straight into their `connect/endpoints`.
1021///
1022/// Called on every hop that value takes: both ways a daemon can report one
1023/// (`accept_reported_zenoh_endpoint` in the coordinator covers the registration
1024/// *and* the later correction, which exists to replace it), and again where a
1025/// receiving daemon merges the result into its own dial list. Validating only
1026/// at the first hop would leave the property depending on which path ran last.
1027///
1028/// Deliberately a charset check rather than a locator parse: zenoh's locator
1029/// grammar covers protocols dora does not model (`quic`, `unixsock-stream`,
1030/// metadata after `?`, config after `#`), and rejecting a valid endpoint would
1031/// break a working deployment. What matters is that nothing here can terminate
1032/// a JSON string or escape it — so quotes, backslashes and control characters
1033/// are refused, along with anything long enough to be worth truncating.
1034pub fn validate_zenoh_endpoint(endpoint: &str) -> Result<(), String> {
1035    const MAX_LEN: usize = 256;
1036    if endpoint.is_empty() {
1037        return Err("zenoh endpoint must not be empty".to_string());
1038    }
1039    if endpoint.len() > MAX_LEN {
1040        return Err(format!(
1041            "zenoh endpoint is {} bytes, over the {MAX_LEN}-byte limit",
1042            endpoint.len()
1043        ));
1044    }
1045    if let Some(bad) = endpoint
1046        .chars()
1047        .find(|c| !matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '.' | ':' | '/' | '-' | '_' | '[' | ']' | '%' | '?' | '#' | '=' | '&' | '+' | '*' | ','))
1048    {
1049        return Err(format!(
1050            "zenoh endpoint contains the disallowed character {bad:?}"
1051        ));
1052    }
1053    Ok(())
1054}
1055
1056// Keep the existing path while all endpoint classification shares the
1057// parser used by daemon advertisement splitting in dora-message.
1058#[cfg(feature = "zenoh")]
1059pub use dora_message::zenoh::zenoh_endpoint_is_loopback;
1060
1061/// Default TCP port for a daemon's inter-daemon zenoh listener.
1062///
1063/// Only used when a deployment *names* the port — `--zenoh-listen <IP>` alone
1064/// still reserves an ephemeral one. An explicit mesh needs a port its peers can
1065/// predict, since they must dial the endpoint before the daemon has told anyone
1066/// what it bound. 5456 is the port every deployment doc example already uses
1067/// for a zenoh peer.
1068pub const DORA_ZENOH_LISTEN_PORT_DEFAULT: u16 = 5456;
1069
1070/// Format `addr:port` as a zenoh TCP endpoint string.
1071///
1072/// The address goes through [`SocketAddr`], whose `Display` brackets IPv6 —
1073/// which is also zenoh's locator grammar (`tcp/[::1]:7447`). Interpolating a
1074/// bare [`IpAddr`] instead would emit `tcp/::1:7447`, where the port colon is
1075/// indistinguishable from the address colons and `insert_json5` rejects the
1076/// result (#3041).
1077///
1078/// Unlike [`reserve_zenoh_endpoint`] this binds nothing, so there is no
1079/// reserve→bind window for another process to slip into: a named port is
1080/// either free when zenoh binds it or it is not, and the
1081/// `info().locators()` check in [`open_zenoh_session_with_listen`] tells the
1082/// caller which.
1083pub fn zenoh_endpoint(addr: IpAddr, port: u16) -> String {
1084    format!("tcp/{}", SocketAddr::new(addr, port))
1085}
1086
1087/// Reserve an unused TCP port on `bind` for use as a zenoh listen endpoint.
1088/// Returns a string suitable for the zenoh `listen/endpoints` config
1089/// (e.g. `tcp/127.0.0.1:43217`, or `tcp/[::1]:43217` for IPv6).
1090///
1091/// The bind address matters beyond which interface accepts connections:
1092/// zenoh advertises the address it bound as its locator, and remote peers
1093/// dial exactly that. A daemon that binds loopback is therefore not merely
1094/// unreachable from another machine — it actively tells remote daemons to
1095/// dial `127.0.0.1`, i.e. their own loopback, where they find nothing (or an
1096/// unrelated local process). Since zenoh 1.9 peers do not relay for each
1097/// other, such a pair has no fallback path and is silently dead. Multi-machine
1098/// deployments must therefore reserve on an address the other machines can
1099/// actually reach; see [`reserve_loopback_zenoh_endpoint`] for the
1100/// single-machine case.
1101///
1102/// There is a small race window between dropping the reservation socket
1103/// and zenoh's own bind. `open_zenoh_session_with_listen` defends against
1104/// it on two layers:
1105///
1106/// 1. `listen/exit_on_failure: false` keeps the daemon alive if zenoh's
1107///    bind silently fails inside the race window.
1108/// 2. After `zenoh::open`, the helper queries `session.info().locators()`
1109///    and only advertises the returned endpoint when our requested
1110///    `addr:port` is actually in the bound-locator list. If the port was
1111///    grabbed by another process, the returned `effective_listen_endpoint`
1112///    is `None` and callers fall back to multicast scouting instead of
1113///    advertising a phantom endpoint (#1858).
1114///
1115/// In practice the OS keeps allocating fresh ephemeral ports each call,
1116/// so collisions remain vanishingly rare.
1117///
1118/// Note that the locator check in (2) compares the requested `addr:port`
1119/// literally, so reserving on the unspecified address (`0.0.0.0`) will not
1120/// match the concrete interface address zenoh reports back. Pass the address
1121/// you want advertised, not a wildcard.
1122pub fn reserve_zenoh_endpoint(bind: IpAddr) -> std::io::Result<String> {
1123    let listener = std::net::TcpListener::bind((bind, 0))?;
1124    let port = listener.local_addr()?.port();
1125    drop(listener);
1126    Ok(zenoh_endpoint(bind, port))
1127}
1128
1129/// Loopback case of [`reserve_zenoh_endpoint`] — the right choice when every
1130/// zenoh peer that needs this listener is on the same host, which is what a
1131/// single-machine deployment looks like.
1132pub fn reserve_loopback_zenoh_endpoint() -> std::io::Result<String> {
1133    reserve_zenoh_endpoint(LOCALHOST)
1134}
1135
1136/// Pick the address a daemon's zenoh listener should bind so that the other
1137/// daemons in the deployment can dial it.
1138///
1139/// Returns [`LOCALHOST`] when the coordinator is itself local: everything that
1140/// needs this listener is then on this host, and binding loopback keeps the
1141/// daemon's zenoh unreachable from the network — which is the status quo for
1142/// single-machine users, and worth preserving.
1143///
1144/// Otherwise the daemon is part of a multi-machine deployment, and we return
1145/// the local address the kernel would use to reach `coordinator_addr`. That is
1146/// the correct choice without anyone configuring anything: on a LAN it is the
1147/// LAN address, and on a mesh VPN (Tailscale/WireGuard) — where the
1148/// coordinator is reached over the tunnel — it is the tunnel address, which is
1149/// exactly the one remote daemons can dial. A multi-homed host that picks the
1150/// wrong interface can be overridden explicitly by the caller.
1151///
1152/// The lookup `connect()`s a UDP socket, which sends no packets: it only asks
1153/// the routing table which source address applies. If there is no route (or
1154/// the lookup otherwise fails) we fall back to [`LOCALHOST`] rather than
1155/// guessing, since a wrong address is advertised to peers and fails silently,
1156/// whereas loopback at least keeps same-host behavior working.
1157pub fn zenoh_bind_address_for(coordinator_addr: SocketAddr) -> IpAddr {
1158    if coordinator_addr.ip().is_loopback() {
1159        return LOCALHOST;
1160    }
1161    local_address_toward(coordinator_addr).unwrap_or(LOCALHOST)
1162}
1163
1164/// Where a daemon's zenoh listener binds: an address, and optionally the port.
1165///
1166/// Both forms are accepted from `--zenoh-listen`:
1167///
1168/// * `10.0.2.100` — the port is left to the OS. Peers learn the resulting
1169///   endpoint by gossip, so this suits a deployment with a rendezvous
1170///   (`--zenoh-peer`) or working multicast.
1171/// * `10.0.2.100:5456`, `[fd7a:1::2]:5456` — a named port, which peers can dial
1172///   without having discovered it first. This is what an explicit mesh needs:
1173///   every daemon's endpoint has to be known before any of them has announced
1174///   anything.
1175///
1176/// IPv6 must be bracketed when naming a port, because `fd7a:1::2:5456` is
1177/// itself a valid IPv6 address and is read as one.
1178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1179pub struct ZenohListen {
1180    /// Address to bind, which is also the address advertised to peers.
1181    pub addr: IpAddr,
1182    /// Port to bind, or `None` to let the OS pick one.
1183    pub port: Option<u16>,
1184}
1185
1186impl ZenohListen {
1187    /// The endpoint to request, reserving an ephemeral port if none was named.
1188    ///
1189    /// A named port skips the reservation entirely: it has no reserve→bind
1190    /// window for another process to slip into, and zenoh's own bind is the
1191    /// only claim on it.
1192    pub fn endpoint(&self) -> std::io::Result<String> {
1193        match self.port {
1194            Some(port) => Ok(zenoh_endpoint(self.addr, port)),
1195            None => reserve_zenoh_endpoint(self.addr),
1196        }
1197    }
1198}
1199
1200impl std::fmt::Display for ZenohListen {
1201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1202        match self.port {
1203            Some(port) => write!(f, "{}", SocketAddr::new(self.addr, port)),
1204            None => write!(f, "{}", self.addr),
1205        }
1206    }
1207}
1208
1209impl std::str::FromStr for ZenohListen {
1210    type Err = String;
1211
1212    fn from_str(s: &str) -> Result<Self, Self::Err> {
1213        // `SocketAddr` first: `10.0.2.100:5456` is not an `IpAddr`, while a
1214        // bare `::1` is not a `SocketAddr`, so neither form is stolen by the
1215        // other. The one genuine ambiguity — unbracketed IPv6 with a port —
1216        // resolves to "address", which is why the docs above insist on
1217        // brackets.
1218        let listen = if let Ok(socket) = s.parse::<SocketAddr>() {
1219            Self {
1220                addr: socket.ip(),
1221                port: Some(socket.port()),
1222            }
1223        } else if let Ok(addr) = s.parse::<IpAddr>() {
1224            Self { addr, port: None }
1225        } else {
1226            return Err(format!(
1227                "`{s}` is neither an IP address (`10.0.2.100`) nor an address \
1228                 with a port (`10.0.2.100:5456`, `[fd7a:1::2]:5456`)"
1229            ));
1230        };
1231        if listen.port == Some(0) {
1232            // Port 0 binds an ephemeral port, which is fine, but the endpoint
1233            // we advertise would still say `:0` — no peer could dial it, and
1234            // the `info().locators()` check would read the mismatch as "the
1235            // listener did not bind". Omitting the port asks for the same thing
1236            // and reserves a concrete one to advertise.
1237            return Err(format!(
1238                "`{s}` names port 0; omit the port to let the OS pick one \
1239                 (dora then advertises the concrete port it reserved)"
1240            ));
1241        }
1242        validate_zenoh_listen(listen.addr).map_err(|err| format!("{err}"))?;
1243        Ok(listen)
1244    }
1245}
1246
1247/// Reject a zenoh listen address that cannot be advertised to peers.
1248///
1249/// Only the wildcard is rejected here, and only because it is *structurally*
1250/// unadvertisable: zenoh would bind every interface but report a concrete
1251/// locator, so the listener verification in [`open_zenoh_session_with_listen`]
1252/// could never match it, and the daemon would silently stop advertising an
1253/// endpoint to its nodes. Whether a concrete address actually exists on this
1254/// host is not knowable here — that surfaces as a bind error from
1255/// [`reserve_zenoh_endpoint`], which callers must treat as fatal when the
1256/// operator named the address explicitly.
1257pub fn validate_zenoh_listen(bind: IpAddr) -> eyre::Result<()> {
1258    if bind.is_unspecified() {
1259        eyre::bail!(
1260            "zenoh listen address must be concrete, not the wildcard `{bind}`. \
1261             Zenoh advertises the address it binds and remote daemons dial exactly \
1262             that, so a wildcard has nothing to advertise. Pass the address other \
1263             daemons should use to reach this host (e.g. its LAN or VPN address)."
1264        );
1265    }
1266    Ok(())
1267}
1268
1269/// Whether a source address the routing table handed back can be advertised to
1270/// peers as a locator.
1271///
1272/// The unspecified address is not a real source, and a loopback source for a
1273/// *remote* target means the routing table told us nothing usable (there is no
1274/// route, or the target resolved back to this host). Advertising either would
1275/// point peers at nothing, so both mean "we learned nothing" and the caller
1276/// should fall back rather than guess.
1277fn usable_source(local: IpAddr) -> Option<IpAddr> {
1278    if local.is_unspecified() || local.is_loopback() {
1279        return None;
1280    }
1281    Some(local)
1282}
1283
1284fn local_address_toward(target: SocketAddr) -> Option<IpAddr> {
1285    // Bind the wildcard of the same family as the target, then `connect` to
1286    // consult the routing table. UDP `connect` is local-only: no traffic.
1287    let bind: SocketAddr = if target.is_ipv4() {
1288        (Ipv4Addr::UNSPECIFIED, 0).into()
1289    } else {
1290        (std::net::Ipv6Addr::UNSPECIFIED, 0).into()
1291    };
1292    let socket = std::net::UdpSocket::bind(bind).ok()?;
1293    socket.connect(target).ok()?;
1294    usable_source(socket.local_addr().ok()?.ip())
1295}
1296
1297/// Zenoh key for node output data.
1298///
1299/// Payload format: raw Arrow bytes with postcard `Metadata` in the Zenoh
1300/// attachment. This topic is published by nodes and consumed directly by
1301/// downstream nodes (plus debug-inspection subscribers). Daemon control frames
1302/// must not be published here; use [`zenoh_daemon_control_topic`] instead.
1303#[cfg(feature = "zenoh")]
1304pub fn zenoh_output_publish_topic(
1305    dataflow_id: uuid::Uuid,
1306    node_id: &dora_message::id::NodeId,
1307    output_id: &dora_message::id::DataId,
1308) -> String {
1309    let network_id = "default";
1310    format!("dora/{network_id}/{dataflow_id}/output/{node_id}/{output_id}")
1311}
1312
1313/// Hex-encode a `DataId` so it occupies exactly one zenoh key chunk.
1314///
1315/// A `DataId` may legally contain `/` (unlike a `NodeId`), so embedding one
1316/// verbatim as a key segment would spill into extra chunks. Hex is unambiguous
1317/// (`[0-9a-f]`, never `/`) and collision-free. Same helper previously used for
1318/// readiness liveliness keys (#2666).
1319#[cfg(feature = "zenoh")]
1320fn hex_key_segment(id: &dora_message::id::DataId) -> String {
1321    use std::fmt::Write;
1322    let s: &str = id.as_ref();
1323    let mut out = String::with_capacity(s.len() * 2);
1324    for b in s.bytes() {
1325        let _ = write!(out, "{b:02x}");
1326    }
1327    out
1328}
1329
1330/// Zenoh key carrying the Arrow IPC **schema** for an output's data topic.
1331///
1332/// Layout: `dora/{network}/{dataflow}/schema/{node}/{hex(output_id)}`.
1333///
1334/// This lives under a dedicated `schema/` plane — **not** under
1335/// [`zenoh_output_publish_topic`] — so it cannot collide with a nested DataId
1336/// such as `cmd/_schema` (whose data topic would otherwise share a key with
1337/// the schema side-channel for `cmd`), and so wildcard subscribers on the
1338/// data-topic namespace never see schema traffic.
1339///
1340/// The output id is hex-encoded into a single chunk because
1341/// DataIds may contain `/`. The key has no `@…` verbatim chunks: zenoh-ext
1342/// liveliness tokens are `${remaining:**}/@adv/${entity}/${zid}/${eid}/${meta}`
1343/// and Zenoh verbatim chunks are hermetic — `**` cannot cross them — so a key
1344/// that introduced `@schema` before `/@adv/…` failed `ke_liveliness::parse`
1345/// and flooded WARN logs (#2923). The producer still publishes here through a
1346/// zenoh-ext `AdvancedPublisher` (cache + `publisher_detection`); subscribers
1347/// recover via `AdvancedSubscriber` history.
1348#[cfg(feature = "zenoh")]
1349pub fn zenoh_output_schema_topic(
1350    dataflow_id: uuid::Uuid,
1351    node_id: &dora_message::id::NodeId,
1352    output_id: &dora_message::id::DataId,
1353) -> String {
1354    let network_id = "default";
1355    let output = hex_key_segment(output_id);
1356    format!("dora/{network_id}/{dataflow_id}/schema/{node_id}/{output}")
1357}
1358
1359/// Zenoh key on which consumers acknowledge a producer's startup route-probe
1360/// markers, as a `/@ack` sub-key of [`zenoh_output_publish_topic`].
1361///
1362/// The producer declares one **exact-key** subscriber here per output and the
1363/// consumers of that output publish their acks to the same exact key, with the
1364/// acking consumer's identity in the attachment (never in the key). Exact-key
1365/// matching means `.../cmd/@ack` and `.../cmd/vel/@ack` can never
1366/// cross-deliver even though `cmd` is a chunk-prefix of `cmd/vel` — the
1367/// collision that forced hex-encoded wildcard keys in the earlier
1368/// liveliness-counting design (#2666) cannot arise without wildcards. The
1369/// `@`-prefixed final chunk additionally keeps the key from matching any
1370/// wildcard subscription on the data-topic namespace.
1371#[cfg(feature = "zenoh")]
1372pub fn zenoh_output_ack_topic(
1373    dataflow_id: uuid::Uuid,
1374    node_id: &dora_message::id::NodeId,
1375    output_id: &dora_message::id::DataId,
1376) -> String {
1377    format!(
1378        "{}/@ack",
1379        zenoh_output_publish_topic(dataflow_id, node_id, output_id)
1380    )
1381}
1382
1383/// Zenoh key for control frames associated with a node output.
1384///
1385/// Payload format: postcard `Timestamped<InterDaemonEvent>` with no Zenoh
1386/// attachment. Published by daemons for inter-daemon control (for example
1387/// `OutputClosed`) and by the coordinator for explicit topic injection. Keeping
1388/// this separate from [`zenoh_output_publish_topic`] avoids mixing control frames
1389/// with raw node output payloads on the same key.
1390#[cfg(feature = "zenoh")]
1391pub fn zenoh_daemon_control_topic(
1392    dataflow_id: uuid::Uuid,
1393    node_id: &dora_message::id::NodeId,
1394    output_id: &dora_message::id::DataId,
1395) -> String {
1396    let network_id = "default";
1397    format!("dora/{network_id}/{dataflow_id}/control/{node_id}/{output_id}")
1398}
1399
1400/// Zenoh topic carrying [`InterDaemonEvent::ExtensionMessage`][msg] for one
1401/// extension within one dataflow. Every daemon in the dataflow subscribes.
1402///
1403/// Per-namespace rather than one shared topic, so two extensions in the same
1404/// dataflow never see each other's traffic.
1405///
1406/// [msg]: dora_message::daemon_to_daemon::InterDaemonEvent::ExtensionMessage
1407pub fn dataflow_extension_topic(dataflow_id: &uuid::Uuid, namespace: &str) -> String {
1408    let network_id = "default";
1409    format!("dora/{network_id}/{dataflow_id}/ext/{namespace}")
1410}
1411
1412#[cfg(test)]
1413mod endpoint_validation_tests {
1414    use super::validate_zenoh_endpoint;
1415
1416    #[test]
1417    fn ordinary_locators_are_accepted() {
1418        for ok in [
1419            "tcp/127.0.0.1:7447",
1420            "tcp/10.0.2.100:5456",
1421            "tcp/[fd7a:1::2]:5456",
1422            "udp/192.168.1.1:7447",
1423            "tcp/host.example:7447",
1424            "tcp/10.0.0.1:7447?prio=high",
1425            "tcp/10.0.0.1:7447#iface=eth0",
1426        ] {
1427            assert!(validate_zenoh_endpoint(ok).is_ok(), "rejected `{ok}`");
1428        }
1429    }
1430
1431    /// The reason this validator exists: the endpoint reaches dora's zenoh
1432    /// config from off-machine, and a quote would end the JSON string it is
1433    /// written into — either breaking the whole array (costing that daemon
1434    /// every connect endpoint) or appending endpoints of someone else's
1435    /// choosing to it.
1436    #[test]
1437    fn quotes_and_escapes_are_rejected() {
1438        for bad in [
1439            r#"tcp/1.2.3.4:1"#.to_string() + "\"",
1440            r#"tcp/1.2.3.4:1","tcp/evil:7447"#.to_string(),
1441            r"tcp/1.2.3.4:1\u0022".to_string(),
1442            "tcp/1.2.3.4:1\n".to_string(),
1443            "tcp/1.2.3.4:1 ".to_string(),
1444        ] {
1445            assert!(validate_zenoh_endpoint(&bad).is_err(), "accepted `{bad}`");
1446        }
1447    }
1448
1449    #[test]
1450    fn empty_and_oversized_endpoints_are_rejected() {
1451        assert!(validate_zenoh_endpoint("").is_err());
1452        assert!(validate_zenoh_endpoint(&"a".repeat(257)).is_err());
1453        assert!(validate_zenoh_endpoint(&"a".repeat(256)).is_ok());
1454    }
1455}
1456
1457#[cfg(test)]
1458mod tests {
1459    use super::*;
1460
1461    #[cfg(feature = "zenoh")]
1462    #[test]
1463    fn loopback_endpoints_are_recognized_in_every_spelling() {
1464        for endpoint in [
1465            "tcp/127.0.0.1:5456",
1466            "tcp/127.0.0.1:5456?iface=lo",
1467            "tcp/[::1]:5456",
1468            "tcp/[::1]",
1469            "tcp/[::ffff:127.0.0.1]:5456",
1470            "tcp/localhost:5456",
1471            "tcp/LOCALHOST:5456",
1472            "udp/127.1.2.3:1",
1473        ] {
1474            assert!(zenoh_endpoint_is_loopback(endpoint), "{endpoint}");
1475        }
1476        for endpoint in [
1477            "tcp/10.0.2.100:5456",
1478            "tcp/[fd7a:1::2]:5456",
1479            "tcp/robot-01.local:5456",
1480            "tcp/0.0.0.0:5456",
1481        ] {
1482            assert!(!zenoh_endpoint_is_loopback(endpoint), "{endpoint}");
1483        }
1484    }
1485
1486    /// The forward-compat contract: the loopback endpoint stays alone in
1487    /// `DORA_ZENOH_LISTEN` so a node built before `DORA_ZENOH_LISTEN_EXTRA`
1488    /// existed — which pushes that value in as a *single* locator — still gets
1489    /// a usable one. A list there would be rejected wholesale by such a node,
1490    /// costing it loopback too and partitioning it from same-machine consumers
1491    /// (dora-rs/dora#2742).
1492    #[cfg(feature = "zenoh")]
1493    #[test]
1494    fn listen_endpoints_keep_loopback_first_and_merge_the_extra_var() {
1495        assert_eq!(
1496            listen_endpoints_from_env(Some("tcp/127.0.0.1:41000"), Some("tcp/10.0.0.2:41001")),
1497            vec![
1498                "tcp/127.0.0.1:41000".to_string(),
1499                "tcp/10.0.0.2:41001".to_string()
1500            ],
1501            "loopback must stay first — order decides which locator a \
1502             same-machine consumer picks, and only loopback carries shared memory"
1503        );
1504    }
1505
1506    #[cfg(feature = "zenoh")]
1507    #[test]
1508    fn listen_endpoints_tolerate_an_absent_or_empty_extra_var() {
1509        assert_eq!(
1510            listen_endpoints_from_env(Some("tcp/127.0.0.1:41000"), None),
1511            vec!["tcp/127.0.0.1:41000".to_string()]
1512        );
1513        assert_eq!(
1514            listen_endpoints_from_env(Some("tcp/127.0.0.1:41000"), Some("")),
1515            vec!["tcp/127.0.0.1:41000".to_string()]
1516        );
1517        assert!(listen_endpoints_from_env(None, None).is_empty());
1518    }
1519
1520    /// A hand-set list in either variable keeps working, so an operator who
1521    /// already scripted a comma-separated `DORA_ZENOH_LISTEN` is not broken by
1522    /// the split.
1523    #[cfg(feature = "zenoh")]
1524    #[test]
1525    fn listen_endpoints_still_accept_a_list_in_either_var() {
1526        assert_eq!(
1527            listen_endpoints_from_env(Some("tcp/127.0.0.1:41000, tcp/10.0.0.2:41001"), None),
1528            vec![
1529                "tcp/127.0.0.1:41000".to_string(),
1530                "tcp/10.0.0.2:41001".to_string()
1531            ]
1532        );
1533    }
1534
1535    #[cfg(feature = "zenoh")]
1536    #[test]
1537    fn multicast_disable_spellings_are_recognized() {
1538        for value in ["off", "0", "false", "no", "OFF", "False", "  off  "] {
1539            assert!(
1540                multicast_disabled_by_value(Some(value)),
1541                "{value:?} should disable multicast scouting"
1542            );
1543        }
1544    }
1545
1546    #[cfg(feature = "zenoh")]
1547    #[test]
1548    fn unset_or_unrecognized_multicast_value_keeps_default() {
1549        // Anything that is not an explicit disable spelling must leave the
1550        // default behaviour: silently dropping discovery because of a typo
1551        // would be a partition with no error to point at (#1856).
1552        assert!(!multicast_disabled_by_value(None));
1553        for value in ["on", "1", "true", "yes", "", "maybe"] {
1554            assert!(
1555                !multicast_disabled_by_value(Some(value)),
1556                "{value:?} must not disable multicast scouting"
1557            );
1558        }
1559    }
1560
1561    /// A caller's own request must survive the fold, whatever the environment
1562    /// says. The environment half is covered by the value tests above; this
1563    /// pins that [`multicast_disabled`] never *weakens* an explicit request —
1564    /// the daemon forwards its result to every node it spawns.
1565    #[cfg(feature = "zenoh")]
1566    #[test]
1567    fn an_explicit_multicast_disable_is_never_lost() {
1568        assert!(multicast_disabled(true));
1569    }
1570
1571    #[test]
1572    fn reserve_loopback_endpoint_returns_loopback_tcp() {
1573        let endpoint = reserve_loopback_zenoh_endpoint().expect("reservation succeeds");
1574        assert!(
1575            endpoint.starts_with("tcp/127.0.0.1:"),
1576            "expected loopback tcp endpoint, got {endpoint}"
1577        );
1578        let port: u16 = endpoint
1579            .rsplit(':')
1580            .next()
1581            .and_then(|p| p.parse().ok())
1582            .expect("endpoint has a numeric port");
1583        assert!(port > 0, "kernel must hand out a non-zero ephemeral port");
1584    }
1585
1586    // A local coordinator means every zenoh peer is on this host, so we must
1587    // keep binding loopback — a single-machine daemon should not start
1588    // listening on the network just because this code path exists.
1589    #[test]
1590    fn local_coordinator_keeps_the_listener_on_loopback() {
1591        for addr in ["127.0.0.1:6013", "[::1]:6013"] {
1592            let addr: SocketAddr = addr.parse().unwrap();
1593            assert_eq!(
1594                zenoh_bind_address_for(addr),
1595                LOCALHOST,
1596                "a loopback coordinator at {addr} must not move the listener off loopback"
1597            );
1598        }
1599    }
1600
1601    // IPv6 endpoints must be bracketed or zenoh cannot parse the port back off
1602    // (`tcp/::1:7447` is ambiguous).
1603    #[test]
1604    fn ipv6_endpoints_are_bracketed() {
1605        match reserve_zenoh_endpoint(IpAddr::V6(std::net::Ipv6Addr::LOCALHOST)) {
1606            Ok(endpoint) => assert!(
1607                endpoint.starts_with("tcp/[::1]:"),
1608                "expected a bracketed IPv6 endpoint, got {endpoint}"
1609            ),
1610            // Many CI runners, Docker containers, and locked-down hosts have no
1611            // IPv6 address on `lo`, so binding `::1` fails with EAFNOSUPPORT
1612            // (`Unsupported`) or `AddrNotAvailable`. That is a property of the
1613            // host, not of the endpoint formatting under test, so skip rather
1614            // than fail — the production path never binds `::1` on such hosts.
1615            Err(e)
1616                if matches!(
1617                    e.kind(),
1618                    std::io::ErrorKind::AddrNotAvailable | std::io::ErrorKind::Unsupported
1619                ) || e.raw_os_error() == Some(97) => {}
1620            Err(e) => panic!("unexpected error reserving ::1 endpoint: {e}"),
1621        }
1622    }
1623
1624    // The filter behind the routing lookup, tested directly rather than through
1625    // the runner's routing table (which would make the assertion depend on the
1626    // machine and, for a remote target, be satisfiable by either branch).
1627    #[test]
1628    fn only_concrete_routable_sources_are_advertisable() {
1629        // Real interface addresses are what we want to advertise.
1630        for ok in ["10.0.2.100", "192.168.1.7", "100.64.0.3"] {
1631            let addr: IpAddr = ok.parse().unwrap();
1632            assert_eq!(
1633                usable_source(addr),
1634                Some(addr),
1635                "{ok} is a concrete routable address and must be advertisable"
1636            );
1637        }
1638        // A wildcard is not a source at all, and a loopback source for a remote
1639        // target means the routing table told us nothing — advertising either
1640        // points peers at nothing.
1641        for rejected in ["0.0.0.0", "127.0.0.1", "::", "::1"] {
1642            let addr: IpAddr = rejected.parse().unwrap();
1643            assert_eq!(
1644                usable_source(addr),
1645                None,
1646                "{rejected} must never be advertised to peers as a locator"
1647            );
1648        }
1649    }
1650
1651    // The wildcard cannot be advertised: zenoh binds every interface but reports
1652    // a concrete locator, so the listener check can never match it and the
1653    // daemon would silently stop advertising an endpoint to its nodes —
1654    // reintroducing the gossip race #2716 removed. Reject it up front instead.
1655    #[test]
1656    fn wildcard_zenoh_listen_is_rejected() {
1657        for wildcard in ["0.0.0.0", "::"] {
1658            let addr: IpAddr = wildcard.parse().unwrap();
1659            let err = validate_zenoh_listen(addr)
1660                .expect_err("wildcard listen address must be rejected, not accepted");
1661            assert!(
1662                err.to_string().contains("concrete"),
1663                "error should tell the operator to pass a concrete address, got: {err}"
1664            );
1665        }
1666    }
1667
1668    // An IPv6 endpoint must bracket its address, or the port colon is
1669    // indistinguishable from the address colons and `insert_json5` rejects the
1670    // locator outright (#3041). A named-port endpoint has to match the shape
1671    // `reserve_zenoh_endpoint` produces, because both end up in the same
1672    // `listen/endpoints` list and are compared verbatim against
1673    // `info().locators()` after open.
1674    #[test]
1675    fn zenoh_endpoint_brackets_ipv6_and_matches_the_reserved_shape() {
1676        assert_eq!(
1677            zenoh_endpoint("10.0.2.100".parse().unwrap(), 5456),
1678            "tcp/10.0.2.100:5456"
1679        );
1680        assert_eq!(
1681            zenoh_endpoint("::1".parse().unwrap(), 5456),
1682            "tcp/[::1]:5456"
1683        );
1684
1685        let reserved = reserve_zenoh_endpoint(LOCALHOST).expect("loopback reservation");
1686        let port = reserved
1687            .rsplit_once(':')
1688            .expect("reserved endpoint carries a port")
1689            .1
1690            .parse()
1691            .expect("reserved port is numeric");
1692        assert_eq!(zenoh_endpoint(LOCALHOST, port), reserved);
1693    }
1694
1695    // `--zenoh-listen` takes both forms, and which one was given decides
1696    // whether peers can dial this daemon before it has announced anything.
1697    #[test]
1698    fn zenoh_listen_parses_address_with_and_without_port() {
1699        let addr_only: ZenohListen = "10.0.2.100".parse().unwrap();
1700        assert_eq!(addr_only.addr, "10.0.2.100".parse::<IpAddr>().unwrap());
1701        assert_eq!(addr_only.port, None);
1702
1703        let with_port: ZenohListen = "10.0.2.100:5456".parse().unwrap();
1704        assert_eq!(with_port.port, Some(5456));
1705        assert_eq!(with_port.endpoint().unwrap(), "tcp/10.0.2.100:5456");
1706
1707        // IPv6 needs brackets to carry a port; unbracketed, the trailing group
1708        // is part of the address. Both parse — they just mean different things,
1709        // which is why the flag docs insist on brackets.
1710        let v6_port: ZenohListen = "[fd7a:1::2]:5456".parse().unwrap();
1711        assert_eq!(v6_port.port, Some(5456));
1712        assert_eq!(v6_port.endpoint().unwrap(), "tcp/[fd7a:1::2]:5456");
1713        let v6_bare: ZenohListen = "fd7a:1::2:5456".parse().unwrap();
1714        assert_eq!(v6_bare.port, None);
1715    }
1716
1717    // A wildcard has nothing to advertise, and port 0 would advertise `:0`.
1718    // Both are rejected at parse time so the operator hears about it at the
1719    // command line rather than as a silent partition later.
1720    #[test]
1721    fn zenoh_listen_rejects_unadvertisable_forms() {
1722        for bad in ["0.0.0.0", "0.0.0.0:5456", "::"] {
1723            let err = bad
1724                .parse::<ZenohListen>()
1725                .expect_err("wildcard must be rejected");
1726            assert!(
1727                err.contains("concrete"),
1728                "unexpected error for {bad}: {err}"
1729            );
1730        }
1731        let err = "10.0.2.100:0"
1732            .parse::<ZenohListen>()
1733            .expect_err("port 0 must be rejected");
1734        assert!(err.contains("port 0"), "unexpected error: {err}");
1735
1736        let err = "not-an-address"
1737            .parse::<ZenohListen>()
1738            .expect_err("garbage must be rejected");
1739        assert!(err.contains("neither"), "unexpected error: {err}");
1740    }
1741
1742    // The endpoint lists merge with dora's rather than replacing them — the
1743    // whole difference between an overlay and `ZENOH_CONFIG`. Naming a router
1744    // must add a path to it, not delete the direct node links dora planned.
1745    #[cfg(feature = "zenoh")]
1746    #[test]
1747    fn an_overlay_splits_off_the_endpoint_lists() {
1748        let overlay = ZenohOverlay::parse(
1749            r#"{
1750                // a router of our own, plus a second listen address
1751                connect: { endpoints: ["tcp/10.0.0.1:7447"], timeout_ms: 5000 },
1752                listen: { endpoints: ["tcp/10.0.0.2:7448"] },
1753                scouting: { multicast: { enabled: true } },
1754            }"#,
1755        )
1756        .expect("valid overlay");
1757
1758        assert_eq!(overlay.connect_endpoints, ["tcp/10.0.0.1:7447"]);
1759        assert_eq!(overlay.listen_endpoints, ["tcp/10.0.0.2:7448"]);
1760        // `endpoints` is taken out of the sections so re-applying them cannot
1761        // overwrite the merged list; a section left empty is dropped entirely.
1762        assert!(overlay.rest.contains_key("connect"));
1763        assert!(!overlay.rest.contains_key("listen"));
1764        assert!(overlay.rest.contains_key("scouting"));
1765    }
1766
1767    // An overlay is applied to a real config: the values must land where zenoh
1768    // expects them, and a subkey must not wipe its siblings.
1769    #[cfg(feature = "zenoh")]
1770    #[test]
1771    fn an_overlay_applies_onto_a_zenoh_config() {
1772        let mut config = zenoh::Config::default();
1773        config
1774            .insert_json5("connect/endpoints", r#"["tcp/127.0.0.1:1"]"#)
1775            .expect("dora's own endpoints");
1776
1777        ZenohOverlay::parse(r#"{ connect: { timeout_ms: 5000 }, mode: "peer" }"#)
1778            .expect("valid overlay")
1779            .apply(&mut config)
1780            .expect("overlay applies");
1781
1782        let rendered = config.to_string();
1783        assert!(
1784            rendered.contains("5000"),
1785            "overlay value missing: {rendered}"
1786        );
1787        assert!(
1788            rendered.contains("tcp/127.0.0.1:1"),
1789            "writing a sibling subkey must not wipe dora's endpoints: {rendered}"
1790        );
1791    }
1792
1793    // A malformed overlay must fail loudly: the operator asked for these
1794    // settings, and a session quietly opened without them is the "runs but
1795    // talks to nobody" outcome that takes hours to diagnose.
1796    #[cfg(feature = "zenoh")]
1797    #[test]
1798    fn a_malformed_overlay_is_rejected() {
1799        for (bad, expected) in [
1800            ("not an object", "object"),
1801            (
1802                r#"{ connect: { endpoints: "tcp/10.0.0.1:7447" } }"#,
1803                "array",
1804            ),
1805            (r#"{ listen: { endpoints: [7447] } }"#, "endpoint strings"),
1806        ] {
1807            let err = ZenohOverlay::parse(bad)
1808                .expect_err("must be rejected")
1809                .to_string();
1810            assert!(
1811                err.contains(expected),
1812                "unexpected error for `{bad}`: {err}"
1813            );
1814        }
1815    }
1816
1817    #[cfg(feature = "zenoh")]
1818    #[test]
1819    fn deterministic_zenoh_config_open_timeout() {
1820        let params = ZenohSessionParams::default();
1821        let built = build_zenoh_config(&params, None).expect("builds default config");
1822        assert_eq!(
1823            *built.config.transport().unicast().open_timeout(),
1824            DEFAULT_ZENOH_UNICAST_OPEN_TIMEOUT_MS
1825        );
1826
1827        // Overlay overrides the open_timeout:
1828        let overlay = ZenohOverlay::parse(r#"{ transport: { unicast: { open_timeout: 4000 } } }"#)
1829            .expect("valid overlay");
1830        let built_overlay =
1831            build_zenoh_config(&params, Some(&overlay)).expect("builds config with overlay");
1832        assert_eq!(
1833            *built_overlay.config.transport().unicast().open_timeout(),
1834            4000
1835        );
1836    }
1837
1838    #[cfg(feature = "zenoh")]
1839    #[test]
1840    fn test_parse_zenoh_open_timeout() {
1841        assert_eq!(
1842            parse_zenoh_open_timeout(None),
1843            DEFAULT_ZENOH_UNICAST_OPEN_TIMEOUT_MS
1844        );
1845        assert_eq!(parse_zenoh_open_timeout(Some(" 2500 ")), 2500);
1846        assert_eq!(
1847            parse_zenoh_open_timeout(Some("not-a-number")),
1848            DEFAULT_ZENOH_UNICAST_OPEN_TIMEOUT_MS
1849        );
1850        // A zero deadline would fail every dial that is not ready on its
1851        // first poll, so it is rejected like an unparseable value.
1852        assert_eq!(
1853            parse_zenoh_open_timeout(Some("0")),
1854            DEFAULT_ZENOH_UNICAST_OPEN_TIMEOUT_MS
1855        );
1856        assert_eq!(parse_zenoh_open_timeout(Some("1")), 1);
1857    }
1858
1859    #[cfg(feature = "zenoh")]
1860    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1861    async fn unreachable_peer_teardown_bounded() {
1862        use std::time::Instant;
1863        use zenoh::Wait;
1864
1865        let (session, _) = open_zenoh_session_with_listen(ZenohSessionParams {
1866            connect_endpoints: &["tcp/198.51.100.1:7447".to_string()],
1867            ..Default::default()
1868        })
1869        .await
1870        .unwrap();
1871
1872        let sub = session.declare_subscriber("test/topic").wait().unwrap();
1873        let publ = session.declare_publisher("test/topic").wait().unwrap();
1874
1875        let start = Instant::now();
1876        drop(publ);
1877        drop(sub);
1878        drop(session);
1879
1880        assert!(start.elapsed() < std::time::Duration::from_secs(5));
1881    }
1882
1883    // Concrete addresses pass validation whether or not they exist on this host:
1884    // existence is not knowable here and surfaces as a bind error instead.
1885    #[test]
1886    fn concrete_zenoh_listen_addresses_are_accepted() {
1887        for ok in ["127.0.0.1", "10.0.2.100", "::1"] {
1888            let addr: IpAddr = ok.parse().unwrap();
1889            assert!(
1890                validate_zenoh_listen(addr).is_ok(),
1891                "{ok} is concrete and must pass validation"
1892            );
1893        }
1894    }
1895
1896    // Node raw output and daemon control frames MUST live on distinct Zenoh
1897    // keys: they share neither format nor consumer, and merging them caused the
1898    // #1992 crossover (daemon postcard-decoding node output). Guard the split.
1899    #[cfg(feature = "zenoh")]
1900    #[test]
1901    fn output_and_control_topics_are_distinct() {
1902        use dora_message::id::{DataId, NodeId};
1903
1904        let dataflow_id = uuid::Uuid::nil();
1905        let node = NodeId::from("node".to_string());
1906        let output = DataId::from("out".to_string());
1907
1908        let output_topic = zenoh_output_publish_topic(dataflow_id, &node, &output);
1909        let control_topic = zenoh_daemon_control_topic(dataflow_id, &node, &output);
1910
1911        assert!(
1912            output_topic.contains("/output/"),
1913            "node output key must contain `/output/`, got {output_topic}"
1914        );
1915        assert!(
1916            control_topic.contains("/control/"),
1917            "daemon control key must contain `/control/`, got {control_topic}"
1918        );
1919        assert_ne!(
1920            output_topic, control_topic,
1921            "node output and daemon control must not share a Zenoh key (dora #1992/#2008)"
1922        );
1923    }
1924
1925    // Data, schema, ack, and control keys for the same (node, output) must all
1926    // be distinct: each carries a different payload format for a different
1927    // consumer, and any overlap would cross-deliver frames to a decoder that
1928    // cannot parse them.
1929    #[cfg(feature = "zenoh")]
1930    #[test]
1931    fn per_output_topics_are_distinct() {
1932        use dora_message::id::{DataId, NodeId};
1933
1934        let dataflow_id = uuid::Uuid::nil();
1935        let node = NodeId::from("node".to_string());
1936        let output = DataId::from("out".to_string());
1937
1938        let topics = [
1939            zenoh_output_publish_topic(dataflow_id, &node, &output),
1940            zenoh_output_schema_topic(dataflow_id, &node, &output),
1941            zenoh_output_ack_topic(dataflow_id, &node, &output),
1942            zenoh_daemon_control_topic(dataflow_id, &node, &output),
1943        ];
1944        for (i, a) in topics.iter().enumerate() {
1945            for b in &topics[i + 1..] {
1946                assert_ne!(a, b, "per-output zenoh keys must not overlap");
1947            }
1948        }
1949    }
1950
1951    // zenoh-ext publisher-detection liveliness uses
1952    // `${remaining:**}/@adv/...`. Verbatim (`@…`) chunks are hermetic, so a
1953    // schema key that itself introduced `/@schema` before `/@adv/` made tokens
1954    // unparseable and flooded WARN logs (#2923). Keep the schema key free of
1955    // `@` chunks (AdvancedPublisher + publisher_detection still used).
1956    #[cfg(feature = "zenoh")]
1957    #[test]
1958    fn schema_topic_has_no_verbatim_chunks() {
1959        use dora_message::id::{DataId, NodeId};
1960
1961        let dataflow_id = uuid::Uuid::nil();
1962        let node = NodeId::from("node".to_string());
1963        let output = DataId::from("out".to_string());
1964        let topic = zenoh_output_schema_topic(dataflow_id, &node, &output);
1965
1966        assert!(
1967            topic.contains("/schema/"),
1968            "schema side-channel must live under the dedicated `/schema/` plane, got {topic}"
1969        );
1970        assert!(
1971            !topic.contains("/output/"),
1972            "schema side-channel must not nest under the data-topic `/output/` path, got {topic}"
1973        );
1974        for chunk in topic.split('/') {
1975            assert!(
1976                !chunk.starts_with('@'),
1977                "schema topic chunk `{chunk}` must not be verbatim (`@…`); \
1978                 otherwise zenoh_ext liveliness tokens fail to parse (#2923)"
1979            );
1980        }
1981    }
1982
1983    // `/_schema` nested under the output path collided with a valid DataId
1984    // `cmd/_schema`. The schema plane must stay outside `output/{node}/{data_id}`.
1985    #[cfg(feature = "zenoh")]
1986    #[test]
1987    fn schema_topic_does_not_collide_with_nested_data_id() {
1988        use dora_message::id::{DataId, NodeId};
1989
1990        let dataflow_id = uuid::Uuid::nil();
1991        let node = NodeId::from("node".to_string());
1992        let parent = DataId::from("cmd");
1993        let nested = DataId::from("cmd/_schema");
1994        assert_ne!(
1995            zenoh_output_schema_topic(dataflow_id, &node, &parent),
1996            zenoh_output_publish_topic(dataflow_id, &node, &nested),
1997        );
1998    }
1999
2000    // The ack design relies on exact-key matching instead of wildcards, so an
2001    // output id that is a chunk-prefix of another (`cmd` vs `cmd/vel` — the
2002    // collision that forced hex-encoded keys in the #2666 liveliness design)
2003    // must yield distinct ack keys with no subsumption possible.
2004    #[cfg(feature = "zenoh")]
2005    #[test]
2006    fn ack_topics_of_prefix_outputs_are_distinct() {
2007        use dora_message::id::{DataId, NodeId};
2008
2009        let dataflow_id = uuid::Uuid::nil();
2010        let node = NodeId::from("node".to_string());
2011        let cmd = DataId::from("cmd".to_string());
2012        let cmd_vel = DataId::from("cmd/vel".to_string());
2013
2014        let cmd_ack = zenoh_output_ack_topic(dataflow_id, &node, &cmd);
2015        let cmd_vel_ack = zenoh_output_ack_topic(dataflow_id, &node, &cmd_vel);
2016
2017        assert_ne!(cmd_ack, cmd_vel_ack);
2018        // `cmd`'s ack key ends in `cmd/@ack`; the nested output's key contains
2019        // `cmd/vel/@ack`. Neither is a prefix of the other, so exact-key
2020        // subscribers can never receive the other output's acks.
2021        assert!(cmd_ack.ends_with("/cmd/@ack"));
2022        assert!(cmd_vel_ack.ends_with("/cmd/vel/@ack"));
2023        assert!(!cmd_vel_ack.starts_with(&cmd_ack));
2024        assert!(!cmd_ack.starts_with(&cmd_vel_ack));
2025    }
2026}