Skip to main content

modem_mgmt/
lib.rs

1//! The management plane: everything the ICD's control channel used to carry —
2//! as a library, for any driver that links the contract (#119).
3//!
4//! Decision D2 deleted that channel entirely — HELLO, capability negotiation,
5//! both snapshot protocols, TX delivery states, the security state model — on
6//! the claim that all of it is better expressed as ordinary Zenoh traffic under
7//! the keyspace-v2 convention. This module is that claim, in code.
8//!
9//! Two planes, kept apart deliberately (`docs/architecture.md` §4.1, §4.6):
10//!
11//! - The **data plane** carries opaque batches and never links against `zenoh`.
12//!   CI holds that with a dependency guard.
13//! - The **management plane** is an ordinary Zenoh client surface on the
14//!   driver's *own* session. It is feature-gated, so a driver built without it
15//!   still moves data and the data-path tests never need it.
16//!
17//! What that buys, beyond tidiness: an operator gets `zenctl` on day one, the
18//! contract is linted at build time by `zenkey-build` rather than written prose,
19//! and capability negotiation becomes a query anyone can make instead of a
20//! handshake only the link can perform.
21
22mod action;
23mod clock;
24mod config;
25pub mod conformance;
26mod destination;
27mod events;
28pub mod host;
29mod identity;
30mod oper;
31mod overlay;
32pub mod plane;
33mod radio;
34mod rpc;
35mod security;
36mod sensor;
37mod state;
38pub mod telemetry;
39
40use std::sync::Arc;
41
42use anyhow::Context as _;
43use zenkey::V1Context;
44use zenoh::Session;
45
46pub use host::{Host, Node, Plane};
47pub use modem_contract::documents::{
48    Ack, ActionEvent, ActionOutcome, ActionRequest, Capabilities, DestinationState, DeviceFault,
49    Duplex, EndpointLane, EndpointState, Identity, IdentityChange, Lane, LaneTable, LinkState,
50    Oper, OperChange, RadioState, SecurityState, Sensor,
51};
52pub use modem_contract::{PRODUCER, PROFILE};
53pub use plane::{LaneView, SchedulerCounters, SduPlane};
54pub use telemetry::subjects as telemetry_subjects;
55
56/// How to reach the local bus.
57#[derive(Clone, Debug, serde::Deserialize)]
58#[serde(deny_unknown_fields)]
59pub struct MgmtConfig {
60    /// Endpoints to connect to, e.g. `["tcp/127.0.0.1:7447"]`.
61    #[serde(default)]
62    pub connect: Vec<String>,
63    /// Endpoints to listen on, if this driver should accept instead.
64    #[serde(default)]
65    pub listen: Vec<String>,
66    /// Whether to allow multicast scouting.
67    ///
68    /// Off by default. On a node whose uplink is a radio, scouting is pure
69    /// cost, and a driver that joined whatever mesh it found would be a
70    /// surprise rather than a feature.
71    #[serde(default)]
72    pub scouting: bool,
73    /// The management session's Zenoh mode: `client`, `peer` or `router`.
74    ///
75    /// Unset, it is **`client` when the session only connects** and `peer`
76    /// when it listens (#152). A session that connects is attaching to the
77    /// node's own `zenohd`, as any local application does, and a client is
78    /// what that router serves without gossip. The shipped routers disable
79    /// gossip, because on a 2400 bit/s link it is pure cost, and a *peer*
80    /// attached to such a router is invisible to everything else on it:
81    /// `zenctl node list` through `zenohd-rf0.json5` found no producer at
82    /// all until this was a client.
83    #[serde(default)]
84    pub mode: Option<String>,
85    /// Credentials the session presents, for a router that authenticates
86    /// (#98). A router holding a `usrpwd` dictionary refuses *every* link
87    /// without credentials, this one included (`auth_face.rs`).
88    ///
89    /// The password is read from a file, so it never sits in this one, and
90    /// is never logged.
91    #[serde(default)]
92    pub usrpwd: Option<UsrPwd>,
93    /// Seconds a `state` document stays fresh. Refreshed at half this.
94    ///
95    /// zenkey requires every `state` subject to carry one: a reader must be
96    /// able to tell "unchanged" from "gone".
97    ///
98    /// The default is **the registry's**, not a number written here, because a
99    /// document that advertises a freshness the contract does not declare is a
100    /// document a consumer cannot trust. An operator may lower it — refreshing
101    /// more often than promised is safe, and the tests do exactly that — but
102    /// [`Mgmt::start`] refuses to raise it above the declared bound.
103    #[serde(default = "default_ttl")]
104    pub ttl_s: u64,
105    /// Milliseconds between telemetry sweeps.
106    ///
107    /// **A cost knob, and §4.6 is the argument for having one.** Seventeen
108    /// counters every five seconds is 3.6 publications a second for ever, which
109    /// is why both shipped routers deny the management plane on the radio. An
110    /// operator whose bus is a 2400 bit/s channel wants sixty seconds; one
111    /// watching a bring-up wants one. Five seconds is a default, not a law, and
112    /// it was previously a `const` nobody could reach.
113    ///
114    /// Milliseconds rather than seconds because the tests that read counters
115    /// off the wire should not each wait out a production cadence — that alone
116    /// was 96 s of a 244 s suite.
117    #[serde(default = "default_telemetry_interval_ms")]
118    pub telemetry_interval_ms: u64,
119    /// Where `persist` keeps a confirmed change across restarts (#128): one
120    /// `<device>.overlay.toml` per device, `0600`. Unset, the unit's
121    /// `StateDirectory` (`$STATE_DIRECTORY`) is used when systemd provides
122    /// one; with neither, nothing persists and `persist` says so.
123    #[serde(default)]
124    pub state_dir: Option<std::path::PathBuf>,
125    /// The provisional boot (#128): seconds after boot by which a device
126    /// started under an overlay must be `up`, or the overlay is set aside
127    /// and the startup file alone applies — once, with an event. Unset,
128    /// an overlay is trusted. A persisted change that cuts a remote node
129    /// off must not survive a power cycle; this is the operator's deadline
130    /// for that, in the operator's file (I1).
131    #[serde(default)]
132    pub provisional_boot_s: Option<u64>,
133}
134
135/// A `usrpwd` identity for the management session (#98).
136#[derive(Clone, Debug, serde::Deserialize)]
137#[serde(deny_unknown_fields)]
138pub struct UsrPwd {
139    /// The user name, which the router's ACL may grant by (`usernames`).
140    pub user: String,
141    /// A file holding the password and nothing else; a trailing newline is
142    /// ignored. Readable by the daemon only (`0600`).
143    pub password_file: std::path::PathBuf,
144}
145
146fn default_telemetry_interval_ms() -> u64 {
147    // The constant is the source, so the default and the cost argument §4.6 is
148    // written in cannot drift apart.
149    telemetry::DEFAULT_INTERVAL.as_millis() as u64
150}
151
152fn default_ttl() -> u64 {
153    state::declared_ttl_s()
154}
155
156impl Default for MgmtConfig {
157    fn default() -> Self {
158        Self {
159            connect: Vec::new(),
160            listen: Vec::new(),
161            scouting: false,
162            mode: None,
163            usrpwd: None,
164            ttl_s: default_ttl(),
165            telemetry_interval_ms: default_telemetry_interval_ms(),
166            state_dir: None,
167            provisional_boot_s: None,
168        }
169    }
170}
171
172/// A running management plane.
173///
174/// Holds the liveliness token: dropping this makes the driver disappear from
175/// every roster, which is the intended way to say "gone" rather than "quiet".
176pub struct Mgmt {
177    session: Session,
178    ctx: V1Context,
179    tasks: Vec<tokio::task::JoinHandle<()>>,
180    _alive: zenoh::liveliness::LivelinessToken,
181    /// One per device the host serves (RFC 04 §5).
182    _device_alive: Arc<
183        std::sync::Mutex<std::collections::BTreeMap<String, zenoh::liveliness::LivelinessToken>>,
184    >,
185}
186
187/// Serve every device on the host: open the session, declare presence, and
188/// start publishing. The one call a driver makes (#119); [`Mgmt::start`] is
189/// the same function under the name the daemon has always used.
190pub async fn serve(cfg: &MgmtConfig, host: Arc<Host>) -> anyhow::Result<Mgmt> {
191    Mgmt::start(cfg, host).await
192}
193
194impl Mgmt {
195    /// Open the local session, declare presence, and start publishing — for
196    /// every device the host serves (#118).
197    ///
198    /// One session, one presence token, one `introspect`: the origin is the
199    /// host and the producer is `modem`, so the bus sees one producer however
200    /// many devices stand behind it. Each device gets its own `lanes`, its own
201    /// telemetry, state and event loops, and its own `{device}` chunk.
202    /// Everything [`Mgmt::start`] can decide without I/O, so a daemon can
203    /// refuse a bad configuration before it says it is running, and then
204    /// bring the plane up behind it (#152).
205    ///
206    /// # Errors
207    ///
208    /// The first problem found.
209    pub fn check(cfg: &MgmtConfig, host: &Host) -> anyhow::Result<()> {
210        anyhow::ensure!(
211            !host.nodes().is_empty(),
212            "a management plane with no device to serve would declare itself alive for nothing"
213        );
214        V1Context::for_producer(&PROFILE, PRODUCER)
215            .context("the producer context is not a valid zenkey context")?;
216        // RFC 08 §6.1: an implementation must not report itself alive while the
217        // types it declares and the types it describes disagree. Checked here,
218        // on the way up, rather than by `build_verified` — that panics, and a
219        // panic inside a `LazyLock` inside a spawned queryable is the worst
220        // available place for this to go wrong.
221        modem_contract::schema::verify_total()
222            .context("the describe surface does not cover every declared type (RFC 08 §7)")?;
223        // Refreshing faster than the declared bound is fine and is what the
224        // tests do; advertising a *longer* freshness than the registry declares
225        // is a document a consumer cannot trust, and RFC 08 §6.1 is unambiguous
226        // that the registry must not lie.
227        anyhow::ensure!(
228            cfg.ttl_s <= state::declared_ttl_s(),
229            "[management] ttl_s = {} exceeds the {} s the registry declares for \
230             this producer's state subjects; lower it, or change the registry \
231             and re-run `just registry-lock`",
232            cfg.ttl_s,
233            state::declared_ttl_s(),
234        );
235        session_mode(cfg)?;
236        if let Some(id) = &cfg.usrpwd {
237            anyhow::ensure!(!id.user.is_empty(), "[management] usrpwd user is empty");
238            std::fs::metadata(&id.password_file).with_context(|| {
239                format!(
240                    "[management] usrpwd password_file {}",
241                    id.password_file.display()
242                )
243            })?;
244        }
245        Ok(())
246    }
247
248    pub async fn start(cfg: &MgmtConfig, host: Arc<Host>) -> anyhow::Result<Self> {
249        // Everything that can be decided without I/O is decided first, so a
250        // misconfigured or self-inconsistent driver refuses to start before it
251        // has opened a socket or bound a key.
252        Self::check(cfg, &host)?;
253        let ctx = V1Context::for_producer(&PROFILE, PRODUCER)
254            .context("the producer context is not a valid zenkey context")?;
255        // Every SDU device's state keys, resolved before anything is declared:
256        // a roster that calls this host alive is entitled to its documents.
257        let state_keys: Vec<(Arc<dyn SduPlane>, state::StateKeys)> = host
258            .sdu_planes()
259            .map(|p| {
260                (
261                    p.clone(),
262                    state::StateKeys::of(&PROFILE.local_origin(), p.as_ref()),
263                )
264            })
265            .collect();
266
267        let session = open_session(cfg).await?;
268
269        // The anti-twin probe (#118, zenkey RFC 03 §1.5): one daemon per host,
270        // and the roster is where a second one shows. Asked before anything is
271        // declared, so a twin refuses to start rather than answering beside
272        // the first — the lock files keep two processes off one *device*; this
273        // keeps two processes off one *producer*. Not an interlock: a bus
274        // partition could let two claimants coexist, which is why the device
275        // lock is taken outside the bus and this is only the early refusal.
276        if let Some(twin) = twin_alive(&session, &ctx).await {
277            let _ = session.close().await;
278            anyhow::bail!(
279                "another daemon already declares {twin} on this host: one daemon serves \
280                 every device on a host (#118) — stop it, or add this device to its config"
281            );
282        }
283
284        // The `@rpc` surface first, and every declaration awaited: the token
285        // below is what a roster reads, and it must not appear before the
286        // procedures it implies are answering (RFC 08 §6.1, #42). `rpc::serve`
287        // used to be synchronous and declared inside three spawned tasks, so
288        // this comment described an ordering the code did not have.
289        // The configuration plane's read side (#125), for every node that
290        // declares one: what it was at start is captured here, once.
291        let state_dir = cfg
292            .state_dir
293            .clone()
294            .or_else(|| std::env::var_os("STATE_DIRECTORY").map(std::path::PathBuf::from));
295        let configs: Vec<Arc<config::ConfigState>> = host
296            .nodes()
297            .iter()
298            .filter_map(|node| {
299                config::ConfigState::of(
300                    node.name(),
301                    oper::Source::of(node),
302                    node.file_keys().clone(),
303                    node.writable().clone(),
304                    state_dir
305                        .as_ref()
306                        .map(|d| d.join(format!("{}.overlay.toml", node.name()))),
307                )
308            })
309            .map(Arc::new)
310            .collect();
311        // Boot reconciles (#128): the overlay, checked and applied, before
312        // anything is served — and set aside if the device is not up by
313        // the operator's deadline.
314        let mut provisional = Vec::new();
315        for state in &configs {
316            if state.boot().await > 0
317                && let Some(s) = cfg.provisional_boot_s
318            {
319                provisional.push(state.provisional(std::time::Duration::from_secs(s)));
320            }
321        }
322
323        // Operator actions (#129), for every node whose device offers any.
324        let actions: Vec<Arc<action::ActionState>> = host
325            .nodes()
326            .iter()
327            .filter_map(|node| {
328                action::ActionState::of(
329                    node.name(),
330                    oper::Source::of(node),
331                    node.actions().clone(),
332                    node.action_intervals().clone(),
333                )
334            })
335            .map(Arc::new)
336            .collect();
337
338        let mut tasks = rpc::serve(session.clone(), host.clone(), &configs, &actions)
339            .await
340            .context("the @rpc surface could not be declared (RFC 08 §6.1)")?;
341
342        // Only now: present, and able to answer.
343        let alive = session
344            .liveliness()
345            .declare_token(ctx.alive_key().as_keyexpr())
346            .await
347            .map_err(|e| anyhow::anyhow!("declare liveliness token: {e}"))?;
348        // And one per device (RFC 04 §5, #120): `state/modem/device/<device>/
349        // alive`, the token that cycles when *that* device restarts — a modem
350        // re-enumerating under a driver that never did (RFC v1.39) — so a
351        // counter reset under its subject is excused for it and no other. The
352        // cycling itself arrives with the detection (#121, #130); the token
353        // is declared now, so the roster shows every device the host serves.
354        let mut device_alive = std::collections::BTreeMap::new();
355        for node in host.nodes() {
356            let key = ctx.device_alive_key(node.name());
357            let token = session
358                .liveliness()
359                .declare_token(key.as_keyexpr())
360                .await
361                .map_err(|e| anyhow::anyhow!("declare device liveliness token {key}: {e}"))?;
362            device_alive.insert(node.name().to_string(), token);
363        }
364        let device_alive = Arc::new(std::sync::Mutex::new(device_alive));
365
366        let devices: Vec<&str> = host.nodes().iter().map(|n| n.name()).collect();
367        tracing::info!(
368            origin = %PROFILE.host_id(),
369            producer = PRODUCER,
370            devices = ?devices,
371            "management plane up"
372        );
373
374        let interval = std::time::Duration::from_millis(cfg.telemetry_interval_ms);
375        for node in host.nodes() {
376            let name = node.name().to_string();
377            // Every device has an operational status, whatever moves its
378            // bytes (#121); polled at the telemetry cadence, refreshed at
379            // the state one.
380            tasks.push(tokio::spawn(oper::publish_loop(
381                session.clone(),
382                PROFILE.local_origin(),
383                host.clone(),
384                name.clone(),
385                oper::Source::of(node),
386                cfg.ttl_s,
387                interval,
388            )));
389            // And an identity (#122), polled at the state cadence: what it
390            // is changes when a terminal is swapped, not every tick.
391            tasks.push(tokio::spawn(identity::publish_loop(
392                session.clone(),
393                PROFILE.local_origin(),
394                name.clone(),
395                oper::Source::of(node),
396                cfg.ttl_s,
397            )));
398            // And what it guarantees about the bytes it carries (I6): for
399            // every device, because the subject is unconditional.
400            tasks.push(tokio::spawn(security::publish_loop(
401                session.clone(),
402                PROFILE.local_origin(),
403                name.clone(),
404                oper::Source::of(node),
405                cfg.ttl_s,
406            )));
407            // And, for a bearer that registers with a network, where it
408            // stands with it (#123); silent for one that does not.
409            tasks.push(tokio::spawn(radio::publish_loop(
410                session.clone(),
411                PROFILE.local_origin(),
412                name.clone(),
413                oper::Source::of(node),
414                cfg.ttl_s,
415            )));
416            match node.plane() {
417                Plane::Sdu(plane) => {
418                    tasks.push(tokio::spawn(telemetry::publish_loop(
419                        session.clone(),
420                        PROFILE.local_origin(),
421                        name,
422                        telemetry::Source::Sdu(plane.clone()),
423                        interval,
424                    )));
425                    // The events plane. Spawned like the other two and, unlike
426                    // them, silent unless something happens — which is what
427                    // `rate = "rare"` declares and what makes it affordable on
428                    // a metered link.
429                    tasks.push(tokio::spawn(events::publish_loop(
430                        session.clone(),
431                        PROFILE.local_origin(),
432                        plane.clone(),
433                    )));
434                }
435                Plane::Netdev(dev) => {
436                    // No lanes, no scheduler, no medium: what a netdev has to
437                    // say is its report, the kernel's counters (#130) and its
438                    // faults, and nothing else is published for it — absent,
439                    // never zero (#115). Its presence epoch cycles its token
440                    // when the interface is re-enumerated or a counter is
441                    // seen to go backwards (zenkey RFC 04 §5, v1.39).
442                    tasks.push(tokio::spawn(presence_loop(
443                        session.clone(),
444                        ctx.device_alive_key(&name),
445                        name.clone(),
446                        dev.clone(),
447                        device_alive.clone(),
448                        interval,
449                    )));
450                    tasks.push(tokio::spawn(telemetry::publish_loop(
451                        session.clone(),
452                        PROFILE.local_origin(),
453                        name.clone(),
454                        telemetry::Source::Netdev(dev.clone()),
455                        interval,
456                    )));
457                    // A radio with a neighbour table publishes it (#137);
458                    // a netdev with no such notion has no loop to run.
459                    if dev.destinations().is_some() {
460                        tasks.push(tokio::spawn(destination::publish_loop(
461                            session.clone(),
462                            PROFILE.local_origin(),
463                            name.clone(),
464                            dev.clone(),
465                            cfg.ttl_s,
466                        )));
467                    }
468                    let dev: Arc<dyn modem_device::Device> = dev.clone();
469                    tasks.push(tokio::spawn(events::publish_device_loop(
470                        session.clone(),
471                        PROFILE.local_origin(),
472                        name,
473                        dev,
474                    )));
475                }
476            }
477        }
478        // Every action invocation is an event (#129).
479        for state in &actions {
480            tasks.push(tokio::spawn(action::publish_loop(
481                session.clone(),
482                PROFILE.local_origin(),
483                state.clone(),
484            )));
485        }
486        // The configuration echo (#125): the read-back, on transition QoS.
487        for state in &configs {
488            tasks.push(tokio::spawn(config::publish_loop(
489                session.clone(),
490                PROFILE.local_origin(),
491                state.clone(),
492                cfg.ttl_s,
493            )));
494        }
495        // The registration document (zenkey RFC 04 §5): versions, and per
496        // device the capability predicates that hold here (#122).
497        tasks.push(tokio::spawn(sensor::publish_loop(
498            session.clone(),
499            PROFILE.local_origin(),
500            host.clone(),
501            cfg.ttl_s,
502        )));
503        for (plane, keys) in state_keys {
504            tasks.push(tokio::spawn(state::publish_loop(
505                session.clone(),
506                keys,
507                plane,
508                cfg.ttl_s,
509            )));
510        }
511
512        tasks.extend(provisional);
513
514        Ok(Self {
515            session,
516            ctx,
517            tasks,
518            _alive: alive,
519            _device_alive: device_alive,
520        })
521    }
522
523    /// The session this plane runs on, for tests and for the RPC surface.
524    pub fn session(&self) -> &Session {
525        &self.session
526    }
527
528    /// The key context, for tests that need to spell a key.
529    pub fn context(&self) -> &V1Context {
530        &self.ctx
531    }
532
533    /// Stop publishing and withdraw presence.
534    pub async fn shutdown(self) {
535        for t in &self.tasks {
536            t.abort();
537        }
538        // Dropping the token withdraws it; closing the session makes that
539        // visible to the network promptly rather than at lease expiry.
540        let _ = self.session.close().await;
541    }
542}
543
544/// The key of a twin's token, if any daemon on this host already holds one.
545///
546/// A liveliness query with a short wait: the token is either on the router
547/// now or it is not, and a daemon starting on a host with no router at all
548/// waits out the timeout and proceeds — the lock files are the interlock.
549async fn twin_alive(session: &Session, ctx: &V1Context) -> Option<String> {
550    let key = ctx.alive_key();
551    let replies = session
552        .liveliness()
553        .get(key.as_keyexpr())
554        .timeout(std::time::Duration::from_secs(2))
555        .await
556        .ok()?;
557    while let Ok(reply) = replies.recv_async().await {
558        if let Ok(sample) = reply.result() {
559            return Some(sample.key_expr().to_string());
560        }
561    }
562    None
563}
564
565/// The management session's mode: as configured, or `client` when it only
566/// connects and `peer` when it listens (#152).
567fn session_mode(cfg: &MgmtConfig) -> anyhow::Result<String> {
568    let mode = cfg.mode.clone().unwrap_or_else(|| {
569        if cfg.listen.is_empty() && !cfg.connect.is_empty() {
570            "client".to_string()
571        } else {
572            "peer".to_string()
573        }
574    });
575    anyhow::ensure!(
576        matches!(mode.as_str(), "client" | "peer" | "router"),
577        "[management] mode {mode:?}: one of client, peer, router"
578    );
579    Ok(mode)
580}
581
582async fn open_session(cfg: &MgmtConfig) -> anyhow::Result<Session> {
583    let mode = session_mode(cfg)?;
584    let mut config = zenoh::Config::default();
585    let list = |v: &[String]| {
586        let items: Vec<String> = v.iter().map(|e| format!("{e:?}")).collect();
587        format!("[{}]", items.join(","))
588    };
589    for (path, value) in [
590        ("mode", format!("{mode:?}")),
591        ("scouting/multicast/enabled", cfg.scouting.to_string()),
592        ("connect/endpoints", list(&cfg.connect)),
593        ("listen/endpoints", list(&cfg.listen)),
594    ] {
595        config
596            .insert_json5(path, &value)
597            .map_err(|e| anyhow::anyhow!("management session config {path}: {e}"))?;
598    }
599    if let Some(id) = &cfg.usrpwd {
600        let password = std::fs::read_to_string(&id.password_file).with_context(|| {
601            format!(
602                "[management] usrpwd password_file {}",
603                id.password_file.display()
604            )
605        })?;
606        for (path, value) in [
607            ("transport/auth/usrpwd/user", id.user.as_str()),
608            (
609                "transport/auth/usrpwd/password",
610                password.trim_end_matches(['\n', '\r']),
611            ),
612        ] {
613            config
614                .insert_json5(path, &serde_json::to_string(value)?)
615                .map_err(|e| anyhow::anyhow!("management session config {path}: {e}"))?;
616        }
617    }
618    if mode != "client" {
619        return zenoh::open(config)
620            .await
621            .map_err(|e| anyhow::anyhow!("{e}"));
622    }
623    // A Zenoh client cannot open without its router, and has no background
624    // redial of its own. This loop is that redial: the supervisor's contract
625    // is that start order does not matter (#96), and the daemon brings this
626    // plane up behind its data path rather than waiting on it (#152).
627    let mut backoff = std::time::Duration::from_secs(1);
628    let mut said = false;
629    loop {
630        match zenoh::open(config.clone()).await {
631            Ok(session) => return Ok(session),
632            Err(e) => {
633                if !said {
634                    tracing::warn!(error = %e, "the management router is not reachable yet; retrying");
635                    said = true;
636                }
637                tokio::time::sleep(backoff).await;
638                backoff = (backoff * 2).min(std::time::Duration::from_secs(10));
639            }
640        }
641    }
642}
643
644/// Cycle a netdev's presence token when its epoch moves (#130): drop the
645/// token, which withdraws it, and declare it again. A reader that saw the
646/// token go and come reads the counters under it as restarted, which the
647/// registry sanctions and a counter that went backwards would otherwise
648/// contradict.
649async fn presence_loop(
650    session: Session,
651    key: zenkey::Key,
652    device: String,
653    dev: Arc<dyn modem_device::Netdev>,
654    tokens: Arc<
655        std::sync::Mutex<std::collections::BTreeMap<String, zenoh::liveliness::LivelinessToken>>,
656    >,
657    interval: std::time::Duration,
658) {
659    let mut seen = dev.epoch();
660    loop {
661        tokio::time::sleep(interval).await;
662        let now = dev.epoch();
663        if now == seen {
664            continue;
665        }
666        seen = now;
667        // Withdraw first, then re-declare: two declarations of one key would
668        // leave the roster showing the device present throughout.
669        drop(tokens.lock().expect("not poisoned").remove(&device));
670        match session.liveliness().declare_token(key.as_keyexpr()).await {
671            Ok(token) => {
672                tokens
673                    .lock()
674                    .expect("not poisoned")
675                    .insert(device.clone(), token);
676                tracing::info!(device = %device, epoch = now, "the device's presence token cycled");
677            }
678            Err(e) => {
679                tracing::warn!(device = %device, error = %e, "the device's presence token could not be re-declared");
680            }
681        }
682    }
683}
684
685#[cfg(test)]
686mod tests {
687    use super::*;
688
689    fn cfg(connect: &[&str], listen: &[&str], mode: Option<&str>) -> MgmtConfig {
690        MgmtConfig {
691            connect: connect.iter().map(|s| (*s).to_string()).collect(),
692            listen: listen.iter().map(|s| (*s).to_string()).collect(),
693            mode: mode.map(str::to_string),
694            ..MgmtConfig::default()
695        }
696    }
697
698    #[test]
699    fn a_session_that_only_connects_is_a_client_of_its_router() {
700        // #152: a peer behind a gossip-less router is seen by nothing.
701        let mode = session_mode(&cfg(&["tcp/127.0.0.1:7447"], &[], None)).unwrap();
702        assert_eq!(mode, "client");
703    }
704
705    #[test]
706    fn a_session_that_listens_is_a_peer_unless_told() {
707        assert_eq!(
708            session_mode(&cfg(&[], &["tcp/127.0.0.1:7447"], None)).unwrap(),
709            "peer"
710        );
711        assert_eq!(
712            session_mode(&cfg(&["tcp/a:1"], &["tcp/b:2"], None)).unwrap(),
713            "peer",
714            "a session that both connects and listens is not anybody's client"
715        );
716        assert_eq!(
717            session_mode(&cfg(&["tcp/a:1"], &[], Some("peer"))).unwrap(),
718            "peer",
719            "an explicit mode wins"
720        );
721    }
722
723    #[test]
724    fn an_unknown_mode_is_refused() {
725        let err = session_mode(&cfg(&["tcp/a:1"], &[], Some("hub"))).unwrap_err();
726        assert!(err.to_string().contains("client, peer, router"), "{err}");
727    }
728}