Skip to main content

zenkey_fleet/bus/
scout.rs

1//! Raw scouting: the Hello layer, below sessions and liveliness (#116).
2//!
3//! `discover` answers "which deployments hold liveliness tokens or storages"
4//! — a question that presumes a working session. Scouting answers the two
5//! questions that come *before* one: "is anything out there at all" and "is
6//! multicast scouting working on this segment". It is a third, independent
7//! signal, not a replacement for either.
8//!
9//! Multicast is deliberately **on** here — scouting is what this module *is*.
10//! The session-opening default stays off (see `session::open`'s contamination
11//! warning): a scout only listens for Hellos and joins nothing.
12
13use crate::report::HelloView;
14use crate::{Error, Result};
15use zenoh::config::WhatAmIMatcher;
16use zenoh::handlers::FifoChannelHandler;
17use zenoh::scouting::Hello;
18
19impl HelloView {
20    fn of(hello: &Hello) -> Self {
21        HelloView {
22            zid: hello.zid().to_string(),
23            whatami: hello.whatami().to_string(),
24            locators: hello.locators().iter().map(|l| l.to_string()).collect(),
25        }
26    }
27}
28
29/// A running scout. Hellos arrive as the segment answers; the caller owns the
30/// deadline (wrap [`ScoutStream::recv`] in a timeout), because how long to
31/// listen is a question about the network, not about this crate.
32pub struct ScoutStream {
33    inner: zenoh::scouting::Scout<FifoChannelHandler<Hello>>,
34}
35
36impl std::fmt::Debug for ScoutStream {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        f.debug_struct("ScoutStream").finish_non_exhaustive()
39    }
40}
41
42impl ScoutStream {
43    /// The next Hello, or `None` once the scout has stopped.
44    pub async fn recv(&self) -> Option<HelloView> {
45        self.inner
46            .recv_async()
47            .await
48            .ok()
49            .map(|h| HelloView::of(&h))
50    }
51
52    /// The Hellos as a [`Stream`](futures_core::Stream), for a consumer that
53    /// composes rather than loops (#343).
54    ///
55    /// Borrows rather than consuming, so [`stop`](Self::stop) still works
56    /// afterwards — the explicit teardown is the reason this type is not just
57    /// a stream. The projection to [`HelloView`] is the same one
58    /// [`recv`](Self::recv) makes.
59    pub fn stream(&self) -> impl futures_core::Stream<Item = HelloView> + '_ {
60        futures_util::StreamExt::map(self.inner.stream(), |h| HelloView::of(&h))
61    }
62
63    /// Stop scouting, explicitly — a drop would stop it too, but silently.
64    pub fn stop(self) {
65        self.inner.stop();
66    }
67}
68
69/// Listen for scouting Hellos: multicast on, plus gossip via any `connect`
70/// endpoints, so a segment with filtered multicast can still answer.
71///
72/// `what` filters by advertised kind; combine with `|`
73/// (`WhatAmI::Router | WhatAmI::Peer`) or pass a parsed [`WhatAmIMatcher`].
74pub async fn scout(
75    what: WhatAmIMatcher,
76    connect: &[String],
77    listen: &[String],
78) -> Result<ScoutStream> {
79    let config = crate::bus::session::explorer_config(connect, listen, true);
80
81    let inner = zenoh::scout(what, config)
82        .await
83        .map_err(|e| Error::bus("scout", "", e))?;
84    Ok(ScoutStream { inner })
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    /// The CLI's ndjson row and the GUI both hang off this exact shape; a
92    /// field rename here is a wire-format change for every script piping
93    /// `zenctl scout --format ndjson`.
94    #[test]
95    fn a_hello_serializes_flat_and_stable() {
96        let view = HelloView {
97            zid: "a1b2".into(),
98            whatami: "router".into(),
99            locators: vec!["tcp/10.0.0.1:7447".into()],
100        };
101        let json = serde_json::to_value(&view).unwrap();
102        assert_eq!(
103            json,
104            serde_json::json!({
105                "zid": "a1b2",
106                "whatami": "router",
107                "locators": ["tcp/10.0.0.1:7447"],
108            })
109        );
110    }
111}