Skip to content
Closed
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
45 changes: 44 additions & 1 deletion js/net/src/ietf/subscriber.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ import { type GroupFlags, Group as GroupMessage } from "./object.ts";
import { PublishNamespace, PublishNamespaceUpdate } from "./publish_namespace.ts";
import { RequestError, RequestOk } from "./request.ts";
import { Subscribe, SubscribeOk, Unsubscribe } from "./subscribe.ts";
import { SubscribeNamespace, SubscribeNamespaceEntry, SubscribeNamespaceEntryDone } from "./subscribe_namespace.ts";
import {
SubscribeNamespace,
SubscribeNamespaceEntry,
SubscribeNamespaceEntryDone,
SubscribeNamespaceLegacy,
} from "./subscribe_namespace.ts";
import { Subscriber } from "./subscriber.ts";
import { ALPN, Version } from "./version.ts";

Expand Down Expand Up @@ -65,6 +70,44 @@ test("every peer is asked", async () => {
expect(await nextStream(pair.client)).toBeDefined();
});

/**
* Draft-14 forbids SUBSCRIBE_NAMESPACE with an empty prefix. The default scope's head
* is that prefix, so we do not ask. An unsolicited PUBLISH_NAMESPACE still lands.
*/
test("draft-14 does not subscribe to an empty prefix", async () => {
const pair = createMockTransportPair(ALPN.DRAFT_14);
const session = new NativeSession(pair.server, Version.DRAFT_14, true);
const subscriber = new Subscriber({ session });
const announced = subscriber.announced();

expect(await nextStream(pair.client)).toBeUndefined();

const incoming = await Stream.open(pair.server, { version: Version.DRAFT_14 });
void subscriber.runPublishNamespace(
new PublishNamespace({ requestId: 0n, trackNamespace: Path.from("surprise") }),
incoming,
);
expect(await announced.next()).toMatchObject({ prefix: Path.from("surprise"), kind: "start" });
announced.close();
incoming.close();
});

/** A non-empty draft-14 prefix is still asked for. */
test("draft-14 still subscribes to a scoped prefix", async () => {
const pair = createMockTransportPair(ALPN.DRAFT_14);
const session = new NativeSession(pair.server, Version.DRAFT_14, true);
const subscriber = new Subscriber({ session });

subscriber.announced(Path.Pattern.subtree(Path.from("cam")));

const peer = await nextStream(pair.client);
if (!peer) throw new Error("no SUBSCRIBE_NAMESPACE was sent");
expect(await peer.reader.u53()).toBe(SubscribeNamespaceLegacy.id);
const size = await peer.reader.u16();
const body = await peer.reader.read(size);
expect(new TextDecoder().decode(body)).toContain("cam");
});

/**
* The other half of discovery: a peer that tells us unasked. Asking must not make us deaf
* to a PUBLISH_NAMESPACE that arrives on its own stream instead.
Expand Down
13 changes: 12 additions & 1 deletion js/net/src/ietf/subscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,8 @@ export class Subscriber {
*
* The peer is asked with SUBSCRIBE_NAMESPACE regardless of what it declared, and an
* unsolicited PUBLISH_NAMESPACE lands here too, so a peer that only tells and one
* that only answers are both discovered.
* that only answers are both discovered. Draft-14 cannot be asked for the empty
* prefix, so an unscoped subscriber only hears what the peer tells.
*
* Hidden routes (a `.`-prefixed segment below the scope's head) are left out unless
* `options.hidden` opts in. The opt-in rides the SUBSCRIBE_NAMESPACE when the peer
Expand Down Expand Up @@ -321,6 +322,16 @@ export class Subscriber {
async #runAnnounced(announced: announce.Producer, prefix: Path.Valid, hidden: boolean) {
const version = this.#session.version;

// Draft-14 makes a prefix with N = 0 a protocol violation. An unscoped interest
// is that empty prefix, so do not ask and take unsolicited PUBLISH_NAMESPACE
// instead. Stay open until the caller drops the consumer, or those announcements
// have nowhere to land.
if (version === Version.DRAFT_14 && prefix === Path.empty()) {
console.debug("skipping empty SUBSCRIBE_NAMESPACE prefix on draft-14");
await announced.closed;
return;
}

// Suffixes live on this stream, so a repeat is recognized as an update to the
// advertisement rather than a second one, which would leak the count.
const live = new Set<Path.Valid>();
Expand Down
119 changes: 117 additions & 2 deletions rs/moq-net/src/ietf/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,12 @@ where
let (goaway_handle, goaway) = crate::goaway::Handle::new(!client);

// One SUBSCRIBE_NAMESPACE per permitted prefix, like `lite::Subscriber`: the
// scope is what we may ask for, and it is not the origin's root.
let namespaces = subscribe.as_ref().map(subscribe_prefixes).unwrap_or_default();
// scope is what we may ask for, and it is not the origin's root. Draft-14
// drops an empty prefix; see `subscribe_prefixes`.
let namespaces = subscribe
.as_ref()
.map(|origin| subscribe_prefixes(origin, version))
.unwrap_or_default();

let withdrawal = crate::session::Withdrawal::default();
let withdrawing = withdrawal.clone();
Expand Down Expand Up @@ -1226,6 +1230,117 @@ mod tests {
assert_eq!(occurrences(&log, b"rootns"), 0, "asked the peer for our local root");
}

/// The control messages that reached the wire, by type id.
///
/// Decoding the framing rather than scanning for a byte: a type id is one varint
/// among many, and a substring match would find one inside a length or a payload.
fn control_message_types(log: &crate::lite::test_transport::Log, version: Version) -> Vec<u64> {
let writes = log.writes.lock().unwrap().clone();
let mut buf = crate::coding::Decoder::new(&writes, version.into());
let mut types = Vec::new();

while !buf.is_empty() {
let Ok(type_id) = buf.varint() else {
break;
};
let Ok(size) = buf.u16() else {
break;
};
if buf.slice(size as usize).is_err() {
break;
}
types.push(type_id);
}

types
}

/// Drive a draft-14 session and return what it wrote.
///
/// `scoped` asks for `cam` under a local root. Otherwise the origin is unscoped,
/// whose interest prefix is empty.
async fn draft14_subscribe_log(scoped: bool) -> crate::lite::test_transport::Log {
const VERSION: Version = Version::Draft14;

let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce();
let subscribe = if scoped {
let patterns = crate::Patterns::from(crate::Pattern::subtree("cam").unwrap());
origin.scope("rootns", &patterns).expect("scope the origin")
} else {
origin.clone()
};

let mut session = crate::lite::test_transport::ScriptedSession::new(Vec::new());
let log = session.log.clone();
let setup = Stream::open(&mut session, VERSION)
.await
.expect("open the control stream");

let (driver, _goaway, _) = start(Config {
runtime: crate::time::Clock::sim(),
session,
setup: Some(setup),
request_id_max: None,
client: true,
publish: None,
subscribe: Some(subscribe),
peer_hop: None,
cost: None,
version: VERSION,
path: None,
authority: None,
peer_setup_stream: None,
peer_declared: None,
early_unis: Vec::new(),
})
.expect("start the session");
let driver = moq_net_sim::spawn(driver);

// A scoped request is written before the peer answers, which never comes.
// An unscoped session must stay silent for the same window.
for _ in 0..ANNOUNCE_TURNS {
if control_message_types(&log, VERSION).contains(&ietf::SubscribeNamespaceLegacy::ID) {
break;
}
moq_net_sim::sleep(std::time::Duration::from_millis(1)).await;
}

assert!(!driver.is_finished(), "the session ended");
assert!(log.closes().is_empty(), "closed the session: {:?}", log.closes());

// The original handle shares the table the session is still reading.
drop(origin);
log
}

/// Draft-14 forbids SUBSCRIBE_NAMESPACE with an empty prefix. An unscoped origin's
/// interest is that prefix, so the session does not ask and takes unsolicited
/// PUBLISH_NAMESPACE instead. A scoped origin still asks for its scope.
#[moq_net_sim::test]
async fn an_unscoped_draft14_session_does_not_subscribe_to_the_root() {
const VERSION: Version = Version::Draft14;

let unscoped = draft14_subscribe_log(false).await;
let unscoped_types = control_message_types(&unscoped, VERSION);
assert!(
!unscoped_types.contains(&ietf::SubscribeNamespaceLegacy::ID),
"an unscoped origin sent SUBSCRIBE_NAMESPACE: {unscoped_types:?}"
);

let scoped = draft14_subscribe_log(true).await;
let scoped_types = control_message_types(&scoped, VERSION);
assert_eq!(
scoped_types
.iter()
.filter(|id| **id == ietf::SubscribeNamespaceLegacy::ID)
.count(),
1,
"a scoped origin must still subscribe: {scoped_types:?}"
);
assert_eq!(occurrences(&scoped, b"cam"), 1, "asked for the scope");
assert_eq!(occurrences(&scoped, b"rootns"), 0, "asked the peer for our local root");
}

/// How many scheduling turns an advertisement gets before the count is taken. Time is
/// paused in these tests, so each turn costs nothing and only runs the driver until it
/// parks again; a busy machine cannot turn a slow announce into a passing silence.
Expand Down
33 changes: 27 additions & 6 deletions rs/moq-net/src/ietf/subscriber.rs
Original file line number Diff line number Diff line change
Expand Up @@ -595,10 +595,21 @@ pub(super) struct Subscriber<S: crate::transport::poll::Session> {
/// our namespace -- a peer outside it has never heard of our root, so a rooted
/// subscriber asks for its scope and mounts the replies under the root.
///
/// Asked unconditionally: a peer with nothing to advertise answers with an empty set,
/// which costs one stream.
pub(super) fn subscribe_prefixes(origin: &origin::Producer) -> Vec<PathOwned> {
crate::model::interest_prefixes(&origin.allowed())
/// A peer with nothing to advertise answers with an empty set, which costs one stream.
///
/// Draft-14 makes a prefix with no tuple fields (N = 0) a protocol violation. An
/// unscoped origin's interest is that empty prefix, so it is left out and the session
/// takes the peer's unsolicited PUBLISH_NAMESPACE instead.
pub(super) fn subscribe_prefixes(origin: &origin::Producer, version: Version) -> Vec<PathOwned> {
let mut prefixes = crate::model::interest_prefixes(&origin.allowed());
if version == Version::Draft14 {
let skipped = prefixes.iter().any(|prefix| prefix.is_empty());
if skipped {
tracing::debug!("skipping empty SUBSCRIBE_NAMESPACE prefix on draft-14");
}
prefixes.retain(|prefix| !prefix.is_empty());
}
prefixes
}

/// Resolve the subscription a data stream belongs to.
Expand Down Expand Up @@ -840,6 +851,14 @@ where
mut stream: Stream<T, Version>,
prefix: PathOwned,
) -> Result<(), Error> {
// Draft-14 makes a prefix with N = 0 a protocol violation. `subscribe_prefixes`
// already drops that root; this is the send path, so a direct caller cannot
// put it on the wire either. The peer's unsolicited PUBLISH_NAMESPACE covers it.
if self.version == Version::Draft14 && prefix.is_empty() {
tracing::debug!("skipping empty SUBSCRIBE_NAMESPACE prefix on draft-14");
return Ok(());
}

// A peer that sent GOAWAY told us to stop opening requests on this session,
// announce-interest included (draft-19 sect 10.4).
if self.going_away.is_set() {
Expand Down Expand Up @@ -4256,7 +4275,7 @@ mod tests {
Default::default(),
);

let mut namespaces = subscribe_prefixes(&subscriber.origin);
let mut namespaces = subscribe_prefixes(&subscriber.origin, Version::Draft16);
assert_eq!(
namespaces,
vec![crate::Path::new("cam").to_owned()],
Expand Down Expand Up @@ -4336,7 +4355,9 @@ mod tests {
Default::default(),
);

let prefix = subscribe_prefixes(&subscriber.origin).pop().expect("one prefix");
let prefix = subscribe_prefixes(&subscriber.origin, VERSION)
.pop()
.expect("one prefix");
let stream = Stream::open(&mut session.clone(), VERSION).await.unwrap();
// Parks on the read after the scripted NAMESPACE is consumed.
let mut run = std::pin::pin!(subscriber.run_subscribe_namespace(stream, prefix));
Expand Down
Loading