Skip to main content

moq_net/lite/
setup.rs

1//! The lite-05+ SETUP message: each endpoint advertises its capabilities once, as
2//! the sole message on a unidirectional Setup Stream, then closes it.
3
4use crate::coding::*;
5
6use super::{Message, Parameters, Version};
7
8/// Setup Parameter id for the Probe capability level.
9const PARAM_PROBE: u64 = 0x1;
10/// Setup Parameter id for the request Path (client-only, URI-less transports).
11const PARAM_PATH: u64 = 0x2;
12/// Setup Parameter id for the client's intended [`Role`] (client-only).
13const PARAM_ROLE: u64 = 0x3;
14/// Setup Parameter id for the link cost the sender assigns to this connection.
15const PARAM_COST: u64 = 0x4;
16/// Setup Parameter id for the endpoint's Hop ID before lite-07, and its Node ID from lite-07.
17const PARAM_HOP: u64 = 0x5;
18/// Setup Parameter id for the sender's implementation, as `name/version` product tokens.
19const PARAM_IMPLEMENTATION: u64 = 0x6;
20/// Setup Parameter id for the client's connection credential (client-only, lite-07+).
21const PARAM_TOKEN: u64 = 0x7;
22/// Setup Parameter id offering the `ietf` extension (draft-lcurley-moq-ietf): "IETF" in ASCII.
23const PARAM_IETF: u64 = 0x4945_5446;
24
25/// The cost of crossing a link that neither end priced.
26///
27/// One, so a mesh that configures no costs accumulates a route cost equal to the
28/// hop count and ranks routes exactly as pre-lite-06 shortest-path routing did. Before
29/// lite-07, pricing a link at 0 makes it free (a sibling in the same datacenter); pricing
30/// it higher makes it a last resort (a metered backbone).
31pub const DEFAULT_COST: u64 = 1;
32
33/// The probe capability an endpoint advertises in SETUP.
34///
35/// Monotonic: a higher level implies every lower one. An unknown (future) value
36/// decodes as the highest level we understand, so a peer that gains a new level is
37/// treated as at least [`Increase`](Self::Increase).
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
39pub enum ProbeLevel {
40	/// No probing. Equivalent to omitting the parameter.
41	#[default]
42	None,
43	/// The publisher can measure and periodically report at least one of the PROBE
44	/// metrics: its estimated bitrate, its round-trip time, or both. Either may be
45	/// unknown in any given report, since the two are independent on the wire.
46	Report,
47	/// The publisher can additionally pad the connection (or send redundant data).
48	Increase,
49}
50
51impl ProbeLevel {
52	/// The level to advertise for `session`, from what its transport actually exposes.
53	///
54	/// [`Report`](Self::Report) claims the publisher can measure and periodically
55	/// report. A transport that exposes neither a send-rate estimate nor an RTT can
56	/// honour neither, and the draft requires such a publisher to reset any Probe
57	/// Stream a subscriber opens. Advertising [`None`](Self::None) instead stops the
58	/// subscriber opening one at all.
59	///
60	/// Both metrics are sampled rather than declared, so this only works for a
61	/// transport whose figures exist by the time the session starts. QUIC and TCP
62	/// both qualify: their RTT comes from the handshake, which has already happened.
63	///
64	/// [`Increase`](Self::Increase) additionally needs a sender, a transport
65	/// [`Probe`](crate::transport::Probe), since the session probes to the peer's
66	/// target through it. Without one a peer's target could never be honored.
67	#[cfg(feature = "async")]
68	pub fn detect(session: &crate::driver::Transport) -> Self {
69		use crate::transport::Metrics as _;
70		use crate::transport::poll::Session as _;
71		let metrics = session.metrics();
72		if metrics.estimated_send_rate().is_none() && metrics.rtt().is_none() {
73			return Self::None;
74		}
75		match session.probe().is_some() {
76			true => Self::Increase,
77			false => Self::Report,
78		}
79	}
80
81	/// Map the wire value to a level, saturating unknown values to [`Increase`](Self::Increase).
82	fn from_code(code: u64) -> Self {
83		match code {
84			0 => Self::None,
85			1 => Self::Report,
86			_ => Self::Increase,
87		}
88	}
89
90	/// The wire value for this level.
91	fn to_code(self) -> u64 {
92		match self {
93			Self::None => 0,
94			Self::Report => 1,
95			Self::Increase => 2,
96		}
97	}
98}
99
100/// The single direction a client intends to use the session for.
101///
102/// A client advertises this in its SETUP so the server can reject a token that lacks
103/// the matching scope during the handshake, instead of accepting a connection that
104/// then silently carries no media (a subscribe-only token used to publish, or vice
105/// versa). It only ever narrows what the server grants, so it is not a security
106/// boundary: the server still enforces the token's scope regardless.
107///
108/// A session is bidirectional by default, which the wire says by omitting the
109/// parameter. `Option<Role>` mirrors that: `None` is the default, and it's also what
110/// a client that predates the parameter decodes to.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112#[non_exhaustive]
113pub enum Role {
114	/// The client will publish tracks (ingest); the server must consume.
115	Publisher,
116	/// The client will subscribe to tracks (egress); the server must publish.
117	Subscriber,
118}
119
120impl Role {
121	/// Map the wire value to a role. `0` and any unrecognized future value are `None`
122	/// (bidirectional): the draft requires a receiver that does not recognize the value
123	/// to treat it as both directions, so a newer client can't break an older server (it
124	/// just loses the early reject and defers fully to the token's scope).
125	fn from_code(code: u64) -> Option<Self> {
126		match code {
127			1 => Some(Role::Publisher),
128			2 => Some(Role::Subscriber),
129			_ => None,
130		}
131	}
132
133	/// The wire value for this role.
134	fn to_code(self) -> u64 {
135		match self {
136			Role::Publisher => 1,
137			Role::Subscriber => 2,
138		}
139	}
140
141	/// Derive the advertised role from which origins a client wired up: publish-only is
142	/// a [`Publisher`](Role::Publisher), consume-only a [`Subscriber`](Role::Subscriber),
143	/// and both (or neither) advertises nothing. This keeps the advertised role from
144	/// drifting away from what the session actually does.
145	pub(crate) fn from_origins(publishes: bool, consumes: bool) -> Option<Self> {
146		match (publishes, consumes) {
147			(true, false) => Some(Role::Publisher),
148			(false, true) => Some(Role::Subscriber),
149			_ => None,
150		}
151	}
152
153	/// Lowercase label for this role (`"publisher"` / `"subscriber"`).
154	pub fn as_str(self) -> &'static str {
155		match self {
156			Role::Publisher => "publisher",
157			Role::Subscriber => "subscriber",
158		}
159	}
160}
161
162impl std::fmt::Display for Role {
163	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164		f.write_str(self.as_str())
165	}
166}
167
168/// The SETUP message, sent once per endpoint on the unidirectional Setup Stream.
169///
170/// lite-05+ only. The two endpoints' SETUP messages are independent: neither side
171/// blocks on the peer's before opening other streams, but a stream whose encoding
172/// depends on a negotiated capability (e.g. PROBE) must wait for it.
173#[derive(Clone, Default, PartialEq, Eq)]
174pub struct Setup {
175	/// The probe capability this endpoint supports. [`ProbeLevel::None`] when absent.
176	pub probe: ProbeLevel,
177	/// The request path, for transports that carry no request URI (native QUIC,
178	/// qmux over TCP/TLS, unix sockets), with `?` and the URI query appended when
179	/// there is one. Sent only by the client; a server never sends one and a relay
180	/// never forwards it. `None` when the transport URI carries the target, where it would
181	/// be a protocol violation, even empty. Otherwise an empty path selects the root, like
182	/// `None`.
183	pub path: Option<String>,
184	/// The single direction the client intends to use, or `None` for a bidirectional
185	/// session. `None` is sent as the absence of the parameter, which is also how a
186	/// client that predates the parameter decodes.
187	pub role: Option<Role>,
188	/// What subscribing from this endpoint costs (lite-06+), added by the peer to the
189	/// route cost of every announcement we forward it.
190	///
191	/// Directional: it prices the sender's own egress, so both ends declare their own
192	/// and the two need not match. `None` means the default cost of 1. Lite-07 refuses 0
193	/// both ways: a free link would leave a route as close as the one it came from.
194	pub cost: Option<u64>,
195	/// This endpoint's Hop ID, the identity forwarded announcements name it by.
196	/// The peer uses it to serve this endpoint's subscriptions from a route that
197	/// does not flow through it (the same split horizon the announce filter
198	/// applies). `None` when the endpoint has no meaningful identity (a
199	/// leaf that never forwards); a wire value of 0 decodes as `None`. Lite-07 declares
200	/// [`node`](Self::node) instead, so it never sends one.
201	pub hop: Option<crate::Hop>,
202	/// This endpoint's Node ID (lite-07+): it forwards, and trusts the peer with the
203	/// whole tree. Two endpoints that both declare one exchange routes; any other pair
204	/// exchanges claims alone.
205	pub node: Option<crate::route::NodeId>,
206	/// The connection credential (lite-07+), which the empty-token Auth Stream names.
207	/// Sent only by the client. The parameter carries no Token Type, so it is always
208	/// [`Token::OUT_OF_BAND`](crate::setup::Token::OUT_OF_BAND).
209	pub token: Option<crate::setup::Token>,
210	/// Whether this endpoint offers the `ietf` extension (lite-07+). Negotiated only when
211	/// both endpoints offer it.
212	pub ietf: bool,
213	/// The sender's implementation, as space-separated `name/version` product tokens
214	/// (`moq-net-rs/0.3.10`). Opaque; `None` omits the parameter.
215	pub implementation: Option<String>,
216}
217
218impl std::fmt::Debug for Setup {
219	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220		f.debug_struct("Setup")
221			.field("probe", &self.probe)
222			// Native transports carry the JWT in this request target.
223			.field(
224				"path",
225				&self.path.as_deref().map(|path| path.split('?').next().unwrap()),
226			)
227			.field("role", &self.role)
228			.field("cost", &self.cost)
229			.field("hop", &self.hop)
230			.field("node", &self.node)
231			.field("token", &self.token)
232			.field("ietf", &self.ietf)
233			.field("implementation", &self.implementation)
234			.finish()
235	}
236}
237
238impl<'a> Message<'a> for Setup {
239	const CONTROL: Option<crate::stats::Message> = Some(crate::stats::Message::Session);
240	const MAX_SIZE: usize = crate::setup::MAX_SETUP_SIZE;
241
242	fn decode_msg(r: &mut Decoder<'a>, version: Version) -> Result<Self, DecodeError> {
243		ReceivedSetup::decode_msg(r, version).map(|received| received.setup)
244	}
245
246	fn encode_msg(&self, w: &mut Encoder<'_>, version: Version) -> Result<(), EncodeError> {
247		if !version.has_setup_stream() {
248			return Err(EncodeError::Version);
249		}
250
251		let mut params = Parameters::default();
252		// None is the wire default, so omit it to keep the message empty when nothing is set.
253		if self.probe != ProbeLevel::None {
254			params.set_varint(PARAM_PROBE, self.probe.to_code(), version)?;
255		}
256		if let Some(path) = &self.path {
257			params.set_bytes(PARAM_PATH, path.as_bytes().to_vec());
258		}
259		// Bidirectional is the wire default (absence of the parameter), so only a
260		// directional role is encoded.
261		if let Some(role) = self.role {
262			params.set_varint(PARAM_ROLE, role.to_code(), version)?;
263		}
264		if let Some(cost) = self.cost {
265			if cost == 0 && version.has_routes() {
266				return Err(EncodeError::InvalidState);
267			}
268			params.set_varint(PARAM_COST, cost, version)?;
269		}
270		if let Some(hop) = self.hop.filter(|_| !version.has_routes()) {
271			params.set_varint(PARAM_HOP, hop.wire_id(version.into()), version)?;
272		}
273		if let Some(node) = self.node {
274			if !version.has_routes() {
275				return Err(EncodeError::Version);
276			}
277			if node.relay == 0 || node.marked {
278				return Err(EncodeError::InvalidState);
279			}
280			let mut value = Vec::new();
281			let mut body = Encoder::new(&mut value, version.into());
282			body.varint(node.relay)?;
283			body.bool(false);
284			params.set_bytes(PARAM_HOP, value);
285		}
286		if let Some(implementation) = &self.implementation {
287			params.set_bytes(PARAM_IMPLEMENTATION, implementation.as_bytes().to_vec());
288		}
289		if let Some(token) = &self.token {
290			if !version.has_auth() {
291				return Err(EncodeError::Version);
292			}
293			// An empty value is no credential, and the untyped parameter cannot carry another type.
294			if token.kind != crate::setup::Token::OUT_OF_BAND || token.value.is_empty() {
295				return Err(EncodeError::Unsupported);
296			}
297			params.set_bytes(PARAM_TOKEN, token.value.clone());
298		}
299		if self.ietf {
300			// The framing it changes is unpublished, so a published version cannot offer it.
301			if !version.has_ietf() {
302				return Err(EncodeError::Version);
303			}
304			params.set_bytes(PARAM_IETF, Vec::new());
305		}
306
307		params.encode(w, version)
308	}
309}
310
311/// Raw presence is needed even when an unknown Role decodes as bidirectional.
312#[derive(Debug)]
313pub(super) struct ReceivedSetup {
314	pub setup: Setup,
315	role_present: bool,
316}
317
318impl<'a> Message<'a> for ReceivedSetup {
319	const CONTROL: Option<crate::stats::Message> = Some(crate::stats::Message::Session);
320	const MAX_SIZE: usize = Setup::MAX_SIZE;
321
322	fn decode_msg(r: &mut Decoder<'a>, version: Version) -> Result<Self, DecodeError> {
323		if !version.has_setup_stream() {
324			return Err(DecodeError::Version);
325		}
326
327		let params = Parameters::decode(r, version)?;
328		let probe = params
329			.get_varint(PARAM_PROBE, version)?
330			.map(ProbeLevel::from_code)
331			.unwrap_or_default();
332		let path = match params.get_bytes(PARAM_PATH) {
333			Some(bytes) => Some(
334				std::str::from_utf8(bytes)
335					.map_err(|_| DecodeError::InvalidValue)?
336					.to_string(),
337			),
338			None => None,
339		};
340		let role_code = params.get_varint(PARAM_ROLE, version)?;
341		let role = role_code.and_then(Role::from_code);
342		let cost = params.get_varint(PARAM_COST, version)?;
343		if cost == Some(0) && version.has_routes() {
344			return Err(DecodeError::InvalidValue);
345		}
346		// Before lite-07, 0 is legal on the wire but carries no identity (it can't be
347		// excluded), so it decodes as "not declared" rather than an error. A lite-07
348		// Node ID is never 0.
349		let (hop, node) = match version.has_routes() {
350			true => match params.get_bytes(PARAM_HOP) {
351				None => (None, None),
352				Some(value) => {
353					let mut body = Decoder::new(value, version.into());
354					let relay = body.varint()?;
355					// A session's node is never a marked identity, which holds none.
356					let marked = body.bool()?;
357					if relay == 0 || marked || !body.is_empty() {
358						return Err(DecodeError::InvalidValue);
359					}
360					(None, Some(crate::route::NodeId::new(relay)))
361				}
362			},
363			false => {
364				let declared = params.get_varint(PARAM_HOP, version)?;
365				(declared.and_then(std::num::NonZeroU64::new).map(crate::Hop::from), None)
366			}
367		};
368		let implementation = if version.has_implementation() {
369			crate::setup::decode_implementation(params.get_bytes(PARAM_IMPLEMENTATION))?
370		} else {
371			None
372		};
373		// An older version does not know these parameters, so it ignores them like any other.
374		let token = match params.get_bytes(PARAM_TOKEN) {
375			Some([]) if version.has_auth() => return Err(DecodeError::InvalidValue),
376			Some(value) if version.has_auth() => Some(crate::setup::Token {
377				kind: crate::setup::Token::OUT_OF_BAND,
378				value: value.to_vec(),
379			}),
380			_ => None,
381		};
382		let ietf = match params.get_bytes(PARAM_IETF) {
383			Some(value) if version.has_ietf() => match value.is_empty() {
384				true => true,
385				false => return Err(DecodeError::InvalidValue),
386			},
387			_ => false,
388		};
389
390		Ok(Self {
391			role_present: role_code.is_some(),
392			setup: Setup {
393				probe,
394				path,
395				role,
396				cost,
397				hop,
398				node,
399				token,
400				ietf,
401				implementation,
402			},
403		})
404	}
405
406	fn encode_msg(&self, w: &mut Encoder<'_>, version: Version) -> Result<(), EncodeError> {
407		self.setup.encode_msg(w, version)
408	}
409}
410
411/// Shared slot for the peer's SETUP, written once when its Setup stream is read.
412///
413/// Streams whose encoding depends on a negotiated capability (e.g. the PROBE
414/// stream) wait on this before deciding what to do. Cheap to clone: every handle
415/// shares the same slot.
416#[derive(Clone)]
417pub(crate) struct PeerSetup(kio::Shared<PeerSetupState>);
418
419struct PeerSetupState {
420	client: bool,
421	address: crate::transport::Address,
422	/// Whether our own SETUP offers the `ietf` extension.
423	ietf: bool,
424	peer: Peer,
425	/// Where the peer's advertised implementation is published for the session handle.
426	implementation: crate::setup::PeerImplementation,
427	/// The session's auth link to tell once the peer's SETUP accepts the connection.
428	accept: Option<crate::auth::Link>,
429	/// Unique to the session, so the route layer tells its streams' sessions apart.
430	tag: u64,
431}
432
433/// Where the peer's SETUP stands.
434enum Peer {
435	/// No Setup Stream yet.
436	Waiting,
437	/// The Setup Stream is claimed and its body still decoding, so no other may arrive.
438	Claimed,
439	Received(Box<Setup>),
440}
441
442impl PeerSetupState {
443	/// Record the peer's SETUP, refusing a second one.
444	fn set(&mut self, setup: Setup) -> Result<(), crate::Error> {
445		if let Peer::Received(_) = self.peer {
446			return Err(crate::Error::ProtocolViolation);
447		}
448		self.implementation.set(setup.implementation.clone());
449		self.peer = Peer::Received(Box::new(setup));
450		Ok(())
451	}
452
453	/// The peer's SETUP, once it arrived.
454	fn setup(&self) -> Option<&Setup> {
455		match &self.peer {
456			Peer::Received(setup) => Some(setup),
457			Peer::Waiting | Peer::Claimed => None,
458		}
459	}
460}
461
462/// A tag no other session holds: every route stream of one session shares it.
463pub(crate) fn session_tag() -> u64 {
464	static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
465	NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
466}
467
468impl PeerSetup {
469	pub fn new(client: bool, address: crate::transport::Address) -> Self {
470		Self(kio::Shared::new(PeerSetupState {
471			client,
472			address,
473			ietf: false,
474			peer: Peer::Waiting,
475			implementation: Default::default(),
476			accept: None,
477			tag: session_tag(),
478		}))
479	}
480
481	/// Unique to this session: every route stream of the session shares it.
482	pub fn tag(&self) -> u64 {
483		self.0.read().tag
484	}
485
486	/// Poll for the Node ID the peer's SETUP declared (lite-07), waiting until it arrives.
487	pub fn poll_node(&self, waiter: &kio::Waiter) -> std::task::Poll<Option<crate::route::NodeId>> {
488		self.poll_get(waiter, |setup| setup.node)
489	}
490
491	/// Tell `link` once the peer's SETUP arrives that it accepted the connection credential.
492	pub fn accepting(self, link: crate::auth::Link) -> Self {
493		link.await_acceptance();
494		self.0.lock().accept = Some(link);
495		self
496	}
497
498	/// Publish the peer's advertised implementation to `slot` once its SETUP arrives.
499	pub fn with_implementation(self, slot: crate::setup::PeerImplementation) -> Self {
500		self.0.lock().implementation = slot;
501		self
502	}
503
504	pub(super) fn receive(&self, received: ReceivedSetup) -> Result<(), crate::Error> {
505		let mut state = self.0.lock();
506		if ((state.client || state.address == crate::transport::Address::Uri) && received.setup.path.is_some())
507			|| (state.client && (received.role_present || received.setup.token.is_some()))
508		{
509			return Err(crate::Error::ProtocolViolation);
510		}
511		state.set(received.setup)?;
512		let accept = state.accept.take();
513		drop(state);
514		if let Some(link) = accept {
515			link.accepted();
516		}
517		Ok(())
518	}
519
520	/// Note whether our own SETUP offers the `ietf` extension, before any stream depends on it.
521	pub fn offer_ietf(self, ietf: bool) -> Self {
522		self.0.lock().ietf = ietf;
523		self
524	}
525
526	/// Poll whether the `ietf` extension is negotiated: both SETUPs offer it.
527	///
528	/// Resolves at once when we did not offer it, and otherwise once the peer's SETUP arrives.
529	pub fn poll_ietf(&self, waiter: &kio::Waiter) -> std::task::Poll<bool> {
530		if !self.0.lock().ietf {
531			return std::task::Poll::Ready(false);
532		}
533		self.poll_get(waiter, |setup| setup.ietf)
534	}
535
536	/// Whether the `ietf` extension is negotiated, or `None` before the peer's SETUP arrives.
537	pub fn ietf(&self) -> Option<bool> {
538		let state = self.0.lock();
539		match state.ietf {
540			false => Some(false),
541			true => state.setup().map(|setup| setup.ietf),
542		}
543	}
544
545	/// Record the peer's SETUP.
546	pub fn set(&self, setup: Setup) -> Result<(), crate::Error> {
547		self.0.lock().set(setup)
548	}
549
550	/// Claim the Setup Stream before decoding its body, refusing any second stream.
551	pub fn claim(&self) -> Result<(), crate::Error> {
552		let mut state = self.0.lock();
553		match state.peer {
554			Peer::Waiting => {
555				state.peer = Peer::Claimed;
556				Ok(())
557			}
558			Peer::Claimed | Peer::Received { .. } => Err(crate::Error::ProtocolViolation),
559		}
560	}
561
562	/// Poll for the peer's advertised probe level, waiting until its SETUP arrives.
563	pub fn poll_probe_level(&self, waiter: &kio::Waiter) -> std::task::Poll<ProbeLevel> {
564		self.poll_get(waiter, |setup| setup.probe)
565	}
566
567	/// Poll for the link cost the peer declared in its SETUP.
568	/// `None` when it declared none, meaning the default cost of 1.
569	pub fn poll_cost(&self, waiter: &kio::Waiter) -> std::task::Poll<Option<u64>> {
570		self.poll_get(waiter, |setup| setup.cost)
571	}
572
573	/// Poll for the [`Hop`](crate::Hop) id the peer declared in its SETUP `Hop`
574	/// parameter. `None` when it declared none: a leaf with no identity worth excluding.
575	pub fn poll_hop(&self, waiter: &kio::Waiter) -> std::task::Poll<Option<crate::Hop>> {
576		self.poll_get(waiter, |setup| setup.hop)
577	}
578
579	/// Poll for a field of the peer's SETUP.
580	///
581	/// The peer MUST send exactly one SETUP, so this resolves once that stream is read.
582	/// Pends forever if it never does; the caller is session state, dropped with the
583	/// driver.
584	fn poll_get<T>(&self, waiter: &kio::Waiter, f: impl FnOnce(&Setup) -> T) -> std::task::Poll<T> {
585		let state = std::task::ready!(self.0.poll(waiter, |state| match state.setup() {
586			Some(_) => std::task::Poll::Ready(()),
587			None => std::task::Poll::Pending,
588		}));
589		std::task::Poll::Ready(f(state.setup().expect("judged under this lock")))
590	}
591}
592
593#[cfg(test)]
594mod tests {
595	use super::*;
596
597	fn round_trip(msg: &Setup) -> Setup {
598		let mut buf = Vec::new();
599		msg.encode(&mut Encoder::new(&mut buf, Version::Lite05.into()), Version::Lite05)
600			.unwrap();
601		let mut slice = &buf[..];
602		let got = crate::coding::decode_buf(&mut slice, Version::Lite05, |r, v| Setup::decode(r, v)).unwrap();
603		assert!(bytes::Buf::remaining(&slice) == 0, "trailing bytes after decode");
604		got
605	}
606
607	#[test]
608	fn empty_round_trip() {
609		let msg = Setup::default();
610		assert_eq!(round_trip(&msg), msg);
611	}
612
613	/// A transport exposing neither metric can't honour a `Report` claim, and the
614	/// draft makes such a publisher reset any Probe Stream a subscriber opens. It
615	/// must advertise `None` so the subscriber never opens one.
616	#[test]
617	#[cfg(feature = "async")]
618	fn detect_reports_nothing_without_stats() {
619		use crate::lite::test_transport::{SinkSession, SinkStats};
620		let session = SinkSession::new(Default::default()).with_stats(SinkStats::default());
621		assert_eq!(
622			ProbeLevel::detect(&crate::driver::Transport::new(session.clone())),
623			ProbeLevel::None
624		);
625	}
626
627	/// Either metric alone is enough to report, since the two PROBE fields are
628	/// independent on the wire.
629	#[test]
630	#[cfg(feature = "async")]
631	fn detect_reports_with_either_metric() {
632		use crate::lite::test_transport::{SinkSession, SinkStats};
633
634		let rtt_only = SinkStats::default().with_rtt(std::time::Duration::from_millis(40));
635		let session = SinkSession::new(Default::default()).with_stats(rtt_only);
636		assert_eq!(
637			ProbeLevel::detect(&crate::driver::Transport::new(session.clone())),
638			ProbeLevel::Report
639		);
640
641		let rate_only = SinkStats::default().with_send_rate(1_000_000);
642		let session = SinkSession::new(Default::default()).with_stats(rate_only);
643		assert_eq!(
644			ProbeLevel::detect(&crate::driver::Transport::new(session.clone())),
645			ProbeLevel::Report
646		);
647	}
648
649	/// A sender probes to the peer's target as well as its own, so it promises the peer
650	/// `Increase`. Without one, `detect_reports_with_either_metric` stays at `Report`.
651	#[test]
652	#[cfg(feature = "async")]
653	fn a_sender_advertises_increase() {
654		use crate::lite::test_transport::{SinkSession, SinkStats};
655
656		let stats = SinkStats::default().with_send_rate(1_000_000);
657		let session = SinkSession::new(Default::default()).with_stats(stats).with_probe();
658		assert_eq!(
659			ProbeLevel::detect(&crate::driver::Transport::new(session.clone())),
660			ProbeLevel::Increase
661		);
662	}
663
664	#[test]
665	fn probe_levels_round_trip() {
666		for probe in [ProbeLevel::None, ProbeLevel::Report, ProbeLevel::Increase] {
667			let msg = Setup {
668				probe,
669				..Default::default()
670			};
671			assert_eq!(round_trip(&msg), msg);
672		}
673	}
674
675	#[test]
676	fn cost_round_trip() {
677		// Zero is a meaningful price before lite-07 (a free same-datacenter link), so it
678		// must survive the round trip as `Some(0)` rather than collapsing into "unpriced".
679		for cost in [None, Some(0), Some(1), Some(7)] {
680			let msg = Setup {
681				cost,
682				..Default::default()
683			};
684			assert_eq!(round_trip(&msg), msg);
685			if cost != Some(0) {
686				let buf = msg.encode_bytes(Version::Lite07).unwrap();
687				assert_eq!(Setup::decode_slice(&buf, Version::Lite07).unwrap().0, msg);
688			}
689		}
690	}
691
692	/// Lite-07 refuses a free link both ways: selection converges only because every
693	/// link adds at least 1.
694	#[test]
695	fn lite07_refuses_a_zero_cost() {
696		let msg = Setup {
697			cost: Some(0),
698			..Default::default()
699		};
700		assert!(matches!(
701			msg.encode_bytes(Version::Lite07),
702			Err(EncodeError::InvalidState)
703		));
704		// Length, one parameter, Cost, a one-byte value of 0.
705		let wire = [0x04, 0x01, 0x04, 0x01, 0x00];
706		assert!(matches!(
707			Setup::decode_slice(&wire, Version::Lite07),
708			Err(DecodeError::InvalidValue)
709		));
710		assert_eq!(Setup::decode_slice(&wire, Version::Lite06).unwrap().0, msg);
711	}
712
713	/// Parameter values follow the session's varint codec, not a fixed one: a value that
714	/// takes the two-byte QUIC form on lite-06 fits one leading-ones byte on lite-07.
715	#[test]
716	fn parameter_values_use_the_version_codec() {
717		let msg = Setup {
718			cost: Some(100),
719			..Default::default()
720		};
721		for (version, wire) in [
722			(Version::Lite06, &[0x05, 0x01, 0x04, 0x02, 0x40, 0x64][..]),
723			(Version::Lite07, &[0x04, 0x01, 0x04, 0x01, 0x64][..]),
724		] {
725			let buf = msg.encode_bytes(version).unwrap();
726			assert_eq!(buf, wire, "{version}");
727			assert_eq!(
728				Setup::decode_slice(&buf, version).unwrap(),
729				(msg.clone(), buf.len()),
730				"{version}"
731			);
732		}
733	}
734
735	/// The `ietf` offer is an empty parameter that only a version with the extension sends,
736	/// and an older one ignores like any unknown parameter.
737	#[test]
738	fn ietf_offer_is_lite07_only() {
739		let msg = Setup {
740			ietf: true,
741			..Default::default()
742		};
743		let buf = msg.encode_bytes(Version::Lite07).unwrap();
744		assert_eq!(Setup::decode_slice(&buf, Version::Lite07).unwrap().0, msg);
745		assert!(msg.encode_bytes(Version::Lite06).is_err());
746
747		// Length, one parameter, its 8-byte QUIC varint ID, and an empty value.
748		let older = [0x0a, 0x01, 0xc0, 0, 0, 0, 0x49, 0x45, 0x54, 0x46, 0x00];
749		assert_eq!(
750			Setup::decode_slice(&older, Version::Lite06).unwrap().0,
751			Setup::default()
752		);
753
754		// A value it does not define is refused.
755		let mut valued = buf.to_vec();
756		assert_eq!(valued.pop(), Some(0), "the offer ends in its empty value");
757		valued.extend([1, 7]);
758		valued[0] += 1;
759		assert!(Setup::decode_slice(&valued, Version::Lite07).is_err());
760	}
761
762	/// The connection credential rides lite-07+, which an older version ignores like any
763	/// unknown parameter, and only an untyped, non-empty token can be sent.
764	#[test]
765	fn token_is_lite07_only() {
766		let token = crate::setup::Token {
767			kind: crate::setup::Token::OUT_OF_BAND,
768			value: b"jwt".to_vec(),
769		};
770		let msg = Setup {
771			token: Some(token.clone()),
772			..Default::default()
773		};
774		let buf = msg.encode_bytes(Version::Lite07).unwrap();
775		// Length, one parameter, its id, then the token's length and bytes.
776		assert_eq!(&buf[..], [0x06, 0x01, 0x07, 0x03, b'j', b'w', b't']);
777		assert_eq!(Setup::decode_slice(&buf, Version::Lite07).unwrap().0, msg);
778		assert!(matches!(msg.encode_bytes(Version::Lite06), Err(EncodeError::Version)));
779		assert_eq!(Setup::decode_slice(&buf, Version::Lite06).unwrap().0, Setup::default());
780
781		for unsendable in [
782			crate::setup::Token {
783				// Any registered type but out-of-band, which moq-lite cannot carry.
784				kind: 0x1,
785				..token.clone()
786			},
787			crate::setup::Token {
788				value: Vec::new(),
789				..token
790			},
791		] {
792			let msg = Setup {
793				token: Some(unsendable),
794				..Default::default()
795			};
796			assert!(matches!(
797				msg.encode_bytes(Version::Lite07),
798				Err(EncodeError::Unsupported)
799			));
800		}
801
802		// An empty value carries no credential, so it is refused rather than read as none.
803		assert!(Setup::decode_slice(&[0x03, 0x01, 0x07, 0x00], Version::Lite07).is_err());
804	}
805
806	/// Only the client presents a connection credential.
807	#[test]
808	fn a_server_token_is_a_protocol_violation() {
809		let setup = Setup {
810			token: Some(crate::setup::Token {
811				kind: crate::setup::Token::OUT_OF_BAND,
812				value: b"jwt".to_vec(),
813			}),
814			..Default::default()
815		};
816		let buf = setup.encode_bytes(Version::Lite07).unwrap();
817		let received = |buf: &[u8]| ReceivedSetup::decode_slice(buf, Version::Lite07).unwrap().0;
818
819		let client = PeerSetup::new(true, crate::transport::Address::Setup);
820		assert!(matches!(
821			client.receive(received(&buf)),
822			Err(crate::Error::ProtocolViolation)
823		));
824		let server = PeerSetup::new(false, crate::transport::Address::Setup);
825		server.receive(received(&buf)).unwrap();
826	}
827
828	/// Never emit a SETUP our own receiver would refuse.
829	#[test]
830	fn encode_enforces_the_setup_limit() {
831		// Count, id, and a 4-byte length varint precede the path.
832		let at_limit = crate::setup::MAX_SETUP_SIZE - 6;
833		let msg = Setup {
834			path: Some("a".repeat(at_limit)),
835			..Default::default()
836		};
837		assert_eq!(round_trip(&msg), msg);
838
839		let msg = Setup {
840			path: Some("a".repeat(at_limit + 1)),
841			..Default::default()
842		};
843		let mut buf = Vec::new();
844		assert!(matches!(
845			msg.encode(&mut Encoder::new(&mut buf, Version::Lite05.into()), Version::Lite05),
846			Err(EncodeError::TooLarge)
847		));
848		assert!(buf.is_empty());
849	}
850
851	#[test]
852	fn path_round_trip() {
853		let msg = Setup {
854			probe: ProbeLevel::Report,
855			path: Some("/room/123".to_string()),
856			..Default::default()
857		};
858		assert_eq!(round_trip(&msg), msg);
859	}
860
861	#[test]
862	fn implementation_round_trip() {
863		for implementation in [None, Some("moq-ffi/0.4.12 moq-net-rs/0.3.10".to_string())] {
864			let msg = Setup {
865				implementation,
866				..Default::default()
867			};
868			let buf = msg.encode_bytes(Version::Lite07).unwrap();
869			assert_eq!(Setup::decode_slice(&buf, Version::Lite07).unwrap().0, msg);
870		}
871	}
872
873	/// The value is UTF-8, so bytes that are not refuse the whole SETUP.
874	#[test]
875	fn implementation_must_be_utf8() {
876		let msg = Setup {
877			implementation: Some("ab".to_string()),
878			..Default::default()
879		};
880		let mut buf = msg.encode_bytes(Version::Lite07).unwrap().to_vec();
881		let last = buf.len() - 1;
882		buf[last] = 0xff;
883		assert!(matches!(
884			Setup::decode_slice(&buf, Version::Lite07),
885			Err(DecodeError::InvalidValue)
886		));
887	}
888
889	#[test]
890	fn older_versions_ignore_implementation_before_parsing_it() {
891		for version in [Version::Lite05, Version::Lite06] {
892			for value in [b"x/1".as_slice(), &[0xff]] {
893				let mut params = Parameters::default();
894				params.set_bytes(PARAM_IMPLEMENTATION, value.to_vec());
895				let mut data = Vec::new();
896				let mut writer = Encoder::new(&mut data, version.into());
897				let prefix = writer.prefix_varint();
898				params.encode(&mut writer, version).unwrap();
899				writer.fill(prefix).unwrap();
900				assert!(Setup::decode_slice(&data, version).unwrap().0.implementation.is_none());
901			}
902		}
903	}
904
905	#[test]
906	fn hop_round_trip() {
907		let msg = Setup {
908			hop: Some(crate::Hop::new(42).unwrap()),
909			..Default::default()
910		};
911		assert_eq!(round_trip(&msg), msg);
912	}
913
914	// A hop past 2^62 - 1 travels as 0 on a QUIC-varint version, which reads as undeclared.
915	#[test]
916	fn wide_hop_reads_as_undeclared_on_lite06() {
917		let msg = Setup {
918			hop: Some(crate::Hop::new(u64::MAX).unwrap()),
919			..Default::default()
920		};
921		let buf = msg.encode_bytes(Version::Lite06).unwrap();
922		assert_eq!(Setup::decode_slice(&buf, Version::Lite06).unwrap().0.hop, None);
923	}
924
925	/// Lite-07 carries the endpoint's Node ID in the parameter that names its Hop ID before.
926	#[test]
927	fn lite07_declares_the_node_instead_of_the_hop() {
928		let version = Version::Lite07;
929		let msg = Setup {
930			hop: Some(crate::Hop::new(42).unwrap()),
931			node: Some(crate::route::NodeId::new(7)),
932			..Default::default()
933		};
934		let got = Setup::decode_slice(&msg.encode_bytes(version).unwrap(), version)
935			.unwrap()
936			.0;
937		assert_eq!(got.hop, None);
938		assert_eq!(got.node, msg.node);
939		assert!(
940			msg.encode_bytes(Version::Lite06).is_err(),
941			"only lite-07 carries a Node ID"
942		);
943
944		// A Node ID of 0 names nobody, Marked must follow it, a session's node is never
945		// marked, and nothing may follow that.
946		for value in [&[0, 0][..], &[7], &[7, 1], &[7, 2], &[7, 0, 1]] {
947			let mut params = Parameters::default();
948			params.set_bytes(super::PARAM_HOP, value.to_vec());
949			let mut data = Vec::new();
950			let mut writer = Encoder::new(&mut data, version.into());
951			let prefix = writer.prefix_varint();
952			params.encode(&mut writer, version).unwrap();
953			writer.fill(prefix).unwrap();
954			assert!(Setup::decode_slice(&data, version).is_err(), "Node ID {value:?}");
955		}
956	}
957
958	// A declared id of 0 carries no identity (it cannot be excluded), so it
959	// decodes as absent rather than erroring.
960	#[test]
961	fn hop_zero_decodes_as_none() {
962		use crate::coding::Encode;
963
964		let version = Version::Lite05;
965		let mut params = Parameters::default();
966		params.set_varint(super::PARAM_HOP, 0, version).unwrap();
967		let mut body = Vec::new();
968		params
969			.encode(&mut Encoder::new(&mut body, version.into()), version)
970			.unwrap();
971		// Frame the body with the Message Length prefix `Setup::decode` expects.
972		let mut buf = Vec::new();
973		Encoder::new(&mut buf, version.into())
974			.varint(body.len() as u64)
975			.unwrap();
976		buf.extend_from_slice(&body);
977		let mut slice = &buf[..];
978		let got = crate::coding::decode_buf(&mut slice, version, |r, v| Setup::decode(r, v)).unwrap();
979		assert_eq!(got.hop, None);
980	}
981
982	#[test]
983	fn empty_path_round_trips() {
984		// An empty path is valid and distinct from absent only on the wire; both mean
985		// the root, so a client doesn't have to special-case it.
986		let msg = Setup {
987			path: Some(String::new()),
988			..Default::default()
989		};
990		assert_eq!(round_trip(&msg), msg);
991	}
992
993	#[test]
994	fn roles_round_trip() {
995		for role in [Some(Role::Publisher), Some(Role::Subscriber), None] {
996			let msg = Setup {
997				path: Some("/room/123".to_string()),
998				role,
999				..Default::default()
1000			};
1001			assert_eq!(round_trip(&msg), msg);
1002		}
1003	}
1004
1005	#[test]
1006	fn unknown_probe_level_saturates_to_increase() {
1007		// Frame a SETUP message carrying an unknown probe level (99) by hand: the
1008		// parameters body, prefixed with its length (the lite Message size prefix).
1009		let mut params = Parameters::default();
1010		params.set_varint(PARAM_PROBE, 99, Version::Lite05).unwrap();
1011		let mut body = Vec::new();
1012		params
1013			.encode(&mut Encoder::new(&mut body, Version::Lite05.into()), Version::Lite05)
1014			.unwrap();
1015
1016		let mut buf = Vec::new();
1017		Encoder::new(&mut buf, Version::Lite05.into())
1018			.varint(body.len() as u64)
1019			.unwrap();
1020		buf.extend_from_slice(&body);
1021
1022		let mut slice = &buf[..];
1023		let got = crate::coding::decode_buf(&mut slice, Version::Lite05, |r, v| Setup::decode(r, v)).unwrap();
1024		assert_eq!(got.probe, ProbeLevel::Increase);
1025	}
1026
1027	/// Roles, pinned to the draft. A swap still round trips against our own decoder but
1028	/// breaks every other implementation.
1029	#[test]
1030	fn role_code_points() {
1031		for (role, spec) in [(Role::Publisher, 1u64), (Role::Subscriber, 2)] {
1032			assert_eq!(role.to_code(), spec, "{role:?}");
1033			assert_eq!(Role::from_code(spec), Some(role));
1034		}
1035	}
1036
1037	#[test]
1038	fn unknown_role_decodes_as_bidirectional() {
1039		// A role value the receiver doesn't recognize (a future extension, or an explicit
1040		// 0) decodes to `None` rather than failing, so a newer client can't break an older
1041		// server. The draft mandates this fallback.
1042		for code in [0u64, 9, 250] {
1043			let mut params = Parameters::default();
1044			params.set_varint(PARAM_ROLE, code, Version::Lite05).unwrap();
1045			let mut body = Vec::new();
1046			params
1047				.encode(&mut Encoder::new(&mut body, Version::Lite05.into()), Version::Lite05)
1048				.unwrap();
1049
1050			let mut buf = Vec::new();
1051			Encoder::new(&mut buf, Version::Lite05.into())
1052				.varint(body.len() as u64)
1053				.unwrap();
1054			buf.extend_from_slice(&body);
1055
1056			let mut slice = &buf[..];
1057			let got = crate::coding::decode_buf(&mut slice, Version::Lite05, |r, v| Setup::decode(r, v)).unwrap();
1058			assert_eq!(got.role, None, "role code {code} should decode as bidirectional");
1059		}
1060	}
1061
1062	#[test]
1063	fn rejects_before_lite05() {
1064		let msg = Setup::default();
1065		let mut buf = Vec::new();
1066		assert!(matches!(
1067			msg.encode(&mut Encoder::new(&mut buf, Version::Lite04.into()), Version::Lite04),
1068			Err(EncodeError::Version)
1069		));
1070	}
1071
1072	#[test]
1073	fn ignores_unknown_parameters() {
1074		// Frame a SETUP carrying an unknown parameter ID alongside the path.
1075		let mut params = Parameters::default();
1076		params.set_bytes(PARAM_PATH, b"/foo".to_vec());
1077		params.set_bytes(0xbeef, b"whatever".to_vec());
1078
1079		let mut body = Vec::new();
1080		params
1081			.encode(&mut Encoder::new(&mut body, Version::Lite05.into()), Version::Lite05)
1082			.unwrap();
1083
1084		// Wrap with the message size prefix the Message impl expects.
1085		let mut buf = Vec::new();
1086		Encoder::new(&mut buf, Version::Lite05.into())
1087			.varint(body.len() as u64)
1088			.unwrap();
1089		buf.extend_from_slice(&body);
1090
1091		let mut slice = &buf[..];
1092		let got = crate::coding::decode_buf(&mut slice, Version::Lite05, |r, v| Setup::decode(r, v)).unwrap();
1093		assert_eq!(got.path.as_deref(), Some("/foo"));
1094	}
1095}