Skip to main content

vector_core/xdc/
session.rs

1//! A joined realtime session: one Mini App instance's gossip topic, the
2//! players on it, and the Nostr signalling that lets them find each other.
3
4use std::collections::{HashMap, HashSet};
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, Mutex};
7use std::time::Duration;
8
9use tokio::sync::{mpsc, watch};
10
11use super::mesh::{self, Mesh, MeshEvent};
12use super::signal::{self, Signal};
13use super::wire::{self, NODE_KEY_LEN};
14
15/// Frames and events queued per session before the oldest are dropped as `Lagged`.
16const QUEUE: usize = 256;
17/// Nodes a session will attribute; past this, newcomers stay anonymous.
18const ROSTER_CAP: usize = 256;
19/// Advertisements dialled at join, newest first.
20const BOOTSTRAP_CAP: usize = 32;
21const READVERTISE_DELAY: Duration = Duration::from_secs(2);
22const READVERTISE_MIN_GAP: Duration = Duration::from_secs(10);
23const LEAVE_WAIT: Duration = Duration::from_secs(15);
24/// How long a node's frames wait for an advertisement to name their sender.
25/// The advertisement travels over Nostr and the first frames straight over the
26/// mesh, so they usually arrive first.
27pub const ATTRIBUTION_WAIT: Duration = Duration::from_secs(10);
28/// Frames held per unnamed node, unnamed nodes held at once, and bytes held in all.
29const HELD_FRAMES: usize = 64;
30const HELD_NODES: usize = 32;
31const HELD_BYTES: usize = 4 * 1024 * 1024;
32
33/// A peer on the mesh. `npub` is the account whose advertisement first named
34/// this node in this chat; `None` until one has, or once two accounts have
35/// claimed the same node.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct XdcPeer {
38    pub node: [u8; NODE_KEY_LEN],
39    pub npub: Option<String>,
40}
41
42/// One frame an app (or another bot) sent on the channel.
43#[derive(Debug, Clone)]
44pub struct XdcFrame {
45    pub payload: Vec<u8>,
46    pub from: XdcPeer,
47    /// The frame came straight from `from.node` over that node's own
48    /// authenticated connection. Otherwise it was relayed, and the sender named
49    /// in its trailer is the sender's claim.
50    pub direct: bool,
51}
52
53impl XdcFrame {
54    /// The payload as UTF-8 text, if it is.
55    pub fn text(&self) -> Option<&str> {
56        std::str::from_utf8(&self.payload).ok()
57    }
58
59    /// The payload parsed as JSON, the encoding nearly every app uses
60    /// (`channel.send(new TextEncoder().encode(JSON.stringify(msg)))`).
61    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Option<T> {
62        serde_json::from_slice(&self.payload).ok()
63    }
64
65    /// The sender's npub, when you can act on it: the frame came straight from
66    /// the sender's device, and only one account in this chat has claimed that
67    /// device. Use it for anything someone could fake (a move, a vote).
68    ///
69    /// `None` when another player passed the frame on, or its sender isn't
70    /// known. A device counts as the first account in the chat to announce it.
71    pub fn verified_sender(&self) -> Option<&str> {
72        self.direct.then_some(self.from.npub.as_deref()).flatten()
73    }
74}
75
76#[derive(Debug, Clone)]
77pub enum XdcEvent {
78    Data(XdcFrame),
79    /// A node connected to us on this topic.
80    PeerJoined(XdcPeer),
81    /// A node dropped off, or a player announced they left.
82    PeerLeft(XdcPeer),
83    /// Frames were dropped: the reader fell behind, or more arrived from an
84    /// unnamed sender than the session holds while it waits for their name.
85    Lagged,
86}
87
88/// Who a node speaks for. The first advertisement binds it; a second account
89/// naming the same node makes it anonymous rather than letting the claim move.
90#[derive(Clone)]
91enum Binding {
92    Npub(String),
93    Contested,
94}
95
96/// What every holder of a session (the handle, its pump, the signal router) shares.
97struct Shared {
98    topic: [u8; 32],
99    /// Canonical base32: one spelling, whatever the caller passed.
100    topic_b32: String,
101    chat_id: String,
102    /// The account that joined. Background work runs as it, never as whoever is
103    /// logged in by then.
104    session: Arc<crate::db::Session>,
105    /// The account's mesh the topic is subscribed on.
106    mesh: Arc<Mesh>,
107    roster: Mutex<HashMap<[u8; NODE_KEY_LEN], Binding>>,
108    /// Nodes reported joined and not yet left, so each join pairs with one leave
109    /// whether gossip or a Nostr departure reports it first.
110    present: Mutex<HashSet<[u8; NODE_KEY_LEN]>>,
111    /// The reader's channel, for events that arrive over Nostr rather than the
112    /// mesh. Taken on leave, so the reader sees the session end.
113    events: Mutex<Option<mpsc::Sender<XdcEvent>>>,
114    /// Set when leaving starts; the session takes no new peers or sends after.
115    closed: AtomicBool,
116    /// Turns true once leaving has finished, departure signal included.
117    done: watch::Sender<bool>,
118    readvertise: Mutex<ReadvertiseState>,
119    /// Signalled when an advertisement names a node, so its held frames go out.
120    claimed: tokio::sync::Notify,
121    /// See [`JoinOptions::hold_unnamed`].
122    hold_unnamed: bool,
123    /// We have advertised on the topic: only then is a departure owed, or a
124    /// re-advertisement wanted.
125    advertised: AtomicBool,
126}
127
128#[derive(Default)]
129struct ReadvertiseState {
130    pending: bool,
131    last: Option<crate::rt::time::Instant>,
132}
133
134impl Shared {
135    fn npub(&self, node: &[u8; NODE_KEY_LEN]) -> Option<String> {
136        match self.roster.lock().unwrap().get(node) {
137            Some(Binding::Npub(n)) => Some(n.clone()),
138            _ => None,
139        }
140    }
141
142    fn peer(&self, node: [u8; NODE_KEY_LEN]) -> XdcPeer {
143        XdcPeer { node, npub: self.npub(&node) }
144    }
145
146    fn bind(&self, node: [u8; NODE_KEY_LEN], npub: &str) {
147        let mut roster = self.roster.lock().unwrap();
148        match roster.get(&node) {
149            None if roster.len() >= ROSTER_CAP => {}
150            None => {
151                roster.insert(node, Binding::Npub(npub.to_string()));
152            }
153            Some(Binding::Npub(n)) if n != npub => {
154                crate::log_warn!("[xdc] node {} claimed by two accounts; leaving it unattributed", mesh::short(&node));
155                roster.insert(node, Binding::Contested);
156            }
157            Some(_) => {}
158        }
159    }
160
161    fn is_closed(&self) -> bool {
162        self.closed.load(Ordering::Relaxed)
163    }
164
165    /// Whether an advertisement may still name this node: none has, and the
166    /// roster has room for it.
167    fn awaits_claim(&self, node: &[u8; NODE_KEY_LEN]) -> bool {
168        let roster = self.roster.lock().unwrap();
169        !roster.contains_key(node) && roster.len() < ROSTER_CAP
170    }
171}
172
173/// The account's joined sessions, by topic. Lives on the session: a swapped-out
174/// account's games are not this account's.
175#[derive(Default)]
176struct Joined {
177    map: Mutex<HashMap<[u8; 32], Arc<Shared>>>,
178    /// Set when the account's sessions are torn down for a swap. A join still in
179    /// flight then must not register (it would escape the teardown and keep a node
180    /// the next account inherits).
181    sealed: AtomicBool,
182}
183
184fn joined_of(session: &Arc<crate::db::Session>) -> Arc<Joined> {
185    session.scoped::<Joined, _>()
186}
187
188fn joined() -> Arc<Joined> {
189    joined_of(&crate::db::current_session())
190}
191
192/// Register a joined session, unless the account's sessions have been sealed for
193/// a swap. Under the lock the teardown seals with: either the teardown sees this
194/// session, or this sees the seal.
195fn register(registry: &Joined, shared: &Arc<Shared>) -> bool {
196    let mut map = registry.map.lock().unwrap();
197    if registry.sealed.load(Ordering::SeqCst) {
198        return false;
199    }
200    map.insert(shared.topic, shared.clone());
201    true
202}
203
204fn live_session(topic: &[u8; 32]) -> Option<Arc<Shared>> {
205    joined().map.lock().unwrap().get(topic).filter(|s| !s.is_closed()).cloned()
206}
207
208/// Whether the live account is in any realtime session.
209pub fn any_live() -> bool {
210    joined_of(&crate::db::live_session()).map.lock().unwrap().values().any(|s| !s.is_closed())
211}
212
213/// Whether this account is in the session on `topic` (base32), and not leaving it.
214pub fn is_joined(topic: &str) -> bool {
215    wire::decode_topic(topic).map(|t| live_session(&t).is_some()).unwrap_or(false)
216}
217
218/// Let sessions run outside the chosen network (Tor, I2P). Iroh connects directly, so session
219/// peers and the Iroh relay see this machine's IP; the app asks the user the same question.
220pub fn allow_outside_transport(allow: bool) {
221    crate::transport::realtime::allow_always(allow);
222}
223
224/// [`allow_outside_transport`], under its original name.
225pub fn allow_outside_tor(allow: bool) {
226    allow_outside_transport(allow);
227}
228
229/// Run `fut` as the account that joined, in its own task.
230fn spawn_as<F>(session: &Arc<crate::db::Session>, fut: F)
231where
232    F: std::future::Future<Output = ()> + Send + 'static,
233{
234    crate::db::spawn_bound(crate::db::with_session(session.clone(), fut));
235}
236
237/// A live realtime session. Dropping it leaves.
238pub struct XdcSession {
239    shared: Arc<Shared>,
240    rx: mpsc::Receiver<XdcEvent>,
241    left: bool,
242}
243
244/// How a session is joined.
245#[derive(Debug, Clone)]
246pub struct JoinOptions {
247    /// Hold a node's frames until an advertisement names its sender (see
248    /// [`XdcFrame::verified_sender`]). An app window has no use for the sender,
249    /// so it takes frames as they come.
250    pub hold_unnamed: bool,
251    /// Advertise as part of joining. Off for a caller that advertises later
252    /// ([`XdcSession::advertise`]) or never (an app with nobody to play with).
253    /// A session that never advertised leaves without a departure signal.
254    pub advertise: bool,
255    /// The caller vouches that the user accepted a session outside the chosen network (Tor,
256    /// I2P). Otherwise the account's consent, or the process-wide
257    /// [`allow_outside_transport`], decides.
258    pub outside_tor: bool,
259}
260
261impl Default for JoinOptions {
262    fn default() -> Self {
263        JoinOptions { hold_unnamed: true, advertise: true, outside_tor: false }
264    }
265}
266
267/// Join the session on `topic` (the `webxdc-topic` an app's message carries)
268/// in `chat_id` (a DM npub or Community channel id): dial everyone already
269/// advertised there, then advertise ourselves so the rest can dial us.
270pub async fn join(chat_id: &str, topic: &str) -> Result<XdcSession, String> {
271    join_with(chat_id, topic, JoinOptions::default()).await
272}
273
274/// [`join`] with options.
275pub async fn join_with(chat_id: &str, topic: &str, options: JoinOptions) -> Result<XdcSession, String> {
276    // Everything below writes and signs as the account that called, even if
277    // another logs in while this awaits.
278    crate::db::scoped(join_inner(chat_id.to_string(), topic.to_string(), options)).await
279}
280
281async fn join_inner(chat_id: String, topic: String, options: JoinOptions) -> Result<XdcSession, String> {
282    let session = crate::db::current_session();
283    let registry = joined_of(&session);
284    let switching = || Err::<XdcSession, String>("the account is switching".into());
285    if registry.sealed.load(Ordering::SeqCst) {
286        return switching();
287    }
288    let topic_bytes = wire::decode_topic(&topic)?;
289    let topic_b32 = wire::encode_topic(&topic_bytes);
290    if !options.outside_tor {
291        crate::transport::realtime::check()?;
292    }
293    // A task still bound to an account that has since swapped out must not start one.
294    if !session.is_live() {
295        return Err("account changed before the session could start".into());
296    }
297    let me = crate::state::my_public_key()
298        .and_then(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok())
299        .ok_or("Not logged in")?;
300
301    // A session still leaving this topic finishes first, so its departure
302    // signal can't land after (and erase) our new advertisement.
303    let prior = registry.map.lock().unwrap().get(&topic_bytes).cloned();
304    if let Some(prior) = prior {
305        if !prior.is_closed() {
306            return Err("already in this session".into());
307        }
308        let mut done = prior.done.subscribe();
309        let _ = crate::rt::time::timeout(LEAVE_WAIT, done.wait_for(|d| *d)).await;
310    }
311
312    if registry.sealed.load(Ordering::SeqCst) {
313        return switching();
314    }
315    let mut unregistered = Unregistered { registry: registry.clone(), owner: session.id(), armed: true };
316    // Leased until the topic is subscribed, so a retire can't close it in between.
317    let lease = mesh::lease_vouched().await?;
318    let mesh = lease.mesh().clone();
319    let addr = wire::encode_node_addr(&mesh.node_addr())?;
320    let (tx, rx) = mpsc::channel(QUEUE);
321    let shared = Arc::new(Shared {
322        topic: topic_bytes,
323        topic_b32: topic_b32.clone(),
324        chat_id: chat_id.clone(),
325        session: session.clone(),
326        mesh: mesh.clone(),
327        roster: Mutex::new(HashMap::new()),
328        present: Mutex::new(HashSet::new()),
329        events: Mutex::new(Some(tx.clone())),
330        closed: AtomicBool::new(false),
331        done: watch::channel(false).0,
332        readvertise: Mutex::new(ReadvertiseState::default()),
333        claimed: tokio::sync::Notify::new(),
334        hold_unnamed: options.hold_unnamed,
335        advertised: AtomicBool::new(false),
336    });
337
338    // Only this chat's advertisements: a signal persisted from any other chat
339    // (a stranger's DM, a channel that banned its sender) is no player here.
340    let mut bootstrap = Vec::new();
341    for ad in crate::db::miniapps::get_active_peer_advertisements_in(&topic_b32, &chat_id, &me, BOOTSTRAP_CAP).unwrap_or_default() {
342        if let Ok(peer) = wire::decode_node_addr(&ad.node_addr_encoded) {
343            shared.bind(*peer.id.as_bytes(), &ad.npub);
344            bootstrap.push(peer);
345        }
346    }
347    crate::log_info!("[xdc] joining {} in {} with {} known peer(s)", &topic_b32[..8], short_chat(&chat_id), bootstrap.len());
348
349    let (mesh_tx, mesh_rx) = mpsc::channel(QUEUE);
350    mesh.subscribe(topic_bytes, bootstrap, mesh_tx).await?;
351    drop(lease);
352    if !register(&registry, &shared) {
353        mesh.unsubscribe(&topic_bytes).await;
354        return Err("the account switched while joining".into());
355    }
356    unregistered.armed = false;
357    spawn_as(&session, pump(shared.clone(), mesh_rx, tx));
358    // The handle exists before the advertisement goes out, so a join dropped
359    // while publishing still leaves.
360    let joined = XdcSession { shared, rx, left: false };
361    if options.advertise {
362        if let Err(e) = advertise(&joined.shared, &addr).await {
363            crate::log_warn!("[xdc] advertisement failed, peers must dial us from an older one: {e}");
364        }
365    }
366    Ok(joined)
367}
368
369/// Held by a join until its session is registered. A join of a sealed account
370/// that stops before then (backed out, failed or cancelled) may have bound the
371/// mesh after the teardown retired it, so it retires it again.
372struct Unregistered {
373    registry: Arc<Joined>,
374    owner: u64,
375    armed: bool,
376}
377
378impl Drop for Unregistered {
379    fn drop(&mut self) {
380        if self.armed && self.registry.sealed.load(Ordering::SeqCst) {
381            mesh::retire(self.owner);
382        }
383    }
384}
385
386/// Translate mesh events for the reader, and re-advertise when a neighbor drops
387/// so a peer that reconnects with a fresh node can find us again. A node's
388/// events wait (see [`Held`]) until an advertisement names who sent them.
389async fn pump(shared: Arc<Shared>, mut mesh_rx: mpsc::Receiver<MeshEvent>, tx: mpsc::Sender<XdcEvent>) {
390    let mut held = Held::default();
391    loop {
392        let wake = held.deadline();
393        let ev = tokio::select! {
394            ev = mesh_rx.recv() => match ev {
395                Some(ev) => Some(ev),
396                None => break,
397            },
398            _ = shared.claimed.notified() => None,
399            _ = crate::rt::time::sleep_until(wake.unwrap_or_else(crate::rt::time::Instant::now)), if wake.is_some() => None,
400        };
401        for out in held.release(&shared, crate::rt::time::Instant::now()) {
402            if tx.send(out).await.is_err() {
403                return;
404            }
405        }
406        let Some(ev) = ev else { continue };
407        let out = match ev {
408            MeshEvent::Data { payload, sender, direct } => match held.hold_frame(&shared, sender, payload, direct) {
409                Some(payload) => XdcEvent::Data(XdcFrame { payload, from: shared.peer(sender), direct }),
410                None => continue,
411            },
412            MeshEvent::NeighborUp(node) => {
413                if held.hold_arrival(&shared, node) || !shared.present.lock().unwrap().insert(node) {
414                    continue;
415                }
416                XdcEvent::PeerJoined(shared.peer(node))
417            }
418            MeshEvent::NeighborDown(node) => {
419                readvertise_later(shared.clone());
420                held.forget_arrival(&node);
421                if !shared.present.lock().unwrap().remove(&node) {
422                    continue;
423                }
424                XdcEvent::PeerLeft(shared.peer(node))
425            }
426            MeshEvent::Lagged => XdcEvent::Lagged,
427        };
428        if tx.send(out).await.is_err() {
429            break;
430        }
431    }
432}
433
434/// Events from nodes no advertisement has named yet. They are held until one
435/// does, then delivered in order with their sender, so a frame is never handed
436/// over anonymous when its sender was about to be provable. A node still
437/// unnamed after [`ATTRIBUTION_WAIT`] is delivered anonymous from then on.
438#[derive(Default)]
439struct Held {
440    nodes: Vec<HeldNode>,
441    waited: HashSet<[u8; NODE_KEY_LEN]>,
442    bytes: usize,
443}
444
445struct HeldNode {
446    node: [u8; NODE_KEY_LEN],
447    since: crate::rt::time::Instant,
448    arrived: bool,
449    frames: Vec<(Vec<u8>, bool)>,
450    dropped: bool,
451}
452
453impl Held {
454    /// The node's hold, opened only for `opens` events: a node connected to us,
455    /// or a frame straight from it. A relayed frame names its sender unproven,
456    /// and anyone could fill every slot with made-up ones.
457    fn entry(&mut self, shared: &Shared, node: [u8; NODE_KEY_LEN], opens: bool) -> Option<&mut HeldNode> {
458        if let Some(i) = self.nodes.iter().position(|h| h.node == node) {
459            return Some(&mut self.nodes[i]);
460        }
461        if !shared.hold_unnamed || !opens || self.waited.contains(&node) || self.nodes.len() >= HELD_NODES || !shared.awaits_claim(&node) {
462            return None;
463        }
464        self.nodes.push(HeldNode { node, since: crate::rt::time::Instant::now(), arrived: false, frames: Vec::new(), dropped: false });
465        self.nodes.last_mut()
466    }
467
468    /// Hold a frame, or hand its payload back to deliver now.
469    fn hold_frame(&mut self, shared: &Shared, node: [u8; NODE_KEY_LEN], payload: Vec<u8>, direct: bool) -> Option<Vec<u8>> {
470        let room = HELD_BYTES.saturating_sub(self.bytes);
471        let Some(h) = self.entry(shared, node, direct) else { return Some(payload) };
472        if h.frames.len() < HELD_FRAMES && payload.len() <= room {
473            let len = payload.len();
474            h.frames.push((payload, direct));
475            self.bytes += len;
476        } else {
477            h.dropped = true;
478        }
479        None
480    }
481
482    fn hold_arrival(&mut self, shared: &Shared, node: [u8; NODE_KEY_LEN]) -> bool {
483        self.entry(shared, node, true).map(|h| h.arrived = true).is_some()
484    }
485
486    fn forget_arrival(&mut self, node: &[u8; NODE_KEY_LEN]) {
487        if let Some(h) = self.nodes.iter_mut().find(|h| h.node == *node) {
488            h.arrived = false;
489        }
490    }
491
492    fn deadline(&self) -> Option<crate::rt::time::Instant> {
493        self.nodes.iter().map(|h| h.since + ATTRIBUTION_WAIT).min()
494    }
495
496    /// Everything now named, or out of time, in the order it arrived.
497    fn release(&mut self, shared: &Shared, now: crate::rt::time::Instant) -> Vec<XdcEvent> {
498        let mut out = Vec::new();
499        let mut kept = Vec::new();
500        for h in std::mem::take(&mut self.nodes) {
501            let named = !shared.awaits_claim(&h.node);
502            if !named && now < h.since + ATTRIBUTION_WAIT {
503                kept.push(h);
504                continue;
505            }
506            if !named {
507                if self.waited.len() >= ROSTER_CAP {
508                    self.waited.clear();
509                }
510                self.waited.insert(h.node);
511            }
512            self.bytes -= h.frames.iter().map(|(p, _)| p.len()).sum::<usize>();
513            let from = shared.peer(h.node);
514            if h.arrived && shared.present.lock().unwrap().insert(h.node) {
515                out.push(XdcEvent::PeerJoined(from.clone()));
516            }
517            out.extend(h.frames.into_iter().map(|(payload, direct)| XdcEvent::Data(XdcFrame { payload, from: from.clone(), direct })));
518            if h.dropped {
519                out.push(XdcEvent::Lagged);
520            }
521        }
522        self.nodes = kept;
523        out
524    }
525}
526
527/// One pending re-advertisement per session, at most one per `READVERTISE_MIN_GAP`:
528/// a peer flapping its connection must not set our publish rate.
529fn readvertise_later(shared: Arc<Shared>) {
530    if !shared.advertised.load(Ordering::SeqCst) {
531        return;
532    }
533    let delay = {
534        let mut st = shared.readvertise.lock().unwrap();
535        if st.pending {
536            return;
537        }
538        st.pending = true;
539        let since = st.last.map(|t| t.elapsed()).unwrap_or(READVERTISE_MIN_GAP);
540        READVERTISE_DELAY.max(READVERTISE_MIN_GAP.saturating_sub(since))
541    };
542    let session = shared.session.clone();
543    spawn_as(&session, async move {
544        crate::rt::time::sleep(delay).await;
545        {
546            let mut st = shared.readvertise.lock().unwrap();
547            st.pending = false;
548            st.last = Some(crate::rt::time::Instant::now());
549        }
550        if shared.is_closed() {
551            return;
552        }
553        if let Ok(addr) = wire::encode_node_addr(&shared.mesh.node_addr()) {
554            let _ = advertise(&shared, &addr).await;
555        }
556    });
557}
558
559impl XdcSession {
560    /// The session's topic, base32, as the app's message carries it.
561    pub fn topic(&self) -> &str {
562        &self.shared.topic_b32
563    }
564
565    /// The DM npub or Community channel id the session is played in.
566    pub fn chat_id(&self) -> &str {
567        &self.shared.chat_id
568    }
569
570    /// Broadcast a frame to everyone on the channel, at most 128 000 bytes.
571    /// Like the app's own `send`, delivery is best-effort and never echoes back.
572    pub async fn send(&self, payload: impl Into<Vec<u8>>) -> Result<(), String> {
573        self.sender().send(payload).await
574    }
575
576    /// The next event, or `None` once the session has ended.
577    pub async fn recv(&mut self) -> Option<XdcEvent> {
578        self.rx.recv().await
579    }
580
581    /// Who a node speaks for, by the advertisement that first named it here.
582    pub fn npub_of(&self, node: &[u8; NODE_KEY_LEN]) -> Option<String> {
583        self.shared.npub(node)
584    }
585
586    /// The mesh the session runs on (see [`mesh::retire_if_idle`]).
587    pub fn mesh(&self) -> Arc<Mesh> {
588        self.shared.mesh.clone()
589    }
590
591    /// How many nodes are directly connected to us on this topic.
592    pub async fn neighbor_count(&self) -> usize {
593        self.shared.mesh.neighbor_count(&self.shared.topic).await
594    }
595
596    /// A handle that sends on this session from another task; it stops working
597    /// once the session is left.
598    pub fn sender(&self) -> XdcSender {
599        XdcSender { shared: self.shared.clone() }
600    }
601
602    /// Resolves once this session has fully left, departure signal included,
603    /// however it ends (dropped, left, or torn down with its account).
604    pub fn finished(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
605        let mut done = self.shared.done.subscribe();
606        async move {
607            let _ = done.wait_for(|d| *d).await;
608        }
609    }
610
611    /// Start leaving without waiting: [`recv`](Self::recv) returns `None` from
612    /// then on, and [`finished`](Self::finished) resolves once it is done.
613    pub fn end(&mut self) {
614        if self.left || !crate::rt::can_spawn() {
615            return;
616        }
617        self.left = true;
618        let shared = self.shared.clone();
619        spawn_as(&shared.session.clone(), leave(shared, true));
620    }
621
622    /// Advertise our node on this session's topic again, for a session joined
623    /// without advertising ([`JoinOptions::advertise`]) or to be found anew.
624    pub async fn advertise(&self) -> Result<(), String> {
625        let addr = wire::encode_node_addr(&self.shared.mesh.node_addr())?;
626        crate::db::with_session(self.shared.session.clone(), advertise(&self.shared, &addr)).await
627    }
628
629    /// Leave: drop the subscription and tell the chat we went.
630    pub async fn leave(mut self) {
631        self.left = true;
632        let shared = self.shared.clone();
633        crate::db::with_session(shared.session.clone(), leave(shared, true)).await;
634    }
635}
636
637/// Marks a session finished when dropped: unsubscribed, deregistered, and
638/// `done` set for anyone waiting on it. Held across every await of a leave, so
639/// a leave cancelled half-way (an account swap's deadline) still never strands
640/// a waiter or leaves the topic subscribed.
641struct Finish {
642    shared: Arc<Shared>,
643    /// The topic may still be subscribed.
644    subscribed: bool,
645}
646
647impl Finish {
648    fn complete(shared: &Arc<Shared>) {
649        shared.events.lock().unwrap_or_else(|e| e.into_inner()).take();
650        {
651            let reg = joined_of(&shared.session);
652            let mut map = reg.map.lock().unwrap_or_else(|e| e.into_inner());
653            if map.get(&shared.topic).is_some_and(|s| Arc::ptr_eq(s, shared)) {
654                map.remove(&shared.topic);
655            }
656        }
657        shared.done.send_replace(true);
658    }
659}
660
661impl Drop for Finish {
662    fn drop(&mut self) {
663        if !self.subscribed || !crate::rt::can_spawn() {
664            return Finish::complete(&self.shared);
665        }
666        // Cut off before the unsubscribe finished: finish it (or wait out the one
667        // under way) first, and only then release waiters.
668        let shared = self.shared.clone();
669        spawn_as(&shared.session.clone(), async move {
670            shared.mesh.unsubscribe(&shared.topic).await;
671            Finish::complete(&shared);
672        });
673    }
674}
675
676/// Start leaving: `None` if another caller already has (wait on `done` instead).
677async fn begin_leave(shared: &Arc<Shared>) -> Option<Finish> {
678    if shared.closed.swap(true, Ordering::Relaxed) {
679        return None;
680    }
681    let mut finish = Finish { shared: shared.clone(), subscribed: true };
682    shared.events.lock().unwrap().take();
683    shared.mesh.unsubscribe(&shared.topic).await;
684    finish.subscribed = false;
685    Some(finish)
686}
687
688/// Publish the departure, unless the account is no longer the one logged in:
689/// its signer is gone, and another account's would link the two.
690async fn announce_left(shared: &Shared) {
691    if shared.session.is_live() && shared.advertised.load(Ordering::SeqCst) {
692        let _ = signal::send(&shared.chat_id, &shared.topic_b32, None).await;
693        let now = unix_now();
694        let owner = last_left_of(&shared.session);
695        let mut left = owner.lock().unwrap();
696        left.retain(|_, at| at.saturating_add(LAST_LEFT_KEEP_SECS) >= now);
697        left.insert(shared.topic, now);
698    }
699}
700
701/// When this account last announced leaving each topic (unix seconds).
702struct LastLeft;
703
704/// A departure only delays an advertisement made within its own second; this is slack for
705/// the clock stepping back.
706const LAST_LEFT_KEEP_SECS: u64 = 60;
707
708fn last_left_of(session: &Arc<crate::db::Session>) -> Arc<Mutex<HashMap<[u8; 32], u64>>> {
709    session.scoped::<LastLeft, _>()
710}
711
712fn unix_now() -> u64 {
713    crate::clock::now_secs()
714}
715
716/// Advertise our node on the session's topic. Dated after our own last
717/// departure from it: a departure wins a same-second tie, so an advertisement
718/// in that second would read as stale and a quick reopen would stay invisible.
719async fn advertise(shared: &Shared, addr: &str) -> Result<(), String> {
720    let left = last_left_of(&shared.session).lock().unwrap().get(&shared.topic).copied();
721    if let Some(left) = left {
722        let now = Duration::from_millis(crate::clock::now_ms());
723        if now.as_secs() <= left {
724            let next = Duration::from_secs(left + 1).saturating_sub(now);
725            crate::rt::time::sleep(next + Duration::from_millis(50)).await;
726        }
727    }
728    // A departure must stay the last word. The send dates its event before
729    // its first await, so nothing can leave between this check and that.
730    if shared.is_closed() {
731        return Err("the session has ended".into());
732    }
733    shared.advertised.store(true, Ordering::SeqCst);
734    signal::send(&shared.chat_id, &shared.topic_b32, Some(addr)).await
735}
736
737async fn leave(shared: Arc<Shared>, announce: bool) {
738    let Some(finish) = begin_leave(&shared).await else {
739        let mut done = shared.done.subscribe();
740        let _ = done.wait_for(|d| *d).await;
741        return;
742    };
743    if announce {
744        announce_left(&shared).await;
745    }
746    drop(finish);
747    crate::log_info!("[xdc] left {}", &shared.topic_b32[..8]);
748}
749
750/// Leave every session of the account now logged in, for an account swap: it
751/// seals the account's registry for good, so no join can slip in behind the
752/// teardown. Everything local happens next and unconditionally, the account's
753/// mesh is closed (the next account binds a fresh node key), and the departure
754/// signals go last, together, within `deadline`. Abandoned part-way, the
755/// account refuses new sessions until it next logs in.
756pub async fn leave_all(deadline: Duration) {
757    leave_every(deadline, true).await;
758}
759
760/// [`leave_all`] for a network switch: the account stays open, so later joins (with consent
761/// for the new network) still work. The mesh closes once nothing uses it.
762pub async fn leave_all_for_switch(deadline: Duration) {
763    leave_every(deadline, false).await;
764    mesh::retire_live_if_idle().await;
765}
766
767async fn leave_every(deadline: Duration, seal: bool) {
768    let session = crate::db::current_session();
769    let registry = joined_of(&session);
770    let all: Vec<Arc<Shared>> = {
771        let map = registry.map.lock().unwrap();
772        if seal {
773            registry.sealed.store(true, Ordering::SeqCst);
774        }
775        map.values().cloned().collect()
776    };
777    let mut leaving = Vec::new();
778    let mut already = Vec::new();
779    for shared in all {
780        match begin_leave(&shared).await {
781            Some(finish) => leaving.push((shared, finish)),
782            None => already.push(shared),
783        }
784    }
785    if seal {
786        mesh::retire(session.id());
787    }
788    let announcements = leaving.into_iter().map(|(shared, finish)| async move {
789        crate::db::with_session(shared.session.clone(), announce_left(&shared)).await;
790        drop(finish);
791    });
792    // Sessions that were already leaving get the same deadline to finish their own.
793    let pending = already.into_iter().map(|shared| async move {
794        let mut done = shared.done.subscribe();
795        let _ = done.wait_for(|d| *d).await;
796    });
797    let _ = crate::rt::time::timeout(
798        deadline,
799        futures_util::future::join(futures_util::future::join_all(announcements), futures_util::future::join_all(pending)),
800    )
801    .await;
802}
803
804/// Sends on a session from anywhere; see [`XdcSession::sender`].
805#[derive(Clone)]
806pub struct XdcSender {
807    shared: Arc<Shared>,
808}
809
810impl XdcSender {
811    pub async fn send(&self, payload: impl Into<Vec<u8>>) -> Result<(), String> {
812        if self.shared.is_closed() {
813            return Err("the session has ended".into());
814        }
815        self.shared.mesh.broadcast(&self.shared.topic, payload.into()).await
816    }
817
818    pub fn topic(&self) -> &str {
819        &self.shared.topic_b32
820    }
821
822    /// Advertise our node on the session's topic (see [`XdcSession::advertise`]).
823    pub async fn advertise(&self) -> Result<(), String> {
824        if self.shared.is_closed() {
825            return Err("the session has ended".into());
826        }
827        let addr = wire::encode_node_addr(&self.shared.mesh.node_addr())?;
828        crate::db::with_session(self.shared.session.clone(), advertise(&self.shared, &addr)).await
829    }
830}
831
832impl Drop for XdcSession {
833    fn drop(&mut self) {
834        // A runtime already shutting down has no one left to tell.
835        if !self.left && crate::rt::can_spawn() {
836            let shared = self.shared.clone();
837            spawn_as(&shared.session.clone(), leave(shared, true));
838        }
839    }
840}
841
842/// Apply an ingested signal to a live session this account is in: learn the
843/// sender's node, dial an advertised peer, report a departure. Returns false
844/// when no live session is on the topic.
845pub async fn apply_signal(sig: &Signal) -> bool {
846    let Ok(topic) = wire::decode_topic(&sig.topic) else { return false };
847    let Some(shared) = live_session(&topic) else { return false };
848    // A signal for our topic from another chat is not a player of this session.
849    // Our own npub is: another device of this account plays as us.
850    if shared.chat_id != sig.chat_id || !sig.current {
851        return true;
852    }
853    match &sig.node_addr {
854        Some(addr) => {
855            let node = *addr.id.as_bytes();
856            shared.bind(node, &sig.npub);
857            shared.claimed.notify_one();
858            if node == shared.mesh.node_key() {
859                return true;
860            }
861            // Dialled in the background: signals arrive inside message processing,
862            // which one unreachable peer must not hold up.
863            let (shared, addr) = (shared.clone(), addr.clone());
864            spawn_as(&shared.session.clone(), async move {
865                match shared.mesh.add_peer(&topic, addr).await {
866                    // A player who reopens the app on a node gossip never saw leave
867                    // gets no fresh NeighborUp; the reachable advertisement is the arrival.
868                    Ok(()) => {
869                        let tx = shared.events.lock().unwrap().clone();
870                        if let Some(tx) = tx {
871                            if shared.present.lock().unwrap().insert(node) && tx.send(XdcEvent::PeerJoined(shared.peer(node))).await.is_err() {
872                                shared.present.lock().unwrap().remove(&node);
873                            }
874                        }
875                    }
876                    Err(e) => crate::log_debug!("[xdc] could not reach advertised peer {}: {e}", mesh::short(&node)),
877                }
878            });
879        }
880        // Gossip keeps a neighbor whose app closed while its node stays up, so the
881        // departure signal is often the only word that a player left.
882        None => {
883            let gone: Vec<[u8; NODE_KEY_LEN]> = {
884                let mut present = shared.present.lock().unwrap();
885                let mine: Vec<_> = present.iter().copied().filter(|n| shared.npub(n).as_deref() == Some(sig.npub.as_str())).collect();
886                for n in &mine {
887                    present.remove(n);
888                }
889                mine
890            };
891            let tx = shared.events.lock().unwrap().clone();
892            if let Some(tx) = tx {
893                for node in gone {
894                    let _ = tx.send(XdcEvent::PeerLeft(shared.peer(node))).await;
895                }
896            }
897        }
898    }
899    true
900}
901
902fn short_chat(chat_id: &str) -> &str {
903    chat_id.get(..12).unwrap_or(chat_id)
904}
905
906#[cfg(test)]
907mod tests {
908    use super::*;
909
910    async fn unregistered(chat: &str, topic: [u8; 32]) -> (Arc<Shared>, mpsc::Receiver<XdcEvent>) {
911        let (tx, rx) = mpsc::channel(QUEUE);
912        let shared = Arc::new(Shared {
913            topic,
914            topic_b32: wire::encode_topic(&topic),
915            chat_id: chat.to_string(),
916            session: crate::db::current_session(),
917            mesh: Arc::new(Mesh::offline().await),
918            roster: Mutex::new(HashMap::new()),
919            present: Mutex::new(HashSet::new()),
920            events: Mutex::new(Some(tx)),
921            closed: AtomicBool::new(false),
922            done: watch::channel(false).0,
923            readvertise: Mutex::new(ReadvertiseState::default()),
924            claimed: tokio::sync::Notify::new(),
925            hold_unnamed: true,
926            advertised: AtomicBool::new(false),
927        });
928        (shared, rx)
929    }
930
931    async fn shared_for(chat: &str, topic: [u8; 32]) -> (Arc<Shared>, mpsc::Receiver<XdcEvent>) {
932        let (shared, rx) = unregistered(chat, topic).await;
933        joined().map.lock().unwrap().insert(topic, shared.clone());
934        (shared, rx)
935    }
936
937    fn sig(chat: &str, npub: &str, topic: &[u8; 32], node: Option<[u8; 32]>, current: bool) -> Signal {
938        Signal {
939            chat_id: chat.to_string(),
940            npub: npub.to_string(),
941            topic: wire::encode_topic(topic),
942            node_addr: node.map(|n| iroh::EndpointAddr::new(iroh::PublicKey::from_bytes(&n).unwrap())),
943            created_at: 1,
944            current,
945        }
946    }
947
948    fn node(seed: u8) -> [u8; 32] {
949        *iroh::SecretKey::from([seed; 32]).public().as_bytes()
950    }
951
952    #[tokio::test]
953    async fn the_first_account_to_name_a_node_keeps_it_and_a_rival_claim_unattributes_it() {
954        // Bound to one session: parallel tests swap the process-wide one.
955        crate::db::with_session(crate::db::current_session(), async {
956            let topic = [41u8; 32];
957            let (shared, _rx) = shared_for("npub1chat", topic).await;
958            let a = node(1);
959            apply_signal(&sig("npub1chat", "npub1alice", &topic, Some(a), true)).await;
960            assert_eq!(shared.npub(&a).as_deref(), Some("npub1alice"));
961            apply_signal(&sig("npub1chat", "npub1alice", &topic, Some(a), true)).await;
962            assert_eq!(shared.npub(&a).as_deref(), Some("npub1alice"), "re-advertising is not a rival");
963
964            apply_signal(&sig("npub1chat", "npub1mallory", &topic, Some(a), true)).await;
965            assert_eq!(shared.npub(&a), None, "a contested node is nobody's");
966            apply_signal(&sig("npub1chat", "npub1alice", &topic, Some(a), true)).await;
967            assert_eq!(shared.npub(&a), None, "contest is permanent for the session");
968            let frame = XdcFrame { payload: vec![], from: shared.peer(a), direct: true };
969            assert_eq!(frame.verified_sender(), None);
970            joined().map.lock().unwrap().remove(&topic);
971        })
972        .await;
973    }
974
975    #[tokio::test]
976    async fn signals_from_another_chat_or_superseded_ones_change_nothing() {
977        // Bound to one session: parallel tests swap the process-wide one.
978        crate::db::with_session(crate::db::current_session(), async {
979            let topic = [42u8; 32];
980            let (shared, _rx) = shared_for("npub1chat", topic).await;
981            let a = node(2);
982            assert!(apply_signal(&sig("npub1stranger", "npub1stranger", &topic, Some(a), true)).await);
983            assert!(apply_signal(&sig("npub1chat", "npub1alice", &topic, Some(a), false)).await);
984            assert_eq!(shared.npub(&a), None);
985            assert!(!apply_signal(&sig("npub1chat", "npub1alice", &[43u8; 32], Some(a), true)).await, "no session on that topic");
986            joined().map.lock().unwrap().remove(&topic);
987        })
988        .await;
989    }
990
991    #[tokio::test]
992    async fn a_departure_leaves_only_its_own_nodes_and_pairs_with_the_arrival() {
993        // Bound to one session: parallel tests swap the process-wide one.
994        crate::db::with_session(crate::db::current_session(), async {
995            let topic = [44u8; 32];
996            let (shared, mut rx) = shared_for("npub1chat", topic).await;
997            let (a, b) = (node(3), node(4));
998            shared.bind(a, "npub1alice");
999            shared.bind(b, "npub1bob");
1000            shared.present.lock().unwrap().extend([a, b]);
1001
1002            apply_signal(&sig("npub1chat", "npub1mallory", &topic, None, true)).await;
1003            assert!(rx.try_recv().is_err(), "a stranger's departure removes nobody");
1004
1005            apply_signal(&sig("npub1chat", "npub1alice", &topic, None, true)).await;
1006            match rx.try_recv() {
1007                Ok(XdcEvent::PeerLeft(p)) => assert_eq!((p.node, p.npub.as_deref()), (a, Some("npub1alice"))),
1008                other => panic!("expected alice to leave, got {other:?}"),
1009            }
1010            apply_signal(&sig("npub1chat", "npub1alice", &topic, None, true)).await;
1011            assert!(rx.try_recv().is_err(), "one leave per arrival");
1012            assert!(shared.present.lock().unwrap().contains(&b));
1013            joined().map.lock().unwrap().remove(&topic);
1014        })
1015        .await;
1016    }
1017
1018    #[tokio::test]
1019    async fn a_closing_session_is_not_joined_and_takes_no_signals() {
1020        // Bound to one session: parallel tests swap the process-wide one.
1021        crate::db::with_session(crate::db::current_session(), async {
1022            let topic = [45u8; 32];
1023            let (shared, _rx) = shared_for("npub1chat", topic).await;
1024            assert!(is_joined(&wire::encode_topic(&topic)));
1025            shared.closed.store(true, Ordering::Relaxed);
1026            assert!(!is_joined(&wire::encode_topic(&topic)));
1027            assert!(!apply_signal(&sig("npub1chat", "npub1alice", &topic, Some(node(5)), true)).await);
1028            joined().map.lock().unwrap().remove(&topic);
1029        })
1030        .await;
1031    }
1032
1033    #[tokio::test]
1034    async fn a_leave_cut_off_half_way_still_finishes() {
1035        crate::db::with_session(crate::db::current_session(), async {
1036            let topic = [46u8; 32];
1037            let (shared, mut rx) = shared_for("npub1chat", topic).await;
1038            let mut done = shared.done.subscribe();
1039            let cut = async {
1040                let _finish = Finish { shared: shared.clone(), subscribed: false };
1041                std::future::pending::<()>().await;
1042            };
1043            assert!(tokio::time::timeout(Duration::from_millis(20), cut).await.is_err());
1044            assert!(*done.borrow_and_update(), "waiters are released");
1045            assert!(!joined().map.lock().unwrap().contains_key(&topic), "deregistered");
1046            // (The pump's own sender, absent here, ends with the unsubscribe.)
1047            assert!(rx.recv().await.is_none(), "the reader sees the end");
1048        })
1049        .await;
1050    }
1051
1052    #[tokio::test]
1053    async fn a_leave_cut_off_mid_unsubscribe_releases_waiters_only_once_the_topic_is_gone() {
1054        crate::db::with_session(crate::db::current_session(), async {
1055            let topic = [48u8; 32];
1056            let (shared, _rx) = shared_for("npub1chat", topic).await;
1057            let (mesh_tx, mut mesh_rx) = mpsc::channel(4);
1058            shared.mesh.subscribe(topic, Vec::new(), mesh_tx).await.unwrap();
1059            let mut done = shared.done.subscribe();
1060            // One poll: the leave starts unsubscribing, then is dropped.
1061            assert!(futures_util::FutureExt::now_or_never(begin_leave(&shared)).is_none());
1062            assert!(!*done.borrow(), "nobody released before the topic is dropped");
1063            done.wait_for(|d| *d).await.unwrap();
1064            assert!(
1065                matches!(mesh_rx.try_recv(), Err(mpsc::error::TryRecvError::Disconnected)),
1066                "the old subscription's handles are gone by the time waiters are released"
1067            );
1068            assert!(!joined().map.lock().unwrap().contains_key(&topic));
1069        })
1070        .await;
1071    }
1072
1073    #[tokio::test]
1074    async fn a_join_after_the_teardown_sealed_the_account_backs_out() {
1075        crate::db::with_session(crate::db::current_session(), async {
1076            let registry = joined();
1077            registry.sealed.store(true, Ordering::SeqCst);
1078            let topic = wire::encode_topic(&[47u8; 32]);
1079            let r = join_inner("npub1chat".into(), topic.clone(), JoinOptions::default()).await;
1080            registry.sealed.store(false, Ordering::SeqCst);
1081            // Refused before anything is bound: the later back-out says otherwise.
1082            assert_eq!(r.err().as_deref(), Some("the account is switching"));
1083        })
1084        .await;
1085    }
1086
1087    #[tokio::test]
1088    async fn a_network_switch_ends_every_session_but_keeps_later_joins_open() {
1089        let _serial = mesh::SLOT_TESTS.lock().await;
1090        crate::db::with_session(crate::db::current_session(), async {
1091            let owner = crate::db::current_session().id();
1092            let node = mesh::install_for_test(owner, Mesh::offline().await).await;
1093            let topic = [45u8; 32];
1094            let (shared, _rx) = shared_for("npub1chat", topic).await;
1095            leave_all_for_switch(Duration::from_millis(200)).await;
1096            assert!(shared.is_closed(), "the session ended");
1097            assert!(!joined().sealed.load(Ordering::SeqCst), "a switch is not an account swap");
1098            assert_eq!(mesh::slot_owner().await, None, "the idle node closed with its last session");
1099            drop(node);
1100            let r = join_inner("npub1chat".into(), wire::encode_topic(&[44u8; 32]), JoinOptions::default()).await;
1101            assert_ne!(r.err().as_deref(), Some("the account is switching"));
1102        })
1103        .await;
1104    }
1105
1106    #[tokio::test]
1107    async fn a_join_that_finishes_after_the_seal_is_not_registered() {
1108        crate::db::with_session(crate::db::current_session(), async {
1109            let topic = [49u8; 32];
1110            let (shared, _rx) = unregistered("npub1chat", topic).await;
1111            let registry = Joined::default();
1112            registry.sealed.store(true, Ordering::SeqCst);
1113            assert!(!register(&registry, &shared));
1114            assert!(registry.map.lock().unwrap().is_empty(), "a sealed account gains no session");
1115            let open = Joined::default();
1116            assert!(register(&open, &shared));
1117            assert!(open.map.lock().unwrap().contains_key(&topic));
1118        })
1119        .await;
1120    }
1121
1122    #[tokio::test]
1123    async fn a_sealed_join_that_stops_before_registering_retires_the_mesh_it_bound() {
1124        let _serial = mesh::SLOT_TESTS.lock().await;
1125        let owner = u64::MAX - 47;
1126        mesh::install_for_test(owner, Mesh::offline().await).await;
1127        let registry = Arc::new(Joined::default());
1128        drop(Unregistered { registry: registry.clone(), owner, armed: true });
1129        tokio::time::sleep(Duration::from_millis(50)).await;
1130        assert_eq!(mesh::slot_owner().await, Some(owner), "an account still open keeps its mesh");
1131        registry.sealed.store(true, Ordering::SeqCst);
1132        drop(Unregistered { registry: registry.clone(), owner, armed: false });
1133        tokio::time::sleep(Duration::from_millis(50)).await;
1134        assert_eq!(mesh::slot_owner().await, Some(owner), "a registered join keeps it");
1135        drop(Unregistered { registry, owner, armed: true });
1136        for _ in 0..100 {
1137            if mesh::slot_owner().await != Some(owner) {
1138                return;
1139            }
1140            tokio::time::sleep(Duration::from_millis(10)).await;
1141        }
1142        panic!("the sealed account's mesh was not retired");
1143    }
1144
1145    fn piped(shared: &Arc<Shared>) -> (mpsc::Sender<MeshEvent>, mpsc::Receiver<XdcEvent>) {
1146        let (mesh_tx, mesh_rx) = mpsc::channel(QUEUE);
1147        let (tx, rx) = mpsc::channel(QUEUE);
1148        crate::db::spawn_bound(pump(shared.clone(), mesh_rx, tx));
1149        (mesh_tx, rx)
1150    }
1151
1152    fn data(node: [u8; 32], text: &str) -> MeshEvent {
1153        MeshEvent::Data { payload: text.as_bytes().to_vec(), sender: node, direct: true }
1154    }
1155
1156    async fn next(rx: &mut mpsc::Receiver<XdcEvent>) -> Option<XdcEvent> {
1157        tokio::time::timeout(Duration::from_millis(300), rx.recv()).await.ok().flatten()
1158    }
1159
1160    fn said(ev: Option<XdcEvent>) -> (Option<String>, Option<String>) {
1161        match ev {
1162            Some(XdcEvent::Data(f)) => (f.text().map(str::to_string), f.verified_sender().map(str::to_string)),
1163            other => panic!("expected a frame, got {other:?}"),
1164        }
1165    }
1166
1167    #[tokio::test]
1168    async fn a_frame_waits_for_an_advertisement_to_name_its_sender() {
1169        crate::db::with_session(crate::db::current_session(), async {
1170            let topic = [50u8; 32];
1171            let (shared, _events) = shared_for("npub1chat", topic).await;
1172            let (alice, bob) = (node(6), node(7));
1173            shared.bind(bob, "npub1bob");
1174            let (mesh, mut rx) = piped(&shared);
1175            mesh.send(MeshEvent::NeighborUp(alice)).await.unwrap();
1176            mesh.send(data(alice, "first")).await.unwrap();
1177            mesh.send(data(alice, "second")).await.unwrap();
1178            mesh.send(data(bob, "hi")).await.unwrap();
1179            assert_eq!(said(next(&mut rx).await), (Some("hi".into()), Some("npub1bob".into())), "a named sender isn't held");
1180            assert!(next(&mut rx).await.is_none(), "alice's events wait for her advertisement");
1181
1182            // Her advertisement lands (dialling her fake node then fails in the background).
1183            let ad = sig("npub1chat", "npub1alice", &topic, Some(alice), true);
1184            crate::db::spawn_bound(async move {
1185                apply_signal(&ad).await;
1186            });
1187            match next(&mut rx).await {
1188                Some(XdcEvent::PeerJoined(p)) => assert_eq!(p.npub.as_deref(), Some("npub1alice")),
1189                other => panic!("expected alice to arrive first, got {other:?}"),
1190            }
1191            assert_eq!(said(next(&mut rx).await), (Some("first".into()), Some("npub1alice".into())));
1192            assert_eq!(said(next(&mut rx).await), (Some("second".into()), Some("npub1alice".into())));
1193            mesh.send(data(alice, "third")).await.unwrap();
1194            assert_eq!(said(next(&mut rx).await), (Some("third".into()), Some("npub1alice".into())), "named from then on");
1195            joined().map.lock().unwrap().remove(&topic);
1196        })
1197        .await;
1198    }
1199
1200    #[tokio::test]
1201    async fn a_sender_nobody_names_is_delivered_anonymous_once_the_wait_is_over() {
1202        crate::db::with_session(crate::db::current_session(), async {
1203            let (shared, _events) = unregistered("npub1chat", [51u8; 32]).await;
1204            let carol = node(8);
1205            let (mesh, mut rx) = piped(&shared);
1206            tokio::time::pause();
1207            mesh.send(data(carol, "x")).await.unwrap();
1208            tokio::time::advance(ATTRIBUTION_WAIT + Duration::from_secs(1)).await;
1209            assert_eq!(said(rx.recv().await), (Some("x".into()), None));
1210            mesh.send(data(carol, "y")).await.unwrap();
1211            let y = tokio::time::timeout(Duration::from_millis(1), rx.recv()).await.expect("no second wait for the same node");
1212            assert_eq!(said(y), (Some("y".into()), None));
1213        })
1214        .await;
1215    }
1216
1217    #[tokio::test]
1218    async fn the_hold_is_bounded_and_opened_only_by_a_node_itself() {
1219        crate::db::with_session(crate::db::current_session(), async {
1220            let (shared, _events) = unregistered("npub1chat", [52u8; 32]).await;
1221            let (mesh, mut rx) = piped(&shared);
1222            // A relayed frame can't open a hold: its named sender is anyone's claim.
1223            mesh.send(MeshEvent::Data { payload: b"relayed".to_vec(), sender: node(20), direct: false }).await.unwrap();
1224            assert_eq!(said(next(&mut rx).await).0.as_deref(), Some("relayed"));
1225            // Every slot taken, the next unnamed node is delivered at once.
1226            for i in 0..HELD_NODES as u8 {
1227                mesh.send(data(node(100 + i), "held")).await.unwrap();
1228            }
1229            mesh.send(data(node(99), "overflow")).await.unwrap();
1230            assert_eq!(said(next(&mut rx).await).0.as_deref(), Some("overflow"));
1231            assert!(next(&mut rx).await.is_none(), "the rest wait");
1232        })
1233        .await;
1234    }
1235
1236    #[tokio::test]
1237    async fn a_held_node_keeps_its_first_frames_then_reports_the_rest_lost() {
1238        crate::db::with_session(crate::db::current_session(), async {
1239            let (shared, _events) = unregistered("npub1chat", [53u8; 32]).await;
1240            let dave = node(21);
1241            let (mesh, mut rx) = piped(&shared);
1242            for i in 0..HELD_FRAMES + 3 {
1243                mesh.send(data(dave, &i.to_string())).await.unwrap();
1244            }
1245            assert!(next(&mut rx).await.is_none());
1246            shared.bind(dave, "npub1dave");
1247            shared.claimed.notify_one();
1248            for i in 0..HELD_FRAMES {
1249                assert_eq!(said(next(&mut rx).await), (Some(i.to_string()), Some("npub1dave".into())));
1250            }
1251            assert!(matches!(next(&mut rx).await, Some(XdcEvent::Lagged)));
1252        })
1253        .await;
1254    }
1255
1256    #[tokio::test]
1257    async fn held_bytes_are_capped_across_the_session() {
1258        crate::db::with_session(crate::db::current_session(), async {
1259            let (shared, _events) = unregistered("npub1chat", [56u8; 32]).await;
1260            let gus = node(24);
1261            let (mesh, mut rx) = piped(&shared);
1262            mesh.send(MeshEvent::Data { payload: vec![1u8; HELD_BYTES / 2], sender: gus, direct: true }).await.unwrap();
1263            mesh.send(MeshEvent::Data { payload: vec![2u8; HELD_BYTES / 2 + 1], sender: gus, direct: true }).await.unwrap();
1264            assert!(next(&mut rx).await.is_none());
1265            shared.bind(gus, "npub1gus");
1266            shared.claimed.notify_one();
1267            match next(&mut rx).await {
1268                Some(XdcEvent::Data(f)) => assert_eq!(f.payload.len(), HELD_BYTES / 2),
1269                other => panic!("expected the frame that fit, got {other:?}"),
1270            }
1271            assert!(matches!(next(&mut rx).await, Some(XdcEvent::Lagged)), "the one that didn't is reported");
1272        })
1273        .await;
1274    }
1275
1276    #[tokio::test]
1277    async fn a_node_that_leaves_while_held_neither_arrives_nor_leaves() {
1278        crate::db::with_session(crate::db::current_session(), async {
1279            let (shared, _events) = unregistered("npub1chat", [54u8; 32]).await;
1280            let erin = node(22);
1281            let (mesh, mut rx) = piped(&shared);
1282            mesh.send(MeshEvent::NeighborUp(erin)).await.unwrap();
1283            mesh.send(data(erin, "bye")).await.unwrap();
1284            mesh.send(MeshEvent::NeighborDown(erin)).await.unwrap();
1285            assert!(next(&mut rx).await.is_none());
1286            shared.bind(erin, "npub1erin");
1287            shared.claimed.notify_one();
1288            assert_eq!(said(next(&mut rx).await), (Some("bye".into()), Some("npub1erin".into())), "its frames still count");
1289            assert!(next(&mut rx).await.is_none(), "no arrival for a node already gone, so no leave either");
1290        })
1291        .await;
1292    }
1293
1294    #[tokio::test]
1295    async fn a_contested_node_is_released_anonymous() {
1296        crate::db::with_session(crate::db::current_session(), async {
1297            let (shared, _events) = unregistered("npub1chat", [55u8; 32]).await;
1298            let frank = node(23);
1299            let (mesh, mut rx) = piped(&shared);
1300            mesh.send(data(frank, "mine")).await.unwrap();
1301            assert!(next(&mut rx).await.is_none());
1302            shared.bind(frank, "npub1frank");
1303            shared.bind(frank, "npub1mallory");
1304            shared.claimed.notify_one();
1305            assert_eq!(said(next(&mut rx).await), (Some("mine".into()), None));
1306        })
1307        .await;
1308    }
1309
1310    #[tokio::test]
1311    async fn an_app_window_gets_frames_from_an_unnamed_sender_at_once() {
1312        crate::db::with_session(crate::db::current_session(), async {
1313            let (shared, _events) = unregistered("npub1chat", [57u8; 32]).await;
1314            let shared = Arc::new(Shared { hold_unnamed: false, ..Arc::try_unwrap(shared).ok().expect("sole owner") });
1315            let (mesh, mut rx) = piped(&shared);
1316            mesh.send(data(node(25), "now")).await.unwrap();
1317            assert_eq!(said(next(&mut rx).await), (Some("now".into()), None));
1318        })
1319        .await;
1320    }
1321
1322    #[tokio::test]
1323    async fn an_advertisement_is_dated_after_our_last_departure() {
1324        crate::db::with_session(crate::db::current_session(), async {
1325            let (shared, _events) = unregistered("npub1chat", [58u8; 32]).await;
1326            let left = unix_now() + 1;
1327            last_left_of(&shared.session).lock().unwrap().insert(shared.topic, left);
1328            // The send itself fails here (no client); what matters is when it is made.
1329            let _ = advertise(&shared, "addr").await;
1330            assert!(unix_now() > left, "a same-second departure would win the tie");
1331        })
1332        .await;
1333    }
1334
1335    #[tokio::test]
1336    async fn only_a_session_that_advertised_announces_its_departure() {
1337        // Departures go out only from the live session; hold off the tests that swap it.
1338        let _swaps = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1339        crate::db::with_session(crate::db::current_session(), async {
1340            let (shared, _events) = unregistered("npub1chat", [59u8; 32]).await;
1341            let departed = || last_left_of(&shared.session).lock().unwrap().contains_key(&shared.topic);
1342            announce_left(&shared).await;
1343            assert!(!departed(), "nothing of ours to retract");
1344            let _ = advertise(&shared, "addr").await;
1345            let stale = [60u8; 32];
1346            last_left_of(&shared.session).lock().unwrap().insert(stale, unix_now() - LAST_LEFT_KEEP_SECS - 1);
1347            announce_left(&shared).await;
1348            assert!(departed());
1349            assert!(!last_left_of(&shared.session).lock().unwrap().contains_key(&stale), "a departure too old to matter goes");
1350        })
1351        .await;
1352    }
1353
1354    #[tokio::test]
1355    async fn only_a_session_that_advertised_re_advertises() {
1356        let (shared, _events) = unregistered("npub1chat", [61u8; 32]).await;
1357        readvertise_later(shared.clone());
1358        assert!(!shared.readvertise.lock().unwrap().pending, "nobody was told we are here");
1359        shared.advertised.store(true, Ordering::SeqCst);
1360        readvertise_later(shared.clone());
1361        assert!(shared.readvertise.lock().unwrap().pending);
1362    }
1363
1364    #[tokio::test]
1365    async fn a_session_that_has_left_never_advertises_again() {
1366        crate::db::with_session(crate::db::current_session(), async {
1367            let (shared, _events) = unregistered("npub1chat", [60u8; 32]).await;
1368            shared.closed.store(true, Ordering::SeqCst);
1369            assert_eq!(advertise(&shared, "addr").await, Err("the session has ended".into()));
1370        })
1371        .await;
1372    }
1373
1374    #[tokio::test]
1375    async fn the_roster_stops_attributing_past_its_cap() {
1376        let (shared, _rx) = unregistered("", [0; 32]).await;
1377        for i in 0..(ROSTER_CAP as u32 + 10) {
1378            let mut n = [0u8; 32];
1379            n[..4].copy_from_slice(&i.to_le_bytes());
1380            shared.bind(n, "npub1x");
1381        }
1382        assert_eq!(shared.roster.lock().unwrap().len(), ROSTER_CAP);
1383    }
1384}