mt_sea 0.15.1

Primitives for a Minot network.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use std::net::{SocketAddr, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use log::{info, warn};

pub const DEFAULT_ZENOH_PORT: u16 = 7447;

/// Default endpoint; configured sessions honor `MINOT_ZENOH_PORT`.
pub const LOCAL_COORD_ENDPOINT: &str = "tcp/127.0.0.1:7447";
/// Default endpoint; configured sessions honor `MINOT_ZENOH_PORT`.
pub const NETWORK_COORD_ENDPOINT: &str = "tcp/0.0.0.0:7447";

static LOCAL_ONLY: AtomicBool = AtomicBool::new(false);
/// Dedicated services can listen on the LAN without merging with every Minot
/// router found through multicast discovery.
static UNICAST_ONLY: AtomicBool = AtomicBool::new(false);

#[cfg(feature = "shm")]
static SHM_RUNTIME_AVAILABLE: AtomicBool = AtomicBool::new(true);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NetworkRole {
    Client,
    Coordinator,
    PubSubPeer,
}

/// Restrict subsequently created Minot Zenoh sessions to IPv4 loopback.
///
/// This must be called before starting any clients or coordinators.
pub fn set_local_only(enabled: bool) {
    LOCAL_ONLY.store(enabled, Ordering::SeqCst);
}

pub fn is_local_only() -> bool {
    LOCAL_ONLY.load(Ordering::SeqCst)
}

/// Disable discovery for subsequently created sessions while retaining the
/// network listening address. Must be called before creating any sessions.
pub fn set_unicast_only(enabled: bool) {
    UNICAST_ONLY.store(enabled, Ordering::SeqCst);
}

pub fn is_unicast_only() -> bool {
    UNICAST_ONLY.load(Ordering::SeqCst)
}

#[cfg(feature = "shm")]
pub(crate) fn is_shm_runtime_available() -> bool {
    SHM_RUNTIME_AVAILABLE.load(Ordering::Acquire)
}

#[cfg(feature = "shm")]
pub(crate) fn is_shm_disabled() -> bool {
    std::env::var("MINOT_SHM_DISABLED")
        .map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
        .unwrap_or(false)
}

#[cfg(feature = "shm")]
pub(crate) fn disable_shm_runtime() {
    SHM_RUNTIME_AVAILABLE.store(false, Ordering::Release);
}

/// TCP port used for the local coordinator probe and coordinator endpoints.
///
/// Set `MINOT_ZENOH_PORT` before creating any Minot sessions. All nodes sharing
/// a coordinator must use the same value. Unset values use 7447; invalid or
/// zero values warn and fall back to 7447. Explicit `MINOT_COORD_ADDR`
/// endpoints retain their own port.
pub fn coordinator_port() -> u16 {
    match std::env::var("MINOT_ZENOH_PORT") {
        Ok(value) => match value.parse::<u16>() {
            Ok(port) if port != 0 => port,
            _ => {
                warn!("Invalid MINOT_ZENOH_PORT '{value}', selecting default {DEFAULT_ZENOH_PORT}");
                DEFAULT_ZENOH_PORT
            }
        },
        Err(std::env::VarError::NotPresent) => DEFAULT_ZENOH_PORT,
        Err(error) => {
            warn!("Invalid MINOT_ZENOH_PORT: {error}, selecting default {DEFAULT_ZENOH_PORT}");
            DEFAULT_ZENOH_PORT
        }
    }
}

/// The port `MINOT_ZENOH_PORT` names, if it is set to a usable one.
pub(crate) fn coordinator_port_from_env() -> Option<u16> {
    std::env::var("MINOT_ZENOH_PORT")
        .ok()
        .and_then(|value| value.parse::<u16>().ok())
        .filter(|port| *port != 0)
}

/// Return whether something is accepting connections on the local coordinator endpoint.
/// This is used to decide whether an auto-start node must create the router before
/// opening its client session. It preserves local-only configuration.
pub fn local_router_is_running() -> bool {
    let address = SocketAddr::from(([127, 0, 0, 1], coordinator_port()));
    TcpStream::connect_timeout(&address, Duration::from_millis(100)).is_ok()
}

pub fn zenoh_config(role: NetworkRole) -> zenoh::Config {
    if role == NetworkRole::PubSubPeer {
        return peer_config_for(is_local_only(), is_unicast_only(), coordinator_port());
    }
    config_for(
        role,
        is_local_only(),
        is_unicast_only(),
        std::env::var("MINOT_COORD_ADDR").ok(),
        role == NetworkRole::Coordinator && local_router_is_running(),
        coordinator_port(),
    )
}

fn peer_config_for(local: bool, unicast_only: bool, port: u16) -> zenoh::Config {
    let multicast = !unicast_only;
    // Off-host peers get a TCP and a UDP link (zenoh multilink). zenoh sends
    // best-effort puts over the UDP link, while declarations, queries and
    // reliable samples stay on TCP, so a lost datagram never loses a
    // subscription. Loopback peers keep a single TCP link: local UDP
    // overflows the default socket buffers with large samples.
    let (endpoints, max_links) = if local {
        (r#""tcp/127.0.0.1:0""#, 1)
    } else {
        (r#""tcp/0.0.0.0:0","udp/0.0.0.0:0""#, 2)
    };
    let mut config = zenoh::Config::from_json5(&format!(
            r#"{{mode:"peer",listen:{{endpoints:[{endpoints}]}},transport:{{unicast:{{max_links:{max_links}}}}},scouting:{{multicast:{{enabled:{multicast},address:"224.0.0.224:{port}",autoconnect:["peer"],listen:true}},gossip:{{enabled:true,multihop:false,autoconnect:["peer"]}}}}}}"#
        )).expect("internal peer configuration must be valid");
    if local {
        // Every local listener is reachable in both directions. Let only one
        // side initiate each connection, avoiding duplicate discovery connects.
        for method in ["multicast", "gossip"] {
            config
                .insert_json5(
                    &format!("scouting/{method}/autoconnect_strategy"),
                    "\"greater-zid\"",
                )
                .expect("local peer autoconnect strategy");
        }
        config
            .insert_json5("scouting/multicast/interface", "\"127.0.0.1\"")
            .expect("loopback interface configuration");
    }
    config
}

/// Open a Zenoh session, retrying without shared memory if SHM initialization fails.
pub(crate) fn open_zenoh_session(role: NetworkRole) -> anyhow::Result<zenoh::Session> {
    open_zenoh_session_with_config(zenoh_config(role))
}

/// Open a configured session with the same SHM fallback used by Minot ships.
pub fn open_zenoh_session_with_config(config: zenoh::Config) -> anyhow::Result<zenoh::Session> {
    use zenoh::Wait;
    #[cfg(feature = "shm")]
    let config = {
        let mut config = config;
        if is_shm_runtime_available() && !is_shm_disabled() {
            disable_implicit_shm_transport(&mut config)?;
        } else {
            disable_shm_in_config(&mut config)?;
        }
        config
    };
    #[cfg(not(feature = "shm"))]
    let config = {
        let mut config = config;
        // Be explicit even though Zenoh was compiled without its SHM implementation:
        // this peer must never advertise SHM capability during link negotiation.
        disable_shm_in_config(&mut config)?;
        config
    };

    #[cfg(feature = "shm")]
    let fallback_config = config.clone();
    match zenoh::open(config).wait() {
        Ok(session) => Ok(session),
        Err(error) => {
            #[cfg(feature = "shm")]
            {
                if !is_shm_initialization_error(&error.to_string()) {
                    return Err(anyhow::anyhow!("Failed to open Zenoh session: {error}"));
                }
                warn!("Zenoh SHM initialization failed: {error}. Retrying with network transport");
                disable_shm_runtime();
                let mut fallback = fallback_config;
                disable_shm_in_config(&mut fallback)?;
                zenoh::open(fallback)
                    .wait()
                    .map_err(|fallback_error| {
                        anyhow::anyhow!(
                            "Failed to open Zenoh session with SHM ({error}) and without SHM ({fallback_error})"
                        )
                    })
            }

            #[cfg(not(feature = "shm"))]
            Err(anyhow::anyhow!("Failed to open Zenoh session: {error}"))
        }
    }
}

#[cfg(feature = "shm")]
fn is_shm_initialization_error(error: &str) -> bool {
    let error = error.to_ascii_lowercase();
    error.contains("shared memory")
        || error.contains("shared-memory")
        || error.contains("posix shm")
        || error.contains("shm segment")
}

fn disable_shm_in_config(config: &mut zenoh::Config) -> anyhow::Result<()> {
    config
        .insert_json5("transport/shared_memory/enabled", "false")
        .map_err(|error| anyhow::anyhow!("Failed to disable Zenoh shared memory: {error}"))?;
    disable_implicit_shm_transport(config)?;
    Ok(())
}

fn disable_implicit_shm_transport(config: &mut zenoh::Config) -> anyhow::Result<()> {
    config
        .insert_json5(
            "transport/shared_memory/transport_optimization/enabled",
            "false",
        )
        .map_err(|error| {
            anyhow::anyhow!("Failed to disable Zenoh SHM transport optimization: {error}")
        })
}

fn config_for(
    role: NetworkRole,
    local_only: bool,
    unicast_only: bool,
    coordinator_addr: Option<String>,
    local_router_running: bool,
    port: u16,
) -> zenoh::Config {
    let local_endpoint = format!("tcp/127.0.0.1:{port}");
    let network_endpoint = format!("tcp/0.0.0.0:{port}");
    if local_only {
        if coordinator_addr.is_some() {
            warn!("--local-only selected. Using {}", local_endpoint);
        }

        let json5 = match (role, local_router_running) {
            (NetworkRole::Coordinator, false) => format!(
                r#"{{mode:"router",scouting:{{multicast:{{enabled:false}},gossip:{{enabled:false}}}},listen:{{endpoints:["{}"]}}}}"#,
                local_endpoint
            ),
            // An external Zenoh router owns the endpoint. Run the Minot
            // coordinator logic on a client session connected to that router.
            (NetworkRole::Coordinator, true)
            | (NetworkRole::Client, _)
            | (NetworkRole::PubSubPeer, _) => format!(
                r#"{{mode:"client",scouting:{{multicast:{{enabled:false}},gossip:{{enabled:false}}}},connect:{{endpoints:["{}"],exit_on_failure:false}}}}"#,
                local_endpoint
            ),
        };

        info!("Using local-only networking on {}", local_endpoint);
        return zenoh::Config::from_json5(&json5)
            .expect("internal local-only Zenoh configuration must be valid");
    }

    if role == NetworkRole::Coordinator {
        let multicast = if unicast_only { "false" } else { "true" };
        let json5 = format!(
            r#"{{mode:"router",scouting:{{multicast:{{enabled:{multicast}}},gossip:{{enabled:{multicast}}}}},listen:{{endpoints:["{}"]}}}}"#,
            network_endpoint
        );
        info!("Using network coordinator endpoint on {}", network_endpoint);
        return zenoh::Config::from_json5(&json5)
            .expect("internal network coordinator Zenoh configuration must be valid");
    }

    if unicast_only && coordinator_addr.is_none() {
        let json5 = format!(
            r#"{{mode:"client",scouting:{{multicast:{{enabled:false}},gossip:{{enabled:false}}}},connect:{{endpoints:["{}"],exit_on_failure:false}}}}"#,
            local_endpoint
        );
        info!("Client using local unicast coordinator: {local_endpoint}");
        return zenoh::Config::from_json5(&json5)
            .expect("internal unicast Zenoh configuration must be valid");
    }

    if let Some(addr) = coordinator_addr {
        let json5 = format!(
            r#"{{mode:"peer",scouting:{{multicast:{{enabled:false}}}},connect:{{endpoints:["{}"]}}}}"#,
            addr
        );
        return match zenoh::Config::from_json5(&json5) {
            Ok(config) => {
                info!("Client using unicast coordinator: {}", addr);
                config
            }
            Err(error) => {
                warn!(
                    "MINOT_COORD_ADDR '{}' produced invalid config: {}, falling back to multicast",
                    addr, error
                );
                zenoh::Config::default()
            }
        };
    }

    zenoh::Config::default()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn peer_config_uses_dynamic_listeners_and_an_isolated_scouting_port() {
        let config = peer_config_for(true, false, 18447);
        assert_eq!(config.get_json("mode").unwrap(), "\"peer\"");
        assert_eq!(
            config.get_json("listen/endpoints").unwrap(),
            r#"["tcp/127.0.0.1:0"]"#
        );
        assert_eq!(
            config.get_json("scouting/multicast/address").unwrap(),
            "\"224.0.0.224:18447\""
        );
        assert_eq!(
            config.get_json("scouting/multicast/interface").unwrap(),
            "\"127.0.0.1\""
        );
        assert_eq!(
            config.get_json("scouting/gossip/multihop").unwrap(),
            "false"
        );
        for method in ["multicast", "gossip"] {
            assert_eq!(
                config
                    .get_json(&format!("scouting/{method}/autoconnect_strategy"))
                    .unwrap(),
                "\"greater-zid\""
            );
        }
        let unicast = peer_config_for(false, true, 18447);
        assert_eq!(
            unicast.get_json("scouting/multicast/enabled").unwrap(),
            "false"
        );
        assert_eq!(
            unicast.get_json("listen/endpoints").unwrap(),
            r#"["tcp/0.0.0.0:0","udp/0.0.0.0:0"]"#
        );
        assert_eq!(
            unicast.get_json("transport/unicast/max_links").unwrap(),
            "2"
        );
        assert_eq!(config.get_json("transport/unicast/max_links").unwrap(), "1");
    }

    #[test]
    fn configured_port_reaches_listeners_and_local_clients() {
        for port in [DEFAULT_ZENOH_PORT, 17447] {
            for (local_only, unicast_only) in [(true, false), (false, true)] {
                let router = config_for(
                    NetworkRole::Coordinator,
                    local_only,
                    unicast_only,
                    None,
                    false,
                    port,
                );
                let host = if local_only { "127.0.0.1" } else { "0.0.0.0" };
                assert_eq!(
                    router.get_json("listen/endpoints").unwrap(),
                    format!(r#"["tcp/{host}:{port}"]"#)
                );
                let client = config_for(
                    NetworkRole::Client,
                    local_only,
                    unicast_only,
                    None,
                    false,
                    port,
                );
                assert_eq!(
                    client.get_json("connect/endpoints").unwrap(),
                    format!(r#"["tcp/127.0.0.1:{port}"]"#)
                );
            }
            let shared_router = config_for(NetworkRole::Coordinator, true, false, None, true, port);
            assert_eq!(
                shared_router.get_json("connect/endpoints").unwrap(),
                format!(r#"["tcp/127.0.0.1:{port}"]"#)
            );
        }
    }

    #[test]
    fn explicit_coordinator_address_keeps_its_port() {
        let config = config_for(
            NetworkRole::Client,
            false,
            false,
            Some("tcp/192.0.2.1:23456".into()),
            false,
            17447,
        );
        assert_eq!(
            config.get_json("connect/endpoints").unwrap(),
            r#"["tcp/192.0.2.1:23456"]"#
        );
    }
}