1use 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
15const QUEUE: usize = 256;
17const ROSTER_CAP: usize = 256;
19const 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);
24pub const ATTRIBUTION_WAIT: Duration = Duration::from_secs(10);
28const HELD_FRAMES: usize = 64;
30const HELD_NODES: usize = 32;
31const HELD_BYTES: usize = 4 * 1024 * 1024;
32
33#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct XdcPeer {
38 pub node: [u8; NODE_KEY_LEN],
39 pub npub: Option<String>,
40}
41
42#[derive(Debug, Clone)]
44pub struct XdcFrame {
45 pub payload: Vec<u8>,
46 pub from: XdcPeer,
47 pub direct: bool,
51}
52
53impl XdcFrame {
54 pub fn text(&self) -> Option<&str> {
56 std::str::from_utf8(&self.payload).ok()
57 }
58
59 pub fn json<T: serde::de::DeserializeOwned>(&self) -> Option<T> {
62 serde_json::from_slice(&self.payload).ok()
63 }
64
65 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 PeerJoined(XdcPeer),
81 PeerLeft(XdcPeer),
83 Lagged,
86}
87
88#[derive(Clone)]
91enum Binding {
92 Npub(String),
93 Contested,
94}
95
96struct Shared {
98 topic: [u8; 32],
99 topic_b32: String,
101 chat_id: String,
102 session: Arc<crate::db::Session>,
105 mesh: Arc<Mesh>,
107 roster: Mutex<HashMap<[u8; NODE_KEY_LEN], Binding>>,
108 present: Mutex<HashSet<[u8; NODE_KEY_LEN]>>,
111 events: Mutex<Option<mpsc::Sender<XdcEvent>>>,
114 closed: AtomicBool,
116 done: watch::Sender<bool>,
118 readvertise: Mutex<ReadvertiseState>,
119 claimed: tokio::sync::Notify,
121 hold_unnamed: bool,
123 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 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#[derive(Default)]
176struct Joined {
177 map: Mutex<HashMap<[u8; 32], Arc<Shared>>>,
178 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
192fn 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
208pub fn any_live() -> bool {
210 joined_of(&crate::db::live_session()).map.lock().unwrap().values().any(|s| !s.is_closed())
211}
212
213pub fn is_joined(topic: &str) -> bool {
215 wire::decode_topic(topic).map(|t| live_session(&t).is_some()).unwrap_or(false)
216}
217
218pub fn allow_outside_transport(allow: bool) {
221 crate::transport::realtime::allow_always(allow);
222}
223
224pub fn allow_outside_tor(allow: bool) {
226 allow_outside_transport(allow);
227}
228
229fn 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
237pub struct XdcSession {
239 shared: Arc<Shared>,
240 rx: mpsc::Receiver<XdcEvent>,
241 left: bool,
242}
243
244#[derive(Debug, Clone)]
246pub struct JoinOptions {
247 pub hold_unnamed: bool,
251 pub advertise: bool,
255 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
267pub async fn join(chat_id: &str, topic: &str) -> Result<XdcSession, String> {
271 join_with(chat_id, topic, JoinOptions::default()).await
272}
273
274pub async fn join_with(chat_id: &str, topic: &str, options: JoinOptions) -> Result<XdcSession, String> {
276 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 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 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 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 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(®istry, &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 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
369struct 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
386async 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#[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 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 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 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
527fn 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 pub fn topic(&self) -> &str {
562 &self.shared.topic_b32
563 }
564
565 pub fn chat_id(&self) -> &str {
567 &self.shared.chat_id
568 }
569
570 pub async fn send(&self, payload: impl Into<Vec<u8>>) -> Result<(), String> {
573 self.sender().send(payload).await
574 }
575
576 pub async fn recv(&mut self) -> Option<XdcEvent> {
578 self.rx.recv().await
579 }
580
581 pub fn npub_of(&self, node: &[u8; NODE_KEY_LEN]) -> Option<String> {
583 self.shared.npub(node)
584 }
585
586 pub fn mesh(&self) -> Arc<Mesh> {
588 self.shared.mesh.clone()
589 }
590
591 pub async fn neighbor_count(&self) -> usize {
593 self.shared.mesh.neighbor_count(&self.shared.topic).await
594 }
595
596 pub fn sender(&self) -> XdcSender {
599 XdcSender { shared: self.shared.clone() }
600 }
601
602 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 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 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 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
637struct Finish {
642 shared: Arc<Shared>,
643 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 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
676async 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
688async 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
701struct LastLeft;
703
704const 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
716async 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 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
750pub async fn leave_all(deadline: Duration) {
757 leave_every(deadline, true).await;
758}
759
760pub 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 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#[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 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 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
842pub 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 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 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 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 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 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 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 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 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 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 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 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(®istry, &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 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 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 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 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 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}