diff --git a/crates/nfx-node/src/mesh/mod.rs b/crates/nfx-node/src/mesh/mod.rs index f55b76a1..0c1d84e1 100644 --- a/crates/nfx-node/src/mesh/mod.rs +++ b/crates/nfx-node/src/mesh/mod.rs @@ -146,9 +146,11 @@ const MAX_LOCAL_CANDIDATES: usize = 7; /// How often a room whose rendition is not all in the store is checked again, so peers hear /// of segments that arrived (a pulled or fetched video fills in), as the bridge does. const REFRESH_EVERY: Duration = Duration::from_secs(10); -/// A room's presence is sent again, out of turn, at most this often: when a new peer whose -/// key is lower (so it is the one to offer) appears, so it need not wait for the next round. -const REANNOUNCE_EVERY: Duration = Duration::from_secs(5); +/// No two of a room's `connect`s go out closer than this (NFX-10 §6.6): NFX-04 §2 admits one +/// presence per 10 s per key, room and type. One due sooner waits for the gap and is never +/// dropped, so a node answers newcomers at most once per gap, and one answer deferred serves +/// every newcomer seen meanwhile. +pub const PRESENCE_MIN_GAP: Duration = Duration::from_secs(signal::PRESENCE_MIN_GAP); /// STUN from Nostr: the sources of names held at most (a beacon per signer and video). Keys /// are free: past it, a new source is ignored until one expires. A creator's beacon of its /// own video is always kept: there is at most one per video watched. @@ -806,6 +808,24 @@ impl Link { } } +impl RoomState { + /// Whether this room's `connect` may go to every relay at `now` (counted as sent if so): + /// inside [`PRESENCE_MIN_GAP`] of the last one it is deferred until the gap has passed. + fn presence_now(&mut self, now: Instant) -> bool { + match self.last_connect { + Some(t) if now < t + PRESENCE_MIN_GAP => { + self.presence_due.get_or_insert(t + PRESENCE_MIN_GAP); + false + } + _ => { + self.last_connect = Some(now); + self.presence_due = None; + true + } + } + } +} + /// A joined room. struct RoomState { room: Room, @@ -814,8 +834,10 @@ struct RoomState { seen: SeenIds, limiter: SenderLimiter, backoff: OfferBackoff, - /// When this room's presence may next go out of turn ([`REANNOUNCE_EVERY`]). - reannounce_at: Instant, + /// When this room's `connect` last went to every relay, and the one deferred until + /// [`PRESENCE_MIN_GAP`] has passed. + last_connect: Option, + presence_due: Option, /// The video's address without its creator (`:`), as a beacon's `a` /// ends: the fallback counts a beacon only for the peers of its own video. video: String, @@ -929,6 +951,11 @@ impl State { .min(self.next_sub_check) .min(self.stun.next_round) .min(self.next_presence); + for r in self.rooms.values() { + if let Some(d) = r.presence_due { + wake = wake.min(d); + } + } for (_, _, at) in self.stun.pending.values() { wake = wake.min(*at); } @@ -1137,7 +1164,8 @@ impl State { seen: SeenIds::default(), limiter: SenderLimiter::default(), backoff: OfferBackoff::default(), - reannounce_at: Instant::now(), + last_connect: None, + presence_due: None, video: spec.video.clone(), }); r.swarm = Swarm { @@ -1164,8 +1192,10 @@ impl State { self.resubscribe().await; self.resubscribe_stun().await; let now = unix_now(); + let at = Instant::now(); for key in joined { - if let Some(r) = self.rooms.get(&key) + if let Some(r) = self.rooms.get_mut(&key) + && r.presence_now(at) && let Ok(ev) = self.session.connect(&r.room, now) { self.publish(&ev); @@ -1606,17 +1636,26 @@ impl State { l.conn.dead = true; } } - if self.gathered && now >= self.next_presence { + let round = self.gathered && now >= self.next_presence; + if round { self.next_presence = now + Duration::from_secs(signal::PRESENCE_INTERVAL); + } + if self.gathered { + // The round's presence, and any deferred inside PRESENCE_MIN_GAP that is now due. let at = unix_now(); + let mut events: Vec = Vec::new(); for r in self.rooms.values_mut() { - r.presence.prune(at); + if round { + r.presence.prune(at); + } + let wanted = round || r.presence_due.is_some_and(|d| d <= now); + if wanted + && r.presence_now(now) + && let Ok(ev) = self.session.connect(&r.room, at) + { + events.push(ev); + } } - let events: Vec = self - .rooms - .values() - .filter_map(|r| self.session.connect(&r.room, at).ok()) - .collect(); for ev in &events { self.publish(ev); } @@ -1758,11 +1797,18 @@ impl State { } if signal::offers_to(&me, &r.sender) { self.maybe_offer(&key, &r.sender); - } else if new && Instant::now() >= room.reannounce_at { + } else if new + && self.has_room(&key) + && self.negotiating(&key) < NEGOTIATIONS_PER_ROOM + { // A newcomer that is to offer heard nothing of this node yet (relays keep - // no ephemeral event): tell it now rather than at the next round. - room.reannounce_at = Instant::now() + REANNOUNCE_EVERY; - if let Ok(ev) = self.session.connect(&room.room, now) { + // no ephemeral event): tell it now rather than at the next round, or when + // PRESENCE_MIN_GAP has passed (NFX-10 §6.6). + let at = Instant::now(); + if let Some(room) = self.rooms.get_mut(&key) + && room.presence_now(at) + && let Ok(ev) = self.session.connect(&room.room, now) + { self.publish(&ev); } } diff --git a/crates/nfx-node/src/mesh/tests.rs b/crates/nfx-node/src/mesh/tests.rs index 000e155a..5f30fb94 100644 --- a/crates/nfx-node/src/mesh/tests.rs +++ b/crates/nfx-node/src/mesh/tests.rs @@ -19,7 +19,7 @@ use tokio::net::UdpSocket; use super::book::{OfferBackoff, PENDING_OFFERS_PER_ROOM, PresenceBook, SeenIds, SenderLimiter}; use super::{ Control, FAILURES_KEPT, FailStage, LinkFailure, MAX_NAMED, MAX_PEERS_PER_ROOM, MeshStatus, - NAMED_PER_KEY, NostrStun, RoomState, State, Stun, StunFallback, + NAMED_PER_KEY, NostrStun, PRESENCE_MIN_GAP, RoomState, State, Stun, StunFallback, }; use crate::nostr::to_nostr; use crate::rtc_serve::{Swarm, Uploader}; @@ -79,7 +79,8 @@ async fn state(max_peers: usize) -> State { seen: SeenIds::default(), limiter: SenderLimiter::default(), backoff: OfferBackoff::default(), - reannounce_at: now, + last_connect: None, + presence_due: None, video: "nfx:mainnet:1:salt-flats-dusk".into(), }, ); @@ -134,6 +135,32 @@ fn offer_from(peer: &Session, at: u64, nonce: u8) -> Event { .unwrap() } +#[tokio::test] +async fn presence_keeps_10_s_apart_and_one_due_sooner_waits() { + let mut s = state(16).await; + let r = s.rooms.get_mut(room().pubkey()).unwrap(); + let t0 = Instant::now(); + assert!(r.presence_now(t0), "the first goes at once"); + assert!( + !r.presence_now(t0 + Duration::from_secs(4)), + "4 s later it waits" + ); + assert_eq!(r.presence_due, Some(t0 + PRESENCE_MIN_GAP)); + assert!( + !r.presence_now(t0 + Duration::from_secs(7)), + "one deferred serves the next" + ); + assert_eq!( + r.presence_due, + Some(t0 + PRESENCE_MIN_GAP), + "and is not pushed back" + ); + assert!(r.presence_now(t0 + PRESENCE_MIN_GAP), "at the gap it goes"); + assert_eq!(r.presence_due, None); + assert_eq!(r.last_connect, Some(t0 + PRESENCE_MIN_GAP)); + assert!(PRESENCE_MIN_GAP >= Duration::from_secs(10), "NFX-04 §2"); +} + #[tokio::test] async fn the_lower_key_offers_and_its_offer_stands() { let mut s = state(16).await; @@ -158,7 +185,16 @@ async fn the_lower_key_offers_and_its_offer_stands() { assert_eq!(s.sent.len(), sent + 1); assert_eq!(tag(s.sent.last().unwrap(), "t"), Some("connect")); feed(&mut s, &lo[1].connect(&room(), now).unwrap()); - assert_eq!(s.sent.len(), sent + 1, "at most once per 5 s"); + assert_eq!( + s.sent.len(), + sent + 1, + "never two presences within 10 s (NFX-04 §2)" + ); + let r = s.rooms.get(room().pubkey()).unwrap(); + let (Some(last), Some(due)) = (r.last_connect, r.presence_due) else { + panic!("the second newcomer's presence is deferred, not dropped") + }; + assert_eq!(due, last + PRESENCE_MIN_GAP); // Glare: the higher key offers while ours is pending. Ours (the lower key's) stands. feed(&mut s, &offer_from(&hi[0], now, 1)); diff --git a/crates/nfx-proto/src/signal.rs b/crates/nfx-proto/src/signal.rs index 9169865e..654d344d 100644 --- a/crates/nfx-proto/src/signal.rs +++ b/crates/nfx-proto/src/signal.rs @@ -30,6 +30,9 @@ pub const ROOM_LABEL: &str = "nfx/1/web/room"; pub const PRESENCE_TTL: u64 = 90; /// How often a session repeats its presence, in seconds. pub const PRESENCE_INTERVAL: u64 = 30; +/// The least time between two of a session's `connect`s in one room, in seconds (NFX-10 +/// §6.6): NFX-04 §2 admits one presence per 10 s per key, room and type. +pub const PRESENCE_MIN_GAP: u64 = 10; /// Oldest `created_at` accepted, in seconds before `now`. pub const MAX_AGE: u64 = 60; /// Newest `created_at` accepted, in seconds after `now`. diff --git a/spec/nfx-10-web.md b/spec/nfx-10-web.md index c3f3840b..568720d1 100644 --- a/spec/nfx-10-web.md +++ b/spec/nfx-10-web.md @@ -560,9 +560,13 @@ Every event is kind **25050** (ephemeral). `t` tells the four types apart: - `i` is the protocol identifier, exactly `nfx-mesh/1`; `y` is the application, `nfx`. - Offer and answer content is **NIP-44 v2**, from the sender's session key to the receiver's (the `p`), of the complete SDP text (`RTCSessionDescription.sdp`, first line - `v=0`). Peers wait for ICE gathering to finish (at most 5 s) and send one SDP that - carries every candidate. NIP-DC's `route` (trickle candidates) is not sent in - `nfx-mesh/1`, and readers ignore it. The content is at most **32768 bytes**. + `v=0`). Peers send one SDP that carries the candidates they gathered. They wait for ICE + gathering to finish, at most 5 s, and MAY stop 300 ms after the first server-reflexive + candidate: the mapping is known then, other servers' answers to the same probe arrive + within a round trip of it, and one STUN server that never answers no longer holds every + connection for the whole 5 s. A native client MAY gather once and put the same candidates + in every SDP. NIP-DC's `route` (trickle candidates) is not sent in `nfx-mesh/1`, and + readers ignore it. The content is at most **32768 bytes**. - Tags are written in the order shown; readers do not depend on order, and ignore tags they do not know. @@ -644,6 +648,17 @@ over 70 KiB (UTF-8) dropped unparsed. - **Presence.** A session sends `connect` when it joins a room and every 30 s after, with `expiration` = `created_at` + 90, and `disconnect` when it leaves (best effort). +- **Telling a newcomer.** Relays keep no ephemeral event, so a session that joins hears of + a member only at the member's next presence, up to 30 s away, and the session with the + lower key is the one to offer (below). So on a valid `connect` from a peer it held no + presence for, whose key is lower, and with room for another peer, a session sends its + own `connect` again, out of turn: a node each time, a page at most once per 30 s per + room, since most members of a busy room are pages. +- **Spacing.** A session never sends two `connect`s in one room less than 10 s apart, out + of turn or not, as NFX-04 §2 admits one presence per 10 s per key, room and type. One due + sooner is sent when the 10 s have passed, not dropped, and one such serves every + newcomer seen meanwhile. A `connect` sent only to a relay that has just been connected, + which has none of the session's, is not counted. - **Who offers (glare).** On a valid `connect` from a peer it is neither connected nor connecting to, and with room for another peer, the session whose key is lower (comparing the 64-character lowercase hex strings) sends an offer; the other waits for @@ -844,3 +859,11 @@ ICE, and a NAT test. HTTPS" now hold only for a player that still asks origins for segments. A player that asks peers only SHOULD say when it waits for a peer and when the browser's WebRTC gathers no UDP candidate. Playlists, init segments and the hash list still come from an origin. +- Draft 2026-11-27 (spec review of main 93f52f4): §6.6 says how a member tells a newcomer + it is there (was: nothing, so a newcomer whose key is lower waited for the member's next + presence, up to 30 s): on a newcomer's `connect`, a member whose key is higher sends its + own out of turn, a page at most once per 30 s per room. No two `connect`s of a session in + one room go less than 10 s apart, as NFX-04 §2 admits (nfxd's 5 s was under it); one due + sooner waits. §6.2 lets a client stop gathering 300 ms after its first server-reflexive + candidate, so a STUN server that never answers no longer costs 5 s per side, and lets a + native client reuse one gathering. Nothing on the wire changes. diff --git a/web/player/src/signal-book.ts b/web/player/src/signal-book.ts index ec53a1b8..d0a80603 100644 --- a/web/player/src/signal-book.ts +++ b/web/player/src/signal-book.ts @@ -89,6 +89,45 @@ export class PresenceBook { } } +/** + * No two of a session's `connect`s in one room go out closer than this: NFX-04 §2 admits one + * presence per 10 s per key, room and type (NFX-10 §6.6). One due sooner waits for the gap. + */ +export const PRESENCE_MIN_GAP_MS = 10_000; +/** How often a page sends its presence out of turn for newcomers, at most, per room (NFX-10 §6.6). */ +export const ANSWER_NEWCOMERS_EVERY_MS = 30_000; +/** + * When a session's `connect` may next go out in one room (NFX-10 §6.6). No two go closer than + * `gapMs` (NFX-04 §2 admits one presence per 10 s per key, room and type): one due sooner + * waits, and is not dropped. Newcomers are answered out of turn at most once per + * `answerEveryMs`. Times are milliseconds. + */ +export class PresenceClock { + #last = Number.NEGATIVE_INFINITY; + #lastAnswer = Number.NEGATIVE_INFINITY; + constructor( + readonly gapMs: number, + readonly answerEveryMs: number, + ) {} + + /** How long a `connect` wanted at `now` must wait: 0 when it may go now. */ + wait(now: number): number { + return Math.max(0, this.#last + this.gapMs - now); + } + + /** A `connect` went to every relay at `now`. */ + sent(now: number): void { + this.#last = now; + } + + /** Whether a newcomer seen at `now` gets our presence out of turn; true counts as that answer. */ + answer(now: number): boolean { + if (now - this.#lastAnswer < this.answerEveryMs) return false; + this.#lastAnswer = now; + return true; + } +} + /** * The ids of the last `max` events taken, so each is taken once whichever relays deliver it. * Only ids of events that verified are added: a relay that sends a forged event under a real diff --git a/web/player/src/signal-nostr.ts b/web/player/src/signal-nostr.ts index 3b8ceed8..27df4063 100644 --- a/web/player/src/signal-nostr.ts +++ b/web/player/src/signal-nostr.ts @@ -33,9 +33,12 @@ import type { RelayStunBook } from './relay-stun'; import { filterRemoteSdpCounted } from './remote-sdp'; import type { StunFallbackBook } from './stun-fallback'; import { + ANSWER_NEWCOMERS_EVERY_MS, LIMITS, OfferBackoff, PresenceBook, + PresenceClock, + PRESENCE_MIN_GAP_MS, SeenIds, SenderLimiter, eventHead, @@ -46,7 +49,7 @@ import { overBytes, } from './signal-book'; -export { LIMITS, PresenceBook, SeenIds, SenderLimiter, eventId, nowSeconds, offersTo }; +export { ANSWER_NEWCOMERS_EVERY_MS, LIMITS, PRESENCE_MIN_GAP_MS, PresenceBook, PresenceClock, SeenIds, SenderLimiter, eventId, nowSeconds, offersTo }; /** NFX-10 §6 constants the library uses (nfx-proto holds the same). */ export const PRESENCE_INTERVAL_MS = 30_000; @@ -465,6 +468,9 @@ export class RoomClient { #me = ''; #unsubscribe: (() => void) | null = null; #timer: ReturnType | null = null; + /** When our `connect` may next go out (NFX-10 §6.6), and the one deferred until then. */ + readonly #clock = new PresenceClock(PRESENCE_MIN_GAP_MS, ANSWER_NEWCOMERS_EVERY_MS); + #due: ReturnType | null = null; #started = false; #destroyed = false; @@ -507,10 +513,10 @@ export class RoomClient { (json) => this.#onEvent(json), (send) => this.#announce(send), ); - this.#announce(); + this.#announceAll(); this.#timer = setInterval(() => { this.#presence.prune(nowSeconds()); - this.#announce(); + this.#announceAll(); }, PRESENCE_INTERVAL_MS); this.#s.log(`mesh: nostr room ${room.slice(0, 12)}… for ${this.#ctx.streamSwarmId}`); } @@ -526,6 +532,39 @@ export class RoomClient { else this.#publish(ev); } + /** + * Our presence to every relay, now, or once `PRESENCE_MIN_GAP_MS` has passed since the last + * one: a presence due sooner is deferred, never dropped, and one deferred serves every + * reason for it met meanwhile. + */ + #announceAll(): void { + if (this.#destroyed || this.#room === null) return; + const wait = this.#clock.wait(Date.now()); + if (wait > 0) { + this.#due ??= setTimeout(() => { + this.#due = null; + this.#announceAll(); + }, wait); + return; + } + if (this.#due !== null) clearTimeout(this.#due); + this.#due = null; + this.#clock.sent(Date.now()); + this.#announce(); + } + + /** + * A newcomer is to offer (its key is lower) and heard nothing of this session yet: relays + * keep no ephemeral event, so without this it waits for our next round, up to 30 s. Our + * presence goes out of turn, at most once per `ANSWER_NEWCOMERS_EVERY_MS`, and only with + * room for another peer (NFX-10 §6.6). + */ + #answerNewcomer(peer: string): void { + if (offersTo(this.#me, peer) || this.#negotiating.has(peer)) return; + if (this.#negotiating.size >= LIMITS.negotiationsPerRoom || !this.#ctx.shouldGenerateOffers()) return; + if (this.#clock.answer(Date.now())) this.#announceAll(); + } + #publish(eventJson: string): void { if (this.#s.pool.publish(eventJson) > 0) this.#s.stats.sent += 1; } @@ -548,9 +587,14 @@ export class RoomClient { this.#s.stats.received += 1; const now = nowSeconds(); switch (r.type) { - case 'connect': - if (this.#presence.add(r.sender, r.created_at, r.expiration ?? 0, now)) this.#maybeOffer(r.sender); + case 'connect': { + const newcomer = !this.#presence.present(r.sender, now); + if (this.#presence.add(r.sender, r.created_at, r.expiration ?? 0, now)) { + this.#maybeOffer(r.sender); + if (newcomer) this.#answerNewcomer(r.sender); + } break; + } case 'disconnect': this.#presence.add(r.sender, r.created_at, null, now); this.#s.stunFallback?.forget(r.sender); @@ -857,6 +901,8 @@ export class RoomClient { this.#destroyed = true; if (this.#timer !== null) clearInterval(this.#timer); this.#timer = null; + if (this.#due !== null) clearTimeout(this.#due); + this.#due = null; this.#unsubscribe?.(); this.#unsubscribe = null; for (const n of this.#negotiating.values()) { diff --git a/web/player/unit.ts b/web/player/unit.ts index 6a57b047..0b29ee6d 100644 --- a/web/player/unit.ts +++ b/web/player/unit.ts @@ -107,6 +107,8 @@ import { LIMITS, OfferBackoff, PresenceBook, + PRESENCE_MIN_GAP_MS, + PresenceClock, SeenIds, SenderLimiter, eventHead, @@ -918,6 +920,21 @@ throws('nine relays', () => checkRelays(Array.from({ length: 9 }, (_, i) => `wss eq('the lower key offers', [offersTo(lo, hi), offersTo(hi, lo)], [true, false]); eq('not to itself', offersTo(lo, lo), false); } +{ + // NFX-10 §6.6: no two connects of a room closer than 10 s (NFX-04 §2), one due sooner waits; + // newcomers answered out of turn at most once per 30 s. + const c = new PresenceClock(10_000, 30_000); + eq('the first connect goes at once', c.wait(1_000), 0); + c.sent(1_000); + eq('one wanted 4 s later waits the other 6 s', c.wait(5_000), 6_000); + eq('at the gap it may go', c.wait(11_000), 0); + eq('the first newcomer is answered', c.answer(5_000), true); + eq('another 29 s later is not', c.answer(34_000), false); + eq('one 30 s later is', c.answer(35_000), true); + c.sent(40_000); + eq('a round 2 s after an out-of-turn connect waits 8 s', c.wait(42_000), 8_000); + eq('NFX-04 §2: the gap is at least 10 s', PRESENCE_MIN_GAP_MS >= 10_000, true); +} { // Presence: newest by created_at wins; a disconnect wins a same-second tie; expiry; bound. const p = new PresenceBook(2);