Skip to main content

vector_core/xdc/
mesh.rs

1//! The Iroh gossip mesh realtime sessions ride: one relay-only endpoint for the
2//! account using it (a fresh node key per account), one gossip subscription per
3//! topic, events out through a channel.
4//!
5//! Wire-compatible with the app's own realtime layer: the same ALPN, transport
6//! tuning, address form and frame trailer, so a headless peer and a player in
7//! the app share one channel.
8
9use std::collections::HashMap;
10use std::sync::atomic::{AtomicBool, AtomicI32, AtomicUsize, Ordering};
11use std::sync::Arc;
12
13use futures_util::StreamExt;
14use iroh::endpoint::VarInt;
15use iroh::{Endpoint, EndpointAddr, EndpointId, RelayMode, SecretKey, TransportAddr};
16use iroh_gossip::api::{Event, GossipReceiver, GossipSender, JoinOptions};
17use iroh_gossip::net::{Gossip, GOSSIP_ALPN};
18use iroh_gossip::proto::TopicId;
19use tokio::sync::{mpsc, watch};
20
21use super::wire::{self, NODE_KEY_LEN};
22
23/// What a subscription reports.
24#[derive(Debug, Clone)]
25pub enum MeshEvent {
26    /// A frame from a peer. `sender` is the node key its trailer names; `direct`
27    /// is true when that same node handed it to us over its own authenticated
28    /// connection, so the trailer could not have been forged in transit.
29    Data { payload: Vec<u8>, sender: [u8; NODE_KEY_LEN], direct: bool },
30    NeighborUp([u8; NODE_KEY_LEN]),
31    NeighborDown([u8; NODE_KEY_LEN]),
32    /// Frames were dropped: the reader fell behind, or gossip did.
33    Lagged,
34}
35
36pub struct Mesh {
37    endpoint: Endpoint,
38    gossip: Gossip,
39    key: [u8; NODE_KEY_LEN],
40    topics: tokio::sync::RwLock<HashMap<TopicId, Topic>>,
41    /// Topics whose handles are still being dropped; each turns true once gone.
42    closing: Arc<std::sync::Mutex<HashMap<TopicId, watch::Receiver<bool>>>>,
43    /// Joins holding the mesh before they have subscribed (see [`lease`]).
44    leases: AtomicUsize,
45    /// Bound with IP transports, so peers may reach it, and learn its address, directly.
46    direct: bool,
47}
48
49/// The mesh, held by a join from the moment it is handed out until its topic is
50/// subscribed: [`retire_if_idle`] sees no topic in that gap, and must not close it.
51pub struct MeshLease(Arc<Mesh>);
52
53impl MeshLease {
54    pub fn mesh(&self) -> &Arc<Mesh> {
55        &self.0
56    }
57}
58
59impl Drop for MeshLease {
60    fn drop(&mut self) {
61        self.0.leases.fetch_sub(1, Ordering::SeqCst);
62    }
63}
64
65struct Topic {
66    sender: GossipSender,
67    pump: crate::rt::JoinHandle<()>,
68    seq: AtomicI32,
69    neighbors: Arc<AtomicUsize>,
70}
71
72/// One dial attempt. A fresh node can spend a few seconds on its relay handshake
73/// before the dial even starts.
74const ADD_PEER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
75
76/// The ALPNs the node accepts: gossip, and calls where this build has them.
77fn alpns() -> Vec<Vec<u8>> {
78    #[allow(unused_mut)]
79    let mut alpns = vec![GOSSIP_ALPN.to_vec()];
80    #[cfg(feature = "calls")]
81    alpns.push(crate::calls::wire::CALL_ALPN.to_vec());
82    alpns
83}
84
85/// The live mesh and the account (session id) it was bound for. One account's
86/// node is never another's: two accounts advertising one node key are linkable.
87static MESH: tokio::sync::Mutex<Option<(u64, Arc<Mesh>)>> = tokio::sync::Mutex::const_new(None);
88
89/// The calling account's mesh, bound on first use with a fresh node key. A mesh
90/// bound for any other account is closed and replaced, never shared.
91pub async fn mesh() -> Result<Arc<Mesh>, String> {
92    crate::transport::realtime::check()?;
93    acquire(false).await
94}
95
96/// [`mesh`], leased until dropped (see [`MeshLease`]).
97pub async fn lease() -> Result<MeshLease, String> {
98    crate::transport::realtime::check()?;
99    acquire(true).await.map(MeshLease)
100}
101
102/// [`lease`] for a caller that already holds the user's consent for this network.
103pub(crate) async fn lease_vouched() -> Result<MeshLease, String> {
104    acquire(true).await.map(MeshLease)
105}
106
107async fn acquire(lease: bool) -> Result<Arc<Mesh>, String> {
108    let session = crate::db::current_session();
109    let mut slot = MESH.lock().await;
110    match claim(&mut slot, session.id(), session.is_live()) {
111        // A node bound under the other privacy choice is replaced once nothing uses it.
112        Claim::Reuse(m) if m.direct != crate::transport::realtime::direct() && m.idle().await => {
113            if let Some((_, old)) = slot.take() {
114                old.close_detached();
115            }
116        }
117        Claim::Reuse(m) => {
118            if lease {
119                m.leases.fetch_add(1, Ordering::SeqCst);
120            }
121            return Ok(m);
122        }
123        Claim::Refuse => return Err("the account is switching".into()),
124        Claim::Bind(previous) => {
125            if let Some(old) = previous {
126                old.close_detached();
127            }
128        }
129    }
130    let m = Arc::new(Mesh::bind().await.map_err(|e| format!("Realtime unavailable: {e}"))?);
131    if lease {
132        m.leases.fetch_add(1, Ordering::SeqCst);
133    }
134    *slot = Some((session.id(), m.clone()));
135    Ok(m)
136}
137
138/// Close `expected` if it is still the live mesh and nothing uses it: no topic,
139/// no join on its way to one, no call. For a client that wants a fresh node
140/// for each app session. Returns whether it closed.
141pub async fn retire_if_idle(expected: &Arc<Mesh>) -> bool {
142    let mut slot = MESH.lock().await;
143    let idle = match slot.as_ref() {
144        Some((_, m)) if Arc::ptr_eq(m, expected) => m.idle().await,
145        _ => false,
146    };
147    if !idle {
148        return false;
149    }
150    if let Some((_, m)) = slot.take() {
151        m.close_detached();
152    }
153    true
154}
155
156/// Close the live mesh if nothing uses it: a node left idle keeps its relay link, address
157/// probes and DNS going outside the chosen network.
158pub async fn retire_live_if_idle() -> bool {
159    let live = MESH.lock().await.as_ref().map(|(_, m)| m.clone());
160    match live {
161        Some(m) => retire_if_idle(&m).await,
162        None => false,
163    }
164}
165
166/// [`retire_live_if_idle`] unless the account is on Clearnet, where one node per account stays:
167/// for a call that just ended, whose node nothing else may be using.
168pub async fn retire_live_off_clearnet() -> bool {
169    if crate::transport::preference() == Some(crate::transport::Kind::Clearnet) {
170        return false;
171    }
172    retire_live_if_idle().await
173}
174
175#[cfg(feature = "calls")]
176fn call_active() -> bool {
177    crate::calls::session::snapshot().is_some()
178}
179
180#[cfg(not(feature = "calls"))]
181fn call_active() -> bool {
182    false
183}
184
185/// Close the mesh bound for account `owner`, if it still holds the slot, so the
186/// next account binds a fresh node key. Returns at once: the slot may be busy
187/// binding, and another account's bind replaces (and closes) it anyway.
188pub fn retire(owner: u64) {
189    if !crate::rt::can_spawn() {
190        return;
191    }
192    // spawn-detached: closes a node by owner id; reads no account state.
193    crate::rt::spawn(async move {
194        if let Some(m) = take_owned(&mut *MESH.lock().await, owner) {
195            m.close_detached();
196        }
197    });
198}
199
200#[cfg(test)]
201pub(crate) async fn install_for_test(owner: u64, mesh: Mesh) -> Arc<Mesh> {
202    install_bound_as(owner, mesh, crate::transport::realtime::direct()).await
203}
204
205/// [`install_for_test`] as though bound under the given privacy choice.
206#[cfg(test)]
207pub(crate) async fn install_bound_as(owner: u64, mut mesh: Mesh, direct: bool) -> Arc<Mesh> {
208    mesh.direct = direct;
209    let mesh = Arc::new(mesh);
210    *MESH.lock().await = Some((owner, mesh.clone()));
211    mesh
212}
213
214/// Serializes the tests that put a mesh in the process-wide slot.
215#[cfg(test)]
216pub(crate) static SLOT_TESTS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
217
218#[cfg(test)]
219pub(crate) async fn slot_owner() -> Option<u64> {
220    MESH.lock().await.as_ref().map(|(owner, _)| *owner)
221}
222
223enum Claim<T> {
224    Reuse(T),
225    /// Bind a fresh one; close the other account's, if any.
226    Bind(Option<T>),
227    Refuse,
228}
229
230/// The slot's rule: an account reuses only its own mesh, and only the live
231/// account may bind one.
232fn claim<T: Clone>(slot: &mut Option<(u64, T)>, owner: u64, live: bool) -> Claim<T> {
233    match slot.as_ref() {
234        Some((o, m)) if *o == owner => Claim::Reuse(m.clone()),
235        _ if !live => Claim::Refuse,
236        _ => Claim::Bind(slot.take().map(|(_, m)| m)),
237    }
238}
239
240fn take_owned<T>(slot: &mut Option<(u64, T)>, owner: u64) -> Option<T> {
241    if slot.as_ref().is_some_and(|(o, _)| *o == owner) {
242        slot.take().map(|(_, m)| m)
243    } else {
244        None
245    }
246}
247
248impl Mesh {
249    async fn bind() -> anyhow_lite::Result<Self> {
250        let mesh = Self::build(wire::relay_mode(), crate::transport::realtime::direct()).await?;
251        // An advertisement without our relay is undiallable.
252        let _ = crate::rt::time::timeout(std::time::Duration::from_secs(8), mesh.endpoint.online()).await;
253        for _ in 0..20 {
254            if mesh.endpoint.addr().addrs.iter().any(|a| matches!(a, TransportAddr::Relay(_))) {
255                break;
256            }
257            crate::rt::time::sleep(std::time::Duration::from_millis(100)).await;
258        }
259        crate::log_info!("[xdc] node {} via {}", short(&mesh.key), wire::relay_urls(&mesh.endpoint.addr()));
260        Ok(mesh)
261    }
262
263    /// A mesh with no relay, for tests: binds offline and at once.
264    #[cfg(test)]
265    pub(crate) async fn offline() -> Self {
266        Self::build(RelayMode::Disabled, true).await.expect("bind")
267    }
268
269    /// Not `direct`: no IP transport, so no UDP socket, no address to hand a peer and nothing to
270    /// holepunch from. Every path then runs through the relay.
271    async fn build(relay_mode: RelayMode, direct: bool) -> anyhow_lite::Result<Self> {
272        let mut seed = [0u8; 32];
273        rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut seed);
274        let secret_key = SecretKey::from(seed);
275        let key = *secret_key.public().as_bytes();
276
277        // The app's tuning, so both ends of a channel behave alike.
278        let transport = iroh::endpoint::QuicTransportConfig::builder()
279            .keep_alive_interval(std::time::Duration::from_secs(15))
280            .max_idle_timeout(Some(std::time::Duration::from_secs(120).try_into()?))
281            .stream_receive_window(VarInt::from_u32(512 * 1024))
282            .receive_window(VarInt::from_u32(2 * 1024 * 1024))
283            .send_window(1_572_864)
284            .max_concurrent_bidi_streams(VarInt::from_u32(256))
285            .max_concurrent_uni_streams(VarInt::from_u32(256))
286            .initial_rtt(std::time::Duration::from_millis(100))
287            .congestion_controller_factory(Arc::new(noq_proto::congestion::CubicConfig::default()))
288            // Observed-address reports route data onto a path the peer can't reach.
289            .send_observed_address_reports(false)
290            .receive_observed_address_reports(false)
291            .build();
292
293        // No address discovery service: nothing announces this node but its own
294        // advertisements, which carry its relay alone. (Iroh itself still trades
295        // direct addresses with connected peers.)
296        struct RelayOnly(RelayMode);
297        impl iroh::endpoint::presets::Preset for RelayOnly {
298            fn apply(self, builder: iroh::endpoint::Builder) -> iroh::endpoint::Builder {
299                builder.relay_mode(self.0).crypto_provider(Arc::new(rustls::crypto::ring::default_provider()))
300            }
301        }
302
303        let builder = Endpoint::builder(RelayOnly(relay_mode)).secret_key(secret_key).alpns(alpns()).transport_config(transport);
304        #[cfg(not(target_arch = "wasm32"))]
305        let builder = if direct { builder } else { builder.clear_ip_transports() };
306        let endpoint = builder.bind().await?;
307
308        let gossip = Gossip::builder().max_message_size(wire::MAX_GOSSIP_MESSAGE).spawn(endpoint.clone());
309
310        let (ep, g) = (endpoint.clone(), gossip.clone());
311        // spawn-detached: the endpoint's accept loop; it lives as long as the endpoint and holds no account state.
312        crate::rt::spawn(async move {
313            while let Some(incoming) = ep.accept().await {
314                let g = g.clone();
315                // spawn-detached: one inbound handshake, handed to gossip.
316                crate::rt::spawn(async move {
317                    match incoming.await {
318                        Ok(conn) if conn.alpn() == GOSSIP_ALPN => {
319                            if let Err(e) = g.handle_connection(conn).await {
320                                crate::log_debug!("[xdc] inbound gossip connection ended: {e}");
321                            }
322                        }
323                        #[cfg(feature = "calls")]
324                        Ok(conn) if conn.alpn() == crate::calls::wire::CALL_ALPN => {
325                            crate::calls::session::on_incoming(conn).await;
326                        }
327                        Ok(_) => {}
328                        Err(e) => crate::log_debug!("[xdc] accept failed: {e}"),
329                    }
330                });
331            }
332        });
333
334        Ok(Self {
335            endpoint,
336            gossip,
337            key,
338            topics: tokio::sync::RwLock::new(HashMap::new()),
339            closing: Arc::new(std::sync::Mutex::new(HashMap::new())),
340            leases: AtomicUsize::new(0),
341            direct,
342        })
343    }
344
345    /// Stop gossip, then close the endpoint, each on its own budget so a peer
346    /// that stops reading can't keep the node online. Detached, so neither a
347    /// cancelled caller nor a slow peer leaves it half-closed.
348    fn close_detached(&self) {
349        if !crate::rt::can_spawn() {
350            return;
351        }
352        let (endpoint, gossip) = (self.endpoint.clone(), self.gossip.clone());
353        // spawn-detached: closes a node no account uses any more; holds no account state.
354        crate::rt::spawn(async move {
355            let _ = crate::rt::time::timeout(std::time::Duration::from_secs(2), gossip.shutdown()).await;
356            let _ = crate::rt::time::timeout(std::time::Duration::from_secs(4), endpoint.close()).await;
357        });
358    }
359
360    /// The endpoint itself, for protocols that share the node (calls dial on it).
361    /// No topic, no join on its way to one, no call.
362    async fn idle(&self) -> bool {
363        self.leases.load(Ordering::SeqCst) == 0 && self.topics.read().await.is_empty() && !call_active()
364    }
365
366    pub fn endpoint(&self) -> &Endpoint {
367        &self.endpoint
368    }
369
370    pub fn node_key(&self) -> [u8; NODE_KEY_LEN] {
371        self.key
372    }
373
374    /// Our address as an advertisement carries it: relay only.
375    pub fn node_addr(&self) -> EndpointAddr {
376        wire::relay_only(self.endpoint.addr())
377    }
378
379    pub async fn neighbor_count(&self, topic: &[u8; 32]) -> usize {
380        self.topics
381            .read()
382            .await
383            .get(&TopicId::from_bytes(*topic))
384            .map(|t| t.neighbors.load(Ordering::Relaxed))
385            .unwrap_or(0)
386    }
387
388    /// Subscribe to a topic and dial `peers`. Events go to `sink` until
389    /// [`unsubscribe`](Self::unsubscribe). One subscription per topic per process.
390    pub async fn subscribe(&self, topic: [u8; 32], peers: Vec<EndpointAddr>, sink: mpsc::Sender<MeshEvent>) -> Result<(), String> {
391        let id = TopicId::from_bytes(topic);
392        // A topic still dropping its last handles would share gossip's state with
393        // the new one: wait it out.
394        let mut topics = loop {
395            let topics = self.topics.write().await;
396            if topics.contains_key(&id) {
397                return Err("already subscribed to this topic".into());
398            }
399            let pending = self.closing.lock().unwrap_or_else(|e| e.into_inner()).get(&id).cloned();
400            match pending {
401                None => break topics,
402                Some(gone) => {
403                    drop(topics);
404                    self.await_teardown(id, gone).await;
405                }
406            }
407        };
408        // Subscribe before dialling, so the topic exists when their frames land.
409        let peers: Vec<EndpointAddr> = peers.into_iter().map(|p| self.reachable(p)).collect();
410        let bootstrap: Vec<EndpointId> = peers.iter().map(|p| p.id).collect();
411        let sub = self
412            .gossip
413            .subscribe_with_opts(id, JoinOptions::with_bootstrap(bootstrap))
414            .await
415            .map_err(|e| e.to_string())?;
416        for peer in peers {
417            self.dial(peer);
418        }
419        let (sender, receiver) = sub.split();
420        let neighbors = Arc::new(AtomicUsize::new(0));
421        // spawn-detached: carries one topic's gossip frames into a channel; no account state.
422        let pump = crate::rt::spawn(pump(receiver, sender.clone(), sink, self.key, neighbors.clone()));
423        // A random start: gossip dedups by content, and this node outlives a
424        // session, so a rejoin counting from zero would repeat old frames byte for byte.
425        let seq = AtomicI32::new(rand::random::<i32>());
426        topics.insert(id, Topic { sender, pump, seq, neighbors });
427        Ok(())
428    }
429
430    /// A peer's address as we will dial it ([`wire::dialable`]), through our
431    /// relay when none of theirs is left.
432    fn reachable(&self, peer: EndpointAddr) -> EndpointAddr {
433        let mut addr = wire::dialable(peer);
434        if addr.addrs.is_empty() {
435            if let Some(relay) = self.endpoint.addr().addrs.into_iter().find(|a| matches!(a, TransportAddr::Relay(_))) {
436                addr.addrs.insert(relay);
437            }
438        }
439        addr
440    }
441
442    fn dial(&self, peer: EndpointAddr) {
443        let peer = self.reachable(peer);
444        if peer.addrs.is_empty() {
445            return;
446        }
447        let (ep, g) = (self.endpoint.clone(), self.gossip.clone());
448        // spawn-detached: one outbound dial; gossip owns the connection after.
449        crate::rt::spawn(async move {
450            match ep.connect(peer, GOSSIP_ALPN).await {
451                Ok(conn) => {
452                    if let Err(e) = g.handle_connection(conn).await {
453                        crate::log_debug!("[xdc] peer connection ended: {e}");
454                    }
455                }
456                Err(e) => crate::log_debug!("[xdc] dial failed: {e}"),
457            }
458        });
459    }
460
461    /// Bring a newly advertised peer into a live topic, retrying 1 s, then 2 s apart.
462    pub async fn add_peer(&self, topic: &[u8; 32], peer: EndpointAddr) -> Result<(), String> {
463        let mut last = String::new();
464        for attempt in 0..3u32 {
465            if attempt > 0 {
466                crate::rt::time::sleep(std::time::Duration::from_secs(1 << (attempt - 1))).await;
467            }
468            // A dead peer must not hold the caller until QUIC's idle timeout.
469            match crate::rt::time::timeout(ADD_PEER_TIMEOUT, self.try_add_peer(topic, &peer)).await {
470                Ok(Ok(())) => return Ok(()),
471                Ok(Err(e)) => last = e,
472                Err(_) => last = "timed out".into(),
473            }
474        }
475        Err(last)
476    }
477
478    async fn try_add_peer(&self, topic: &[u8; 32], peer: &EndpointAddr) -> Result<(), String> {
479        let addr = self.reachable(peer.clone());
480        let conn = self.endpoint.connect(addr, GOSSIP_ALPN).await.map_err(|e| e.to_string())?;
481        self.gossip.handle_connection(conn).await.map_err(|e| e.to_string())?;
482        let sender = {
483            let topics = self.topics.read().await;
484            topics.get(&TopicId::from_bytes(*topic)).ok_or("not subscribed")?.sender.clone()
485        };
486        sender.join_peers(vec![peer.id]).await.map_err(|e| e.to_string())
487    }
488
489    pub async fn broadcast(&self, topic: &[u8; 32], payload: Vec<u8>) -> Result<(), String> {
490        if payload.len() > wire::MAX_PAYLOAD {
491            return Err(format!("frame of {} bytes exceeds the {} byte limit", payload.len(), wire::MAX_PAYLOAD));
492        }
493        let (sender, frame) = {
494            let topics = self.topics.read().await;
495            let t = topics.get(&TopicId::from_bytes(*topic)).ok_or("not subscribed")?;
496            let seq = t.seq.fetch_add(1, Ordering::Relaxed).wrapping_add(1);
497            (t.sender.clone(), wire::seal_frame(payload, seq, &self.key))
498        };
499        sender.broadcast(frame.into()).await.map_err(|e| e.to_string())
500    }
501
502    /// Drop every handle on the topic: gossip only forgets a topic once all are gone,
503    /// and a surviving clone would break the next subscription to it. Returns once
504    /// they are gone, including those of an unsubscribe already under way; the
505    /// teardown finishes even if this call is cancelled.
506    pub async fn unsubscribe(&self, topic: &[u8; 32]) {
507        let id = TopicId::from_bytes(*topic);
508        let gone = {
509            let mut topics = self.topics.write().await;
510            match topics.remove(&id) {
511                Some(t) => {
512                    let (done, gone) = watch::channel(false);
513                    self.closing.lock().unwrap_or_else(|e| e.into_inner()).insert(id, gone.clone());
514                    let closing = self.closing.clone();
515                    // spawn-detached: drops one topic's gossip handles; holds no account state.
516                    crate::rt::spawn(async move {
517                        drop(t.sender);
518                        t.pump.abort();
519                        let _ = t.pump.await;
520                        crate::rt::yield_now().await;
521                        // Deregister before signalling: a resubscribe waits on this
522                        // signal, so the entry removed is always this teardown's own.
523                        closing.lock().unwrap_or_else(|e| e.into_inner()).remove(&id);
524                        done.send_replace(true);
525                    });
526                    Some(gone)
527                }
528                None => self.closing.lock().unwrap_or_else(|e| e.into_inner()).get(&id).cloned(),
529            }
530        };
531        if let Some(gone) = gone {
532            self.await_teardown(id, gone).await;
533        }
534    }
535
536    /// Wait for a topic's teardown. One whose task died unsignalled (its runtime
537    /// shut down) is forgotten rather than waited on forever.
538    async fn await_teardown(&self, id: TopicId, mut gone: watch::Receiver<bool>) {
539        if gone.wait_for(|g| *g).await.is_err() {
540            let mut closing = self.closing.lock().unwrap_or_else(|e| e.into_inner());
541            if closing.get(&id).is_some_and(|rx| rx.same_channel(&gone)) {
542                closing.remove(&id);
543            }
544        }
545    }
546}
547
548/// The accept loop holds the endpoint open, so releasing the last handle must close it.
549impl Drop for Mesh {
550    fn drop(&mut self) {
551        self.close_detached();
552    }
553}
554
555async fn pump(
556    mut receiver: GossipReceiver,
557    sender: GossipSender,
558    sink: mpsc::Sender<MeshEvent>,
559    our_key: [u8; NODE_KEY_LEN],
560    neighbors: Arc<AtomicUsize>,
561) {
562    let lagged = AtomicBool::new(false);
563    let deliver = |ev: MeshEvent| {
564        if lagged.swap(false, Ordering::Relaxed) && sink.try_send(MeshEvent::Lagged).is_err() {
565            lagged.store(true, Ordering::Relaxed);
566        }
567        if sink.try_send(ev).is_err() {
568            lagged.store(true, Ordering::Relaxed);
569        }
570    };
571    while let Some(event) = receiver.next().await {
572        if sink.is_closed() {
573            break;
574        }
575        match event {
576            Ok(Event::Received(msg)) => {
577                let Some((payload, sender_key)) = wire::open_frame(&msg.content) else { continue };
578                if sender_key == our_key {
579                    continue;
580                }
581                let direct = msg.scope.is_direct() && *msg.delivered_from.as_bytes() == sender_key;
582                deliver(MeshEvent::Data { payload: payload.to_vec(), sender: sender_key, direct });
583            }
584            Ok(Event::NeighborUp(peer)) => {
585                // A peer that reached us through the accept loop still needs joining to the topic.
586                let _ = sender.join_peers(vec![peer]).await;
587                neighbors.fetch_add(1, Ordering::Relaxed);
588                deliver(MeshEvent::NeighborUp(*peer.as_bytes()));
589            }
590            Ok(Event::NeighborDown(peer)) => {
591                // fetch_update: its rename, try_update, is newer than the toolchains Vector builds with.
592                #[allow(deprecated)]
593                let _ = neighbors.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |c| c.checked_sub(1));
594                deliver(MeshEvent::NeighborDown(*peer.as_bytes()));
595            }
596            Ok(Event::Lagged) => deliver(MeshEvent::Lagged),
597            Err(e) => crate::log_debug!("[xdc] gossip error: {e}"),
598        }
599    }
600}
601
602pub(crate) fn short(key: &[u8; NODE_KEY_LEN]) -> String {
603    crate::simd::hex::bytes_to_hex_string(&key[..6])
604}
605
606/// `?` over iroh's and noq's error types without pulling in anyhow.
607mod anyhow_lite {
608    pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
609}
610
611#[cfg(test)]
612mod tests {
613    use super::*;
614
615    #[tokio::test]
616    async fn a_private_node_has_no_socket_and_so_no_address_to_give_away() {
617        let unreachable: iroh::RelayUrl = "https://127.0.0.1:1".parse().unwrap();
618        let private = Mesh::build(RelayMode::Custom(iroh::RelayMap::from(unreachable)), false).await.unwrap();
619        assert!(private.endpoint.bound_sockets().is_empty(), "no IP transport bound");
620        assert!(!private.endpoint.addr().addrs.iter().any(|a| matches!(a, TransportAddr::Ip(_))), "nothing direct to advertise or trade");
621        let direct = Mesh::build(RelayMode::Disabled, true).await.unwrap();
622        assert!(!direct.endpoint.bound_sockets().is_empty(), "a direct node binds its sockets");
623    }
624
625    #[test]
626    fn an_account_never_gets_another_accounts_mesh() {
627        let mut slot = Some((1u64, "a"));
628        assert!(matches!(claim(&mut slot, 1, true), Claim::Reuse("a")));
629        assert!(matches!(claim(&mut slot, 1, false), Claim::Reuse("a")), "its own, even mid-swap");
630        assert!(matches!(claim(&mut slot, 2, false), Claim::Refuse), "a swapped-out account binds nothing");
631        assert_eq!(slot, Some((1, "a")));
632        assert!(matches!(claim(&mut slot, 2, true), Claim::Bind(Some("a"))), "the next account replaces it");
633        assert_eq!(slot, None);
634        assert!(matches!(claim(&mut slot, 2, true), Claim::Bind(None)));
635    }
636
637    #[test]
638    fn retiring_closes_only_the_named_accounts_mesh() {
639        let mut slot = Some((2u64, "b"));
640        assert_eq!(take_owned(&mut slot, 1), None);
641        assert_eq!(slot, Some((2, "b")));
642        assert_eq!(take_owned(&mut slot, 2), Some("b"));
643        assert_eq!(slot, None);
644    }
645
646    #[tokio::test]
647    async fn an_unsubscribe_cut_off_half_way_still_drops_the_topic_before_a_retry_returns() {
648        let mesh = Mesh::offline().await;
649        let topic = [7u8; 32];
650        let (tx, mut rx) = mpsc::channel(4);
651        mesh.subscribe(topic, Vec::new(), tx).await.unwrap();
652        // One poll: the entry is removed, then the call is dropped mid-teardown.
653        assert!(futures_util::FutureExt::now_or_never(mesh.unsubscribe(&topic)).is_none());
654        mesh.unsubscribe(&topic).await;
655        assert!(
656            matches!(rx.try_recv(), Err(mpsc::error::TryRecvError::Disconnected)),
657            "the pump's handles are gone once the retry returns"
658        );
659        let (tx, _rx) = mpsc::channel(4);
660        mesh.subscribe(topic, Vec::new(), tx).await.expect("the topic can be joined again");
661        mesh.unsubscribe(&topic).await;
662    }
663
664    #[tokio::test]
665    async fn releasing_a_mesh_closes_its_node() {
666        let mesh = Mesh::offline().await;
667        let endpoint = mesh.endpoint.clone();
668        drop(mesh);
669        for _ in 0..100 {
670            if endpoint.is_closed() {
671                return;
672            }
673            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
674        }
675        panic!("the endpoint outlived its mesh");
676    }
677
678    #[tokio::test]
679    #[allow(clippy::await_holding_lock)]
680    async fn a_call_off_clearnet_takes_its_idle_node_with_it() {
681        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
682        let _serial = SLOT_TESTS.lock().await;
683        let before = crate::transport::preference();
684        let owner = crate::db::live_session_id();
685        let mesh = install_for_test(owner, Mesh::offline().await).await;
686        crate::transport::set_preference(Some(crate::transport::Kind::Clearnet));
687        assert!(!retire_live_off_clearnet().await, "Clearnet keeps the account's node");
688        assert_eq!(slot_owner().await, Some(owner));
689        crate::transport::set_preference(Some(crate::transport::Kind::Tor));
690        let (tx, _rx) = mpsc::channel(4);
691        mesh.subscribe([8u8; 32], Vec::new(), tx).await.unwrap();
692        assert!(!retire_live_off_clearnet().await, "a Mini App session still on it keeps it");
693        mesh.unsubscribe(&[8u8; 32]).await;
694        assert!(retire_live_off_clearnet().await, "off Clearnet the idle node goes");
695        assert_eq!(slot_owner().await, None);
696        crate::transport::set_preference(before);
697    }
698
699    #[tokio::test]
700    #[allow(clippy::await_holding_lock)]
701    async fn a_mesh_is_retired_only_once_nothing_uses_it() {
702        // The live session's network decides whether a lease may open a node at all.
703        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
704        let _serial = SLOT_TESTS.lock().await;
705        crate::db::with_session(crate::db::current_session(), async {
706            let owner = crate::db::current_session().id();
707            let mesh = install_for_test(owner, Mesh::offline().await).await;
708            let lease = lease().await.expect("the caller's own mesh");
709            assert!(Arc::ptr_eq(lease.mesh(), &mesh));
710            assert!(!retire_if_idle(&mesh).await, "a join between handing out the mesh and subscribing holds it");
711            drop(lease);
712            let (tx, _rx) = mpsc::channel(4);
713            mesh.subscribe([9u8; 32], Vec::new(), tx).await.unwrap();
714            assert!(!retire_if_idle(&mesh).await, "a subscribed topic holds it");
715            mesh.unsubscribe(&[9u8; 32]).await;
716            assert!(retire_if_idle(&mesh).await, "idle, it closes");
717            assert_eq!(slot_owner().await, None);
718            let successor = install_for_test(owner, Mesh::offline().await).await;
719            assert!(!retire_if_idle(&mesh).await, "a stale close must not take its successor");
720            assert_eq!(slot_owner().await, Some(owner));
721            assert!(retire_if_idle(&successor).await);
722        })
723        .await;
724    }
725
726    #[tokio::test]
727    async fn a_node_in_use_keeps_serving_after_the_privacy_choice_changes() {
728        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
729        let _serial = SLOT_TESTS.lock().await;
730        crate::db::with_session(crate::db::current_session(), async {
731            let owner = crate::db::current_session().id();
732            let mesh = install_bound_as(owner, Mesh::offline().await, !crate::transport::realtime::direct()).await;
733            let (tx, _rx) = mpsc::channel(4);
734            mesh.subscribe([7u8; 32], Vec::new(), tx).await.unwrap();
735            let lease = lease().await.expect("the mesh in use");
736            assert!(Arc::ptr_eq(lease.mesh(), &mesh), "a session in progress is never cut over to a new node");
737            drop(lease);
738            mesh.unsubscribe(&[7u8; 32]).await;
739            assert!(retire_if_idle(&mesh).await);
740        })
741        .await;
742    }
743}