Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 64 additions & 18 deletions crates/nfx-node/src/mesh/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -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<Instant>,
presence_due: Option<Instant>,
/// The video's address without its creator (`<namespace>:<video-id>`), as a beacon's `a`
/// ends: the fallback counts a beacon only for the peers of its own video.
video: String,
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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 {
Expand All @@ -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);
Expand Down Expand Up @@ -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<Event> = 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<Event> = self
.rooms
.values()
.filter_map(|r| self.session.connect(&r.room, at).ok())
.collect();
for ev in &events {
self.publish(ev);
}
Expand Down Expand Up @@ -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);
}
}
Expand Down
42 changes: 39 additions & 3 deletions crates/nfx-node/src/mesh/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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(),
},
);
Expand Down Expand Up @@ -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;
Expand All @@ -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));
Expand Down
3 changes: 3 additions & 0 deletions crates/nfx-proto/src/signal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
29 changes: 26 additions & 3 deletions spec/nfx-10-web.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
39 changes: 39 additions & 0 deletions web/player/src/signal-book.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading