moqtap_client/draft13/connection.rs
1use bytes::{Buf, Bytes, BytesMut};
2
3use crate::draft13::endpoint::{Endpoint, EndpointError};
4use crate::draft13::event::{ClientEvent, Direction, FetchObject, StreamKind, SubgroupObject};
5use crate::draft13::observer::ConnectionObserver;
6use crate::draft13::session::request_id::Role;
7use crate::draft13::session::setup;
8use crate::forwarding_preference::ObjectForwardingPreference;
9use crate::malformed_tracks::MalformedTrackCondition;
10use crate::track_locations::{EndOfTrackForm, ObjectLocation, ObjectRole, TrackObjects};
11use crate::transport::{RecvStream, SendStream, Transport, TransportError};
12use moqtap_codec::dispatch::{
13 AnyControlMessage, AnyDatagramHeader, AnyFetchHeader, AnySubgroupHeader,
14};
15use moqtap_codec::draft13::data_stream::{FetchObjectHeader, ObjectHeader, SubgroupGaps};
16use moqtap_codec::draft13::message::ControlMessage;
17use moqtap_codec::error::CodecError;
18use moqtap_codec::kvp::KeyValuePair;
19use moqtap_codec::types::*;
20use moqtap_codec::varint::VarInt;
21use moqtap_codec::version::DraftVersion;
22
23/// MoQT ALPN identifier (used by raw QUIC transport).
24pub const MOQT_ALPN: &[u8] = b"moq-00";
25
26/// Errors from the draft-13 connection layer.
27#[derive(Debug, thiserror::Error)]
28pub enum ConnectionError {
29 /// Endpoint state machine error.
30 #[error("endpoint error: {0}")]
31 Endpoint(#[from] EndpointError),
32 /// Wire codec error.
33 #[error("codec error: {0}")]
34 Codec(#[from] CodecError),
35 /// Transport-level error.
36 #[error("transport error: {0}")]
37 Transport(#[from] TransportError),
38 /// Variable-length integer decoding error.
39 #[error("varint error: {0}")]
40 VarInt(#[from] moqtap_codec::varint::VarIntError),
41 /// Control stream was not opened.
42 #[error("control stream not open")]
43 NoControlStream,
44 /// Stream ended before a complete message was read.
45 #[error("unexpected end of stream")]
46 UnexpectedEnd,
47 /// Stream was finished by the peer.
48 #[error("stream finished")]
49 StreamFinished,
50 /// Invalid server address string.
51 #[error("invalid server address: {0}")]
52 InvalidAddress(String),
53 /// TLS configuration error.
54 #[error("TLS config error: {0}")]
55 TlsConfig(String),
56 /// Data stream used out of order: an object before its header, or an
57 /// Object ID that does not advance on the last one written.
58 #[error("data stream state error: {0}")]
59 DataStreamState(&'static str),
60 /// A control message this build decoded for draft-13 and then could not
61 /// narrow to draft-13's own message type.
62 ///
63 /// Unreachable, and that is not the same as harmless. `read_control`
64 /// decodes with this connection's own draft, so the `AnyControlMessage` it
65 /// hands back can only carry this draft's variant — but the narrowing arm
66 /// is compiled in every configuration anyway, under
67 /// `#[allow(unreachable_patterns)]` rather than a `cfg` naming the other
68 /// drafts, because such a list has to be edited in every draft
69 /// module whenever a draft is added, and a copy that omits one leaves the
70 /// match non-exhaustive.
71 ///
72 /// Spelled as `CodecError::UnknownMessageType(0)` it would not stay inert:
73 /// every draft's
74 /// [`codec_session_error_code`](Connection::codec_session_error_code)
75 /// answers that variant `Some(PROTOCOL_VIOLATION)`. So the day the
76 /// narrowing did fail, this build's own defect would reach a caller as *the
77 /// peer sent a control message type this draft does not assign, and the
78 /// session must be closed with a Protocol Violation* — carrying `0x00` as
79 /// the codepoint that proved it. A conformance report reading that
80 /// publishes a named, well-evidenced accusation against a relay for
81 /// something no relay did.
82 ///
83 /// A variant of its own is what stops that.
84 /// [`draft_specific_cause`](Connection::draft_specific_cause) answers it
85 /// [`LocalRefusal`], the facade turns that into [`ErrorCause::Facade`], and
86 /// nothing downstream can read a rule out of a cause that says nothing
87 /// reached the wire. What is pinned is the consequence rather than the
88 /// unreachability: nothing pins the arm's reachability, which is exactly
89 /// why the consequence must not be an accusation.
90 ///
91 /// [`LocalRefusal`]: crate::above_codec_rules::DraftSpecificCause::LocalRefusal
92 /// [`ErrorCause::Facade`]: crate::dispatch::ErrorCause::Facade
93 #[error(
94 "a control message decoded for draft-13 did not narrow to draft-13: a defect in this build, and evidence about nothing the peer did"
95 )]
96 ControlMessageNarrowing,
97 /// A datagram whose Type announces extension headers arrived with an
98 /// Extension Headers Length of 0.
99 ///
100 /// Types 0x01, 0x03 and 0x05 close the session. The two close rules still
101 /// carry draft-11's code points, and are read through the datagram table in
102 /// draft-13 Section 9, which assigns 0x00-0x03 to OBJECT_DATAGRAM and
103 /// 0x04-0x05 to OBJECT_DATAGRAM_STATUS:
104 ///
105 /// - draft-13 Section 9.3.2: "The Type field takes the form 0b0000001X (or
106 /// the set of values from 0x02 to 0x03)" and "If an endpoint receives a
107 /// datagram with Type 0x03 and Extension Headers Length is 0, it MUST
108 /// close the session with Protocol Violation." draft-11 Section 9 assigns
109 /// 0x02-0x03 to OBJECT_DATAGRAM_STATUS. draft-14 Appendix A.1 lists
110 /// "Corrected missed code point updates to Object Datagram Status
111 /// (#1082)", and that change rewrites the sentence to "Type 0x05". It
112 /// names 0x05.
113 /// - draft-13 Section 9.3.1: "If an endpoint receives a datagram with Type
114 /// 0x01 and Extension Headers Length is 0, it MUST close the session with
115 /// Protocol Violation." 0x01 is the only OBJECT_DATAGRAM Type with
116 /// extensions in draft-11 Section 9.2. draft-13 Section 9.3.1 Table 12
117 /// adds 0x03, End Of Group with Extensions Present "Yes", and the
118 /// sentence was not updated. draft-14 Section 10.3.1 states the rule for
119 /// every such Type: "If an endpoint receives a datagram with Extensions
120 /// Present as "Yes" and a Extension Headers Length of 0, it MUST close
121 /// the session with PROTOCOL_VIOLATION." It names 0x01 and 0x03.
122 ///
123 /// The codec's `DatagramType` carries the same ruling.
124 ///
125 /// The codec's header decoder refuses such a datagram as a bare
126 /// `InvalidField`. [`Connection::recv_datagram`] names it here, and
127 /// [`Connection::close_for_data_stream`] closes the session over it.
128 #[error(
129 "the datagram for object {object_id} announces extension headers and has an Extension Headers Length of 0"
130 )]
131 EmptyDatagramExtensions {
132 /// The Object ID the datagram named.
133 object_id: u64,
134 },
135}
136
137/// [`ConnectionError::EmptyDatagramExtensions`] for a datagram the header
138/// decoder refused as `InvalidField`, when its empty extension block was the
139/// fault.
140///
141/// Every Type the codec's `DatagramType` says carries extensions: 0x01, 0x03
142/// and 0x05. Each carries an Object ID and a Publisher Priority.
143fn empty_datagram_extensions(data: &[u8]) -> Option<ConnectionError> {
144 use crate::datagram_prefix::{empty_extension_block, Prefix};
145 use moqtap_codec::draft13::data_stream::DatagramType;
146 empty_extension_block(data, |datagram_type, _| {
147 DatagramType::from_id(datagram_type)?
148 .has_extensions()
149 .then_some(Prefix { object_id: true, priority: true })
150 })
151 .map(|object_id| ConnectionError::EmptyDatagramExtensions { object_id })
152}
153
154impl From<crate::transport::DialError> for ConnectionError {
155 /// Maps a dial failure onto the variants this error already has, so a
156 /// caller matches `InvalidAddress` or `TlsConfig`.
157 ///
158 /// A `LocalSocket` failure maps to `InvalidAddress`, which the facade reads
159 /// as this side's failure
160 /// ([`ErrorCause::Facade`](crate::dispatch::ErrorCause::Facade)). The dial
161 /// phase stays on [`DialError::phase`](crate::transport::DialError::phase).
162 fn from(e: crate::transport::DialError) -> Self {
163 match e {
164 // Two variants, one arm, deliberately — see above.
165 crate::transport::DialError::InvalidAddress(s)
166 | crate::transport::DialError::LocalSocket(s) => ConnectionError::InvalidAddress(s),
167 crate::transport::DialError::TlsConfig(s) => ConnectionError::TlsConfig(s),
168 crate::transport::DialError::Transport(e) => ConnectionError::Transport(e),
169 }
170 }
171}
172
173/// Transport type for the connection.
174#[derive(Debug, Clone)]
175pub enum TransportType {
176 /// Raw QUIC via quinn. The `addr` field should be `host:port`.
177 Quic,
178 /// WebTransport via wtransport. The `url` field is the WebTransport URL.
179 WebTransport {
180 /// The WebTransport endpoint URL (e.g., `https://host:port/path`).
181 url: String,
182 },
183}
184
185/// Configuration for a draft-13 MoQT client connection.
186pub struct ClientConfig {
187 /// Additional draft versions to offer in CLIENT_SETUP (draft-13 is always
188 /// offered first).
189 pub additional_versions: Vec<DraftVersion>,
190 /// The transport type (QUIC or WebTransport).
191 pub transport: TransportType,
192 /// Whether to skip TLS certificate verification (for testing).
193 pub skip_cert_verification: bool,
194 /// Custom CA certificates to trust (DER-encoded).
195 pub ca_certs: Vec<Vec<u8>>,
196 /// Setup parameters to include in CLIENT_SETUP (e.g., auth tokens).
197 pub setup_parameters: Vec<moqtap_codec::kvp::KeyValuePair>,
198}
199
200impl ClientConfig {
201 /// Returns the MoQT version varints for the CLIENT_SETUP message.
202 /// Draft-13 first, then any additional versions.
203 pub fn supported_versions(&self) -> Vec<VarInt> {
204 let mut versions = vec![DraftVersion::Draft13.version_varint()];
205 for v in &self.additional_versions {
206 let varint = v.version_varint();
207 if !versions.contains(&varint) {
208 versions.push(varint);
209 }
210 }
211 versions
212 }
213
214 /// Returns the ALPN protocol identifiers for the transport.
215 pub fn alpn(&self) -> Vec<Vec<u8>> {
216 match &self.transport {
217 TransportType::Quic => vec![DraftVersion::Draft13.quic_alpn().to_vec()],
218 TransportType::WebTransport { .. } => vec![b"h3".to_vec()],
219 }
220 }
221}
222
223/// A framed writer for a send stream. Handles MoQT length-prefixed framing.
224pub struct FramedSendStream {
225 inner: SendStream,
226 /// What the subgroup header opened on this stream settled, once one has
227 /// been written.
228 ///
229 /// `None` until a subgroup header has been written, which is what makes an
230 /// object sent before its header answerable rather than unframed bytes.
231 subgroup_objects: Option<SubgroupStreamState>,
232}
233
234/// What a subgroup header fixes for every object written after it.
235///
236/// Two facts, and neither is recoverable from an object on its own: the
237/// Object ID it has to advance past, and whether the stream's type puts an
238/// extension block on each object. The second has to be remembered rather than
239/// guessed: a header type whose Extensions Present column reads Yes puts an
240/// Extension Headers Length on every object of the subgroup, so assuming
241/// "absent" would write a stream a reader could not follow.
242#[derive(Debug, Clone, Copy)]
243struct SubgroupStreamState {
244 /// The last Object ID written, or `None` before the first object.
245 previous_object_id: Option<u64>,
246 /// Whether each object writes an Extension Headers Length field.
247 carries_extension_block: bool,
248}
249
250impl FramedSendStream {
251 /// Create a new framed send stream.
252 pub fn new(inner: SendStream) -> Self {
253 Self { inner, subgroup_objects: None }
254 }
255
256 /// Get the transport-level stream ID.
257 pub fn stream_id(&self) -> u64 {
258 self.inner.stream_id()
259 }
260
261 /// Write a control message to the stream with type+length framing.
262 /// Returns the raw bytes that were written (for event capture).
263 pub async fn write_control(
264 &mut self,
265 msg: &AnyControlMessage,
266 ) -> Result<Vec<u8>, ConnectionError> {
267 let mut buf = Vec::new();
268 msg.encode(&mut buf)?;
269 self.inner.write_all(&buf).await?;
270 Ok(buf)
271 }
272
273 /// Write a subgroup stream header. Also opens the Object ID bookkeeping
274 /// [`FramedSendStream::write_subgroup_object`] holds the stream to.
275 ///
276 /// The header is refused, and nothing is written, if its fields disagree
277 /// with its own stream type. That check has to happen here rather than at
278 /// the first object: the type is what every object after it is framed
279 /// against, so a header that went out saying the wrong thing cannot be
280 /// taken back.
281 pub async fn write_subgroup_header(
282 &mut self,
283 header: &AnySubgroupHeader,
284 ) -> Result<(), ConnectionError> {
285 let mut buf = Vec::new();
286 header.encode_stream_checked(&mut buf)?;
287 self.inner.write_all(&buf).await?;
288 // The framing is read off the header now, while the header is in hand.
289 // An object arriving later cannot say whether the stream carries an
290 // extension block, and writing one either way is not a recoverable
291 // mistake: the reader takes the next field along as the missing length
292 // and misframes every object after it.
293 self.subgroup_objects = Some(SubgroupStreamState {
294 previous_object_id: None,
295 carries_extension_block: header.carries_extension_block(),
296 });
297 Ok(())
298 }
299
300 /// Write a fetch response header.
301 pub async fn write_fetch_header(
302 &mut self,
303 header: &AnyFetchHeader,
304 ) -> Result<(), ConnectionError> {
305 let mut buf = Vec::new();
306 header.encode_stream(&mut buf);
307 self.inner.write_all(&buf).await?;
308 Ok(())
309 }
310
311 /// Append a draft-13 subgroup object (header + payload) to the stream.
312 ///
313 /// Section 9.4.2: "A publisher MUST NOT send an Object on a stream if its
314 /// Object ID is less than a previously sent Object ID within a given group
315 /// in that stream." A subgroup stream carries one group, so the Object IDs
316 /// written here are exactly the ones that sentence compares, and the
317 /// comparison needs the object before - which no per-header check can see.
318 /// The state advances only once the object has been written, so declining to
319 /// write an object leaves the next one measured against the last one kept.
320 ///
321 /// An equal Object ID is refused as well as a smaller one. The draft's own
322 /// sentence forbids only "less than", but an Object ID names an Object
323 /// within a Group: writing one twice on a stream describes the same Object
324 /// with two different payloads, and a reader has no way to choose. The
325 /// dispatch-level writer in the codec draws the line in the same place, and
326 /// two writers that disagreed about it would be worse than either answer.
327 ///
328 /// # Errors
329 ///
330 /// [`ConnectionError::DataStreamState`] if no subgroup header has been
331 /// written yet, or if `object` does not advance past the last one written.
332 pub async fn write_subgroup_object(
333 &mut self,
334 object: &SubgroupObject,
335 ) -> Result<(), ConnectionError> {
336 let state = self
337 .subgroup_objects
338 .as_mut()
339 .ok_or(ConnectionError::DataStreamState("subgroup header not written yet"))?;
340 let object_id = object.header.object_id.into_inner();
341 if matches!(state.previous_object_id, Some(prev) if object_id <= prev) {
342 return Err(ConnectionError::DataStreamState(
343 "object id does not advance on the last one written to this stream",
344 ));
345 }
346 // The declared length comes from the payload rather than from the
347 // caller's field: a header that disagrees with the bytes beside it
348 // desynchronises every object after it on the stream, and nothing
349 // downstream can recover.
350 let mut header = object.header.clone();
351 header.payload_length = VarInt::from_usize(object.payload.len());
352 let mut buf = Vec::new();
353 header.encode_checked_with_extensions(state.carries_extension_block, &mut buf)?;
354 buf.extend_from_slice(&object.payload);
355 self.inner.write_all(&buf).await?;
356 state.previous_object_id = Some(object_id);
357 Ok(())
358 }
359
360 /// Append a draft-13 fetch object (header + payload) to the stream.
361 pub async fn write_fetch_object(
362 &mut self,
363 object: &FetchObject,
364 ) -> Result<(), ConnectionError> {
365 // The declared length comes from the payload rather than from the
366 // caller's field: a header that disagrees with the bytes beside it
367 // desynchronises every object after it on the stream, and nothing
368 // downstream can recover.
369 let mut header = object.header.clone();
370 header.payload_length = VarInt::from_usize(object.payload.len());
371 let mut buf = Vec::new();
372 header.encode_checked(&mut buf)?;
373 buf.extend_from_slice(&object.payload);
374 self.inner.write_all(&buf).await?;
375 Ok(())
376 }
377
378 /// Finish the stream (send FIN).
379 pub async fn finish(&mut self) -> Result<(), ConnectionError> {
380 self.inner.finish()?;
381 Ok(())
382 }
383}
384
385/// What an Object Status makes of an object, for Section 9.2.1.1's table.
386///
387/// `None` is Normal and not "no status": a datagram carrying a payload has no
388/// status field at all, and an object with a payload is an ordinary object.
389fn object_role(status: Option<u64>) -> ObjectRole {
390 match status {
391 None | Some(0x0) => ObjectRole::Produced,
392 // 0x4, end of Track. This draft folded drafts 08 through 10's second
393 // end-of-track status into this one and kept the looser of the two
394 // conditions, so the Group ID may equal the largest group seen.
395 Some(0x4) => ObjectRole::EndsTrack(Some(EndOfTrackForm::LastGroup)),
396 // Every other status is a statement about objects rather than one of
397 // them. Two of them name an Object ID one past the largest on purpose,
398 // so counting one as produced would refuse the end-of-track object the
399 // draft goes on to define.
400 _ => ObjectRole::Neither,
401 }
402}
403
404/// A framed reader for a recv stream. Handles MoQT varint-length decoding.
405pub struct FramedRecvStream {
406 inner: RecvStream,
407 buf: BytesMut,
408 /// The record this stream's objects are measured against, and the Group ID
409 /// its header named.
410 ///
411 /// One group for the whole stream: a subgroup header names it once and no
412 /// object header repeats it. `None` on a stream that was never given one —
413 /// a stream for an alias no live binding names, and every stream built
414 /// outside [`Connection::accept_subgroup_stream`] — and on such a stream
415 /// the objects are read without being measured against the track at all.
416 tracking: Option<(TrackObjects, u64)>,
417 /// Whether the subgroup stream this reader is on carries an extension block
418 /// on every object.
419 ///
420 /// The stream's Type says so and nothing in an object header repeats it, so
421 /// a reader that does not remember the Type cannot parse the objects at all:
422 /// on an extensions-bearing stream it reads the Extension Headers Length as
423 /// the Object Payload Length and every field after it is nonsense.
424 ///
425 /// Set by [`FramedRecvStream::read_subgroup_header`] and read by
426 /// [`FramedRecvStream::read_subgroup_object`]. `false` until a subgroup
427 /// header has been read, which is the only order those two may be called
428 /// in.
429 subgroup_has_extensions: bool,
430 /// The Prior Group ID Gap values this subgroup stream's Objects carried.
431 /// Set by [`FramedRecvStream::read_subgroup_header`].
432 subgroup_gaps: Option<SubgroupGaps>,
433 /// The Prior gap conditions this fetch stream's Objects show. Reset by
434 /// [`FramedRecvStream::read_fetch_header`].
435 fetch_gaps: moqtap_codec::draft13::data_stream::FetchGaps,
436}
437
438impl FramedRecvStream {
439 /// Create a new framed receive stream.
440 pub fn new(inner: RecvStream) -> Self {
441 Self {
442 inner,
443 buf: BytesMut::with_capacity(4096),
444 subgroup_has_extensions: false,
445 subgroup_gaps: None,
446 tracking: None,
447 fetch_gaps: moqtap_codec::draft13::data_stream::FetchGaps::new(),
448 }
449 }
450
451 /// Measure this stream's objects against `objects`, all of them in `group`.
452 ///
453 /// Called by [`Connection::accept_subgroup_stream`] once the header has been
454 /// read, which is the only point at which both the track and the group are
455 /// known.
456 fn measure_objects_against(&mut self, objects: TrackObjects, group: u64) {
457 self.tracking = Some((objects, group));
458 }
459
460 /// Record or judge one object this stream carried.
461 ///
462 /// The whole of Section 9.2.1.1's rule that a single header cannot settle: the
463 /// object's Group ID is the stream's, its Object ID is its own, and what
464 /// they are measured against is everything the track has carried on any
465 /// stream.
466 fn note_subgroup_object(&self, header: &ObjectHeader) -> Result<(), ConnectionError> {
467 let Some((objects, group)) = &self.tracking else { return Ok(()) };
468 let at = ObjectLocation { group: *group, object: header.object_id.into_inner() };
469 objects.note_with_final_object(at, object_role(Some(header.object_status as u64))).map_err(
470 |fault| {
471 ConnectionError::Endpoint(EndpointError::for_track_fault(
472 objects.alias(),
473 at,
474 fault,
475 ))
476 },
477 )
478 }
479
480 /// Get the transport-level stream ID.
481 pub fn stream_id(&self) -> u64 {
482 self.inner.stream_id()
483 }
484
485 /// Read more data from the stream into the internal buffer.
486 async fn fill(&mut self) -> Result<bool, ConnectionError> {
487 let mut tmp = [0u8; 4096];
488 match self.inner.read(&mut tmp).await {
489 Ok(Some(n)) => {
490 self.buf.extend_from_slice(&tmp[..n]);
491 Ok(true)
492 }
493 Ok(None) => Ok(false),
494 Err(e) => Err(ConnectionError::Transport(e)),
495 }
496 }
497
498 /// Ensure at least `n` bytes are available in the buffer.
499 async fn ensure(&mut self, n: usize) -> Result<(), ConnectionError> {
500 while self.buf.len() < n {
501 if !self.fill().await? {
502 return Err(ConnectionError::UnexpectedEnd);
503 }
504 }
505 Ok(())
506 }
507
508 /// Read a control message from the stream.
509 ///
510 /// When `capture_raw` is true, the returned tuple includes a clone of the
511 /// framed wire bytes (for observer emission). When false, the second
512 /// element is `None` and the payload clone is skipped.
513 pub async fn read_control(
514 &mut self,
515 capture_raw: bool,
516 ) -> Result<(AnyControlMessage, Option<Vec<u8>>), ConnectionError> {
517 // Read type ID varint
518 self.ensure(1).await?;
519 let type_len = varint_len(self.buf[0]);
520 self.ensure(type_len).await?;
521
522 let mut cursor = &self.buf[..type_len];
523 let _type_id = VarInt::decode(&mut cursor)?;
524
525 // Draft-13 uses a fixed 16-bit length after the type id.
526 let len_field_size = 2;
527 self.ensure(type_len + len_field_size).await?;
528 let payload_len = u16::from_be_bytes([self.buf[type_len], self.buf[type_len + 1]]) as usize;
529
530 // Read full payload
531 let total = type_len + len_field_size + payload_len;
532 self.ensure(total).await?;
533
534 // Capture raw bytes only if requested (observer attached).
535 let raw = capture_raw.then(|| self.buf[..total].to_vec());
536
537 // Now decode the whole message using the draft-13 dispatcher
538 let mut frame = &self.buf[..total];
539 let msg = AnyControlMessage::decode(DraftVersion::Draft13, &mut frame)?;
540 self.buf.advance(total);
541 Ok((msg, raw))
542 }
543
544 /// Read a subgroup stream header.
545 pub async fn read_subgroup_header(&mut self) -> Result<AnySubgroupHeader, ConnectionError> {
546 self.ensure(1).await?;
547 loop {
548 let mut cursor = &self.buf[..];
549 match AnySubgroupHeader::decode_stream(DraftVersion::Draft13, &mut cursor) {
550 Ok(header) => {
551 let consumed = self.buf.len() - cursor.remaining();
552 self.buf.advance(consumed);
553 // Clippy would rather see these two arms as an `if let`, and rustc rejects
554 // that in a single-draft build, where the pattern is irrefutable. Only a
555 // `match` satisfies both.
556 #[allow(clippy::single_match)]
557 match header {
558 AnySubgroupHeader::Draft13(ref d) => {
559 self.subgroup_has_extensions = d.stream_type.has_extensions();
560 self.subgroup_gaps = Some(SubgroupGaps::new(d));
561 }
562 // Only this draft's header sets the flag. With draft 13 the only enabled
563 // draft `AnySubgroupHeader` has a single variant, the arm above is
564 // exhaustive and this one unreachable. Compiled in every configuration with
565 // the lint allowed, rather than gated on a `cfg` naming every other
566 // draft: such a list has to be edited in every draft module whenever a
567 // draft is added, and a copy that omits one leaves this match
568 // non-exhaustive.
569 #[allow(unreachable_patterns)]
570 _ => {}
571 }
572 return Ok(header);
573 }
574 Err(e) if e.is_incomplete() => {
575 if !self.fill().await? {
576 return Err(ConnectionError::UnexpectedEnd);
577 }
578 }
579 Err(e) => return Err(ConnectionError::Codec(e)),
580 }
581 }
582 }
583
584 /// Read a fetch response header.
585 pub async fn read_fetch_header(&mut self) -> Result<AnyFetchHeader, ConnectionError> {
586 self.ensure(1).await?;
587 loop {
588 let mut cursor = &self.buf[..];
589 match AnyFetchHeader::decode_stream(DraftVersion::Draft13, &mut cursor) {
590 Ok(header) => {
591 let consumed = self.buf.len() - cursor.remaining();
592 self.buf.advance(consumed);
593 self.fetch_gaps = moqtap_codec::draft13::data_stream::FetchGaps::new();
594 return Ok(header);
595 }
596 Err(e) if e.is_incomplete() => {
597 if !self.fill().await? {
598 return Err(ConnectionError::UnexpectedEnd);
599 }
600 }
601 Err(e) => return Err(ConnectionError::Codec(e)),
602 }
603 }
604 }
605
606 /// Read the next draft-13 subgroup object (header + payload).
607 ///
608 /// Whether an object carries an extension block is a property of the
609 /// stream's Type, not of the object, so this reads it from the header
610 /// [`FramedRecvStream::read_subgroup_header`] recorded rather than assuming
611 /// either answer. Assuming "no extensions" is not a conservative default: on
612 /// a stream whose Type announces them the Extension Headers Length is read
613 /// as the Object Payload Length, and every object on the stream comes back
614 /// wrong instead of being refused.
615 ///
616 /// It is also what puts the rule binding extension headers to Object Status
617 /// within reach on a subgroup stream. A reader that never reads the block
618 /// cannot notice that a non-existent Object carried one.
619 ///
620 /// A Prior Group ID Gap larger than the stream's Group ID, or gaps that
621 /// leave no value common to every Object on the stream that carried one,
622 /// are returned as [`CodecError::MalformedTrack`] (draft-13 Section 10.1);
623 /// [`Connection::withdraw_for_subgroup_stream`] withdraws from the track.
624 pub async fn read_subgroup_object(&mut self) -> Result<SubgroupObject, ConnectionError> {
625 loop {
626 let mut cursor = &self.buf[..];
627 match ObjectHeader::decode_with_extensions(self.subgroup_has_extensions, &mut cursor) {
628 Ok(header) => {
629 let header_consumed = self.buf.len() - cursor.remaining();
630 let payload_len = header.payload_length.into_inner() as usize;
631 let total = header_consumed + payload_len;
632 if self.buf.len() < total {
633 if !self.fill().await? {
634 return Err(ConnectionError::UnexpectedEnd);
635 }
636 continue;
637 }
638 if let Some(gaps) = &mut self.subgroup_gaps {
639 gaps.check(&header).map_err(ConnectionError::Codec)?;
640 }
641 let payload = self.buf[header_consumed..total].to_vec();
642 self.buf.advance(total);
643 self.note_subgroup_object(&header)?;
644 return Ok(SubgroupObject { header, payload });
645 }
646 Err(e) if e.is_incomplete() => {
647 if !self.fill().await? {
648 return Err(ConnectionError::UnexpectedEnd);
649 }
650 }
651 Err(e) => return Err(ConnectionError::Codec(e)),
652 }
653 }
654 }
655
656 /// Read the next draft-13 fetch object (header + payload).
657 ///
658 /// A Prior Group ID Gap fault the stream shows (draft-13 Section 10.1) is
659 /// returned as [`CodecError::MalformedTrack`], and an extension block that
660 /// does not parse as [`CodecError::MalformedObjectProperties`].
661 /// [`Connection::withdraw_for_fetch_stream`] withdraws from the track over the
662 /// first; this draft states no Malformed Track condition for the second.
663 pub async fn read_fetch_object(&mut self) -> Result<FetchObject, ConnectionError> {
664 loop {
665 let mut cursor = &self.buf[..];
666 match FetchObjectHeader::decode(&mut cursor) {
667 Ok(header) => {
668 let header_consumed = self.buf.len() - cursor.remaining();
669 let payload_len = header.payload_length.into_inner() as usize;
670 let total = header_consumed + payload_len;
671 if self.buf.len() < total {
672 if !self.fill().await? {
673 return Err(ConnectionError::UnexpectedEnd);
674 }
675 continue;
676 }
677 let payload = self.buf[header_consumed..total].to_vec();
678 self.buf.advance(total);
679 self.fetch_gaps
680 .check(
681 header.group_id.into_inner(),
682 header.object_id.into_inner(),
683 &header.extensions,
684 )
685 .map_err(ConnectionError::Codec)?;
686 return Ok(FetchObject { header, payload });
687 }
688 Err(e) if e.is_incomplete() => {
689 if !self.fill().await? {
690 return Err(ConnectionError::UnexpectedEnd);
691 }
692 }
693 Err(e) => return Err(ConnectionError::Codec(e)),
694 }
695 }
696 }
697}
698
699/// A live draft-13 MoQT connection over QUIC or WebTransport.
700pub struct Connection {
701 transport: Transport,
702 endpoint: Endpoint,
703 /// Behind a lock because a control message is written from two kinds of
704 /// place. Most of them are the caller's own request, made through `&mut
705 /// self`. The UNSUBSCRIBE that answers a Malformed Track is not: the
706 /// conditions that make a track malformed are detected on the data plane,
707 /// where this connection is reached through a shared reference. The lock
708 /// also makes one message the unit of writing, so two of them cannot
709 /// interleave on the stream.
710 control_send: Option<tokio::sync::Mutex<FramedSendStream>>,
711 control_recv: Option<FramedRecvStream>,
712 observer: Option<Box<dyn ConnectionObserver>>,
713 /// Setup events buffered during `connect()` and replayed when an
714 /// observer attaches via `set_observer` — without this, an observer
715 /// attached after `connect` returns would never see the handshake.
716 pending_events: Vec<ClientEvent>,
717 /// The server's half of the setup handshake, kept whole.
718 ///
719 /// The endpoint acts on the parameters it recognises and retains none of
720 /// them, and which parameters a server sends — in what order, with what
721 /// values — is the sharpest thing a session says about the implementation
722 /// behind it.
723 server_setup: AnyControlMessage,
724 /// The framed wire bytes of [`Self::server_setup`].
725 server_setup_raw: Option<Vec<u8>>,
726}
727
728impl Connection {
729 /// Connect to a draft-13 MoQT server as a client.
730 pub async fn connect(addr: &str, config: ClientConfig) -> Result<Self, ConnectionError> {
731 // PATH is for native QUIC only, and the transport is known here and
732 // nowhere further in. Refusing before dialling means a session that
733 // the server would close on sight is never opened.
734 setup::validate_client_path_transport(
735 &config.setup_parameters,
736 matches!(config.transport, TransportType::WebTransport { .. }),
737 )
738 .map_err(EndpointError::from)?;
739
740 let transport = match &config.transport {
741 TransportType::Quic => Self::connect_quic(addr, &config).await?,
742 TransportType::WebTransport { url } => {
743 let url = url.clone();
744 Self::connect_webtransport(&url, &config).await?
745 }
746 };
747
748 Self::adopt(transport, config).await
749 }
750
751 /// Run the MoQT setup handshake over a transport somebody else established.
752 ///
753 /// For choosing the draft from what the server selected: dial once through
754 /// [`crate::transport::dial_quic`] offering every ALPN, then bring the
755 /// connection to the module its answer names. [`Self::connect`] cannot do
756 /// this — it derives its single ALPN from the draft it was given.
757 ///
758 /// `config.draft` must match this module. The transport is adopted as
759 /// given; nothing here re-checks the ALPN it was negotiated with.
760 pub async fn adopt(
761 transport: Transport,
762 config: ClientConfig,
763 ) -> Result<Self, ConnectionError> {
764 Self::adopt_offering(transport, config, None).await
765 }
766
767 /// [`Self::adopt`], offering exactly `versions` in CLIENT_SETUP.
768 ///
769 /// `None` offers what `config` implies, which is what [`Self::adopt`]
770 /// passes. `Some` replaces the list outright, and takes raw varints rather
771 /// than [`DraftVersion`]s because the reason to reach for this is to offer
772 /// a version no draft assigns — which an enum of drafts cannot name.
773 ///
774 /// A server MUST answer with a version the client offered and MUST
775 /// otherwise close the session; from draft-11 the code for that is
776 /// `VERSION_NEGOTIATION_FAILED` (0x15). How a relay spells the refusal is
777 /// a conformance measurement, and offering a version deliberately outside
778 /// the negotiable set is the only way to ask for it.
779 pub async fn adopt_offering(
780 transport: Transport,
781 config: ClientConfig,
782 versions: Option<Vec<VarInt>>,
783 ) -> Result<Self, ConnectionError> {
784 // PATH is for native QUIC only, and the transport is known here and
785 // nowhere further in. Refusing before dialling means a session that
786 // the server would close on sight is never opened.
787 setup::validate_client_path_transport(
788 &config.setup_parameters,
789 matches!(config.transport, TransportType::WebTransport { .. }),
790 )
791 .map_err(EndpointError::from)?;
792
793 // Open bidirectional control stream
794 let (send, recv) = transport.open_bi().await?;
795 let mut control_send = FramedSendStream::new(send);
796 let mut control_recv = FramedRecvStream::new(recv);
797
798 // Perform setup handshake
799 let mut endpoint = Endpoint::new(Role::Client);
800 endpoint.connect()?;
801 let setup_msg = endpoint.send_client_setup(
802 versions.unwrap_or_else(|| config.supported_versions()),
803 config.setup_parameters.clone(),
804 )?;
805 let any_setup = AnyControlMessage::Draft13(setup_msg);
806 let raw_setup = control_send.write_control(&any_setup).await?;
807
808 let (server_setup, raw_server_setup) = control_recv.read_control(true).await?;
809 match &server_setup {
810 AnyControlMessage::Draft13(ControlMessage::ServerSetup(ref ss)) => {
811 endpoint.receive_server_setup(ss)?;
812 }
813 _ => {
814 return Err(ConnectionError::Endpoint(EndpointError::NotActive));
815 }
816 }
817
818 let mut pending_events = Vec::with_capacity(3);
819 pending_events.push(ClientEvent::ControlMessage {
820 direction: Direction::Send,
821 message: any_setup,
822 raw: Some(raw_setup),
823 });
824 pending_events.push(ClientEvent::ControlMessage {
825 direction: Direction::Receive,
826 message: server_setup.clone(),
827 raw: raw_server_setup.clone(),
828 });
829 if let Some(v) = endpoint.negotiated_version() {
830 pending_events.push(ClientEvent::SetupComplete { negotiated_version: v.into_inner() });
831 }
832
833 Ok(Self {
834 transport,
835 endpoint,
836 control_send: Some(tokio::sync::Mutex::new(control_send)),
837 control_recv: Some(control_recv),
838 observer: None,
839 pending_events,
840 server_setup,
841 server_setup_raw: raw_server_setup,
842 })
843 }
844
845 /// Establish a raw QUIC connection.
846 ///
847 /// Offers this draft's ALPN alone; [`crate::transport::dial_quic`] holds the
848 /// TLS and endpoint setup.
849 async fn connect_quic(addr: &str, config: &ClientConfig) -> Result<Transport, ConnectionError> {
850 let (transport, _negotiated) = crate::transport::dial_quic(
851 addr,
852 &crate::transport::QuicDialOptions {
853 skip_cert_verification: config.skip_cert_verification,
854 ca_certs: config.ca_certs.clone(),
855 ..crate::transport::QuicDialOptions::new(config.alpn())
856 },
857 )
858 .await?;
859 Ok(transport)
860 }
861
862 /// Establish a WebTransport connection.
863 ///
864 /// [`crate::transport::dial_webtransport`] holds the TLS and endpoint
865 /// setup, exactly as `connect_quic` above defers its own. That is not
866 /// only deduplication: both dials hand the same `QuicDialOptions` to the
867 /// same config constructor in `transport::quic`, so the bundled roots and
868 /// `config.ca_certs` are what each of them trusts and one relay gets one
869 /// verdict whichever transport carries it. Settling trust at this call site
870 /// instead — from `wtransport`'s own builder settings, or from a second
871 /// config of this draft's own — puts the decision in two places, and a
872 /// caller's private CA then reaches only the dials whose call site
873 /// installed it.
874 #[cfg(feature = "webtransport")]
875 async fn connect_webtransport(
876 url: &str,
877 config: &ClientConfig,
878 ) -> Result<Transport, ConnectionError> {
879 Ok(crate::transport::dial_webtransport(
880 url,
881 &crate::transport::QuicDialOptions {
882 skip_cert_verification: config.skip_cert_verification,
883 ca_certs: config.ca_certs.clone(),
884 ..crate::transport::QuicDialOptions::new(config.alpn())
885 },
886 )
887 .await?)
888 }
889
890 /// Stub for when the webtransport feature is not enabled.
891 #[cfg(not(feature = "webtransport"))]
892 async fn connect_webtransport(
893 _url: &str,
894 _config: &ClientConfig,
895 ) -> Result<Transport, ConnectionError> {
896 Err(ConnectionError::Transport(TransportError::Connect(
897 "webtransport feature not enabled".into(),
898 )))
899 }
900
901 // ── Observer ───────────────────────────────────────────────
902
903 /// Attach an observer. Buffered handshake events from `connect()` are
904 /// flushed in arrival order before this returns.
905 pub fn set_observer(&mut self, observer: Box<dyn ConnectionObserver>) {
906 self.observer = Some(observer);
907 for event in self.pending_events.drain(..) {
908 if let Some(ref obs) = self.observer {
909 obs.on_event_owned(event);
910 }
911 }
912 }
913
914 /// Remove the observer.
915 pub fn clear_observer(&mut self) {
916 self.observer = None;
917 }
918
919 /// Emit an event to the observer, if one is attached.
920 fn emit(&self, event: ClientEvent) {
921 if let Some(ref obs) = self.observer {
922 obs.on_event_owned(event);
923 }
924 }
925
926 // ── Control message I/O ─────────────────────────────────
927
928 /// Send a control message on the control stream.
929 pub async fn send_control(&self, msg: &ControlMessage) -> Result<(), ConnectionError> {
930 let any = AnyControlMessage::Draft13(msg.clone());
931 let mut send =
932 self.control_send.as_ref().ok_or(ConnectionError::NoControlStream)?.lock().await;
933 let raw = send.write_control(&any).await?;
934 drop(send);
935 self.emit(ClientEvent::ControlMessage {
936 direction: Direction::Send,
937 message: any,
938 raw: Some(raw),
939 });
940 Ok(())
941 }
942
943 /// Read the next control message from the control stream.
944 pub async fn recv_control(&mut self) -> Result<ControlMessage, ConnectionError> {
945 let recv = self.control_recv.as_mut().ok_or(ConnectionError::NoControlStream)?;
946 let capture_raw = self.observer.is_some();
947 let (any, raw) = match recv.read_control(capture_raw).await {
948 Ok(v) => v,
949 Err(e) => return Err(self.close_for_codec(e)),
950 };
951 if capture_raw {
952 self.emit(ClientEvent::ControlMessage {
953 direction: Direction::Receive,
954 message: any.clone(),
955 raw,
956 });
957 }
958 match any {
959 AnyControlMessage::Draft13(msg) => Ok(msg),
960 // `AnyControlMessage` carries one variant per enabled draft feature. With draft 13 the
961 // only one enabled the arm above is exhaustive and this rejection arm unreachable.
962 // Compiled in every configuration with the lint allowed, rather than gated on a `cfg`
963 // naming the other drafts: such a list has to be edited in every draft
964 // module whenever a draft is added, and a copy that omits one leaves this match
965 // non-exhaustive.
966 #[allow(unreachable_patterns)]
967 _ => Err(ConnectionError::ControlMessageNarrowing),
968 }
969 }
970
971 /// Read and dispatch the next incoming control message through the endpoint
972 /// state machine. Returns the decoded message for inspection.
973 pub async fn recv_and_dispatch(&mut self) -> Result<ControlMessage, ConnectionError> {
974 let msg = self.recv_control().await?;
975 self.endpoint.receive_message(msg.clone()).map_err(|e| self.close_if_session_fatal(e))?;
976
977 if let ControlMessage::GoAway(ref ga) = msg {
978 self.emit(ClientEvent::Draining { new_session_uri: ga.new_session_uri.clone() });
979 }
980
981 Ok(msg)
982 }
983
984 // ── Subscribe flow ──────────────────────────────────────
985
986 /// Send a SUBSCRIBE and return the allocated request ID.
987 ///
988 /// Draft-12: the subscriber no longer chooses a track alias. The alias is
989 /// returned by the publisher in SUBSCRIBE_OK and can be retrieved later
990 /// from the endpoint via `endpoint().track_alias_for(request_id)`.
991 pub async fn subscribe(
992 &mut self,
993 track_namespace: TrackNamespace,
994 track_name: Vec<u8>,
995 subscriber_priority: u8,
996 group_order: GroupOrder,
997 filter_type: FilterType,
998 parameters: Vec<KeyValuePair>,
999 ) -> Result<VarInt, ConnectionError> {
1000 let (req_id, msg) = self.endpoint.subscribe(
1001 track_namespace,
1002 track_name,
1003 subscriber_priority,
1004 group_order,
1005 filter_type,
1006 parameters,
1007 )?;
1008 self.send_control(&msg).await?;
1009 Ok(req_id)
1010 }
1011
1012 /// Send a SUBSCRIBE for a range of the track, starting at a given
1013 /// location.
1014 ///
1015 /// The Filter Type is derived from the range, so the message cannot name a
1016 /// filter whose fields it does not carry.
1017 #[allow(clippy::too_many_arguments)]
1018 pub async fn subscribe_range(
1019 &mut self,
1020 track_namespace: TrackNamespace,
1021 track_name: Vec<u8>,
1022 subscriber_priority: u8,
1023 group_order: GroupOrder,
1024 start_location: Location,
1025 end_group: Option<VarInt>,
1026 parameters: Vec<KeyValuePair>,
1027 ) -> Result<VarInt, ConnectionError> {
1028 let (req_id, msg) = self.endpoint.subscribe_range(
1029 track_namespace,
1030 track_name,
1031 subscriber_priority,
1032 group_order,
1033 start_location,
1034 end_group,
1035 parameters,
1036 )?;
1037 self.send_control(&msg).await?;
1038 Ok(req_id)
1039 }
1040
1041 /// Send an UNSUBSCRIBE for the given request ID.
1042 pub async fn unsubscribe(&mut self, request_id: VarInt) -> Result<(), ConnectionError> {
1043 let msg = self.endpoint.unsubscribe(request_id)?;
1044 self.send_control(&msg).await
1045 }
1046
1047 /// Accept a subscription the peer opened, sending SUBSCRIBE_OK and giving
1048 /// its track a Track Alias.
1049 ///
1050 /// The endpoint refuses an alias a live track of its own already holds and
1051 /// refuses a second answer to one SUBSCRIBE, so nothing is written on the
1052 /// wire when it does either.
1053 pub async fn subscribe_ok(
1054 &mut self,
1055 request_id: VarInt,
1056 track_alias: VarInt,
1057 expires: VarInt,
1058 group_order: GroupOrder,
1059 parameters: Vec<KeyValuePair>,
1060 ) -> Result<(), ConnectionError> {
1061 let msg = self.endpoint.send_subscribe_ok(
1062 request_id,
1063 track_alias,
1064 expires,
1065 group_order,
1066 parameters,
1067 )?;
1068 self.send_control(&msg).await
1069 }
1070
1071 /// Reject a subscription the peer opened, sending SUBSCRIBE_ERROR.
1072 ///
1073 /// The endpoint refuses a second answer to one SUBSCRIBE, so nothing is
1074 /// written on the wire when it does.
1075 pub async fn subscribe_error(
1076 &mut self,
1077 request_id: VarInt,
1078 error_code: VarInt,
1079 reason_phrase: Vec<u8>,
1080 ) -> Result<(), ConnectionError> {
1081 let msg = self.endpoint.send_subscribe_error(request_id, error_code, reason_phrase)?;
1082 self.send_control(&msg).await
1083 }
1084
1085 /// End a subscription this endpoint accepted, sending SUBSCRIBE_DONE.
1086 pub async fn subscribe_done(
1087 &mut self,
1088 request_id: VarInt,
1089 status_code: VarInt,
1090 stream_count: VarInt,
1091 reason_phrase: Vec<u8>,
1092 ) -> Result<(), ConnectionError> {
1093 let msg = self.endpoint.send_subscribe_done(
1094 request_id,
1095 status_code,
1096 stream_count,
1097 reason_phrase,
1098 )?;
1099 self.send_control(&msg).await
1100 }
1101
1102 /// Narrow a subscription this endpoint opened, sending SUBSCRIBE_UPDATE.
1103 ///
1104 /// No Request ID is spent: on this draft the message's one identifier
1105 /// field names the subscription it modifies.
1106 #[allow(clippy::too_many_arguments)]
1107 pub async fn subscribe_update(
1108 &mut self,
1109 request_id: VarInt,
1110 start_group: VarInt,
1111 start_object: VarInt,
1112 end_group: VarInt,
1113 subscriber_priority: u8,
1114 forward: Forward,
1115 parameters: Vec<KeyValuePair>,
1116 ) -> Result<(), ConnectionError> {
1117 let msg = self.endpoint.subscribe_update(
1118 request_id,
1119 start_group,
1120 start_object,
1121 end_group,
1122 subscriber_priority,
1123 forward,
1124 parameters,
1125 )?;
1126 self.send_control(&msg).await
1127 }
1128
1129 /// Offer the peer a subscription to a track this endpoint publishes, and
1130 /// return the Request ID the offer was allocated.
1131 ///
1132 /// Nothing is written on the wire when the endpoint refuses to build the
1133 /// offer, which it does when the Track Alias is one another live track of
1134 /// this session already holds.
1135 #[allow(clippy::too_many_arguments)]
1136 pub async fn publish(
1137 &mut self,
1138 track_namespace: TrackNamespace,
1139 track_name: Vec<u8>,
1140 track_alias: VarInt,
1141 group_order: GroupOrder,
1142 largest_location: Option<Location>,
1143 forward: Forward,
1144 parameters: Vec<KeyValuePair>,
1145 ) -> Result<VarInt, ConnectionError> {
1146 let (req_id, msg) = self.endpoint.publish(
1147 track_namespace,
1148 track_name,
1149 track_alias,
1150 group_order,
1151 largest_location,
1152 forward,
1153 parameters,
1154 )?;
1155 self.send_control(&msg).await?;
1156 Ok(req_id)
1157 }
1158
1159 /// Accept a PUBLISH the peer sent, which establishes the subscription it
1160 /// opened.
1161 ///
1162 /// The endpoint refuses a second answer to one PUBLISH, so nothing is
1163 /// written on the wire when it does.
1164 #[allow(clippy::too_many_arguments)]
1165 pub async fn publish_ok(
1166 &mut self,
1167 request_id: VarInt,
1168 forward: Forward,
1169 subscriber_priority: u8,
1170 group_order: GroupOrder,
1171 filter_type: FilterType,
1172 start_group: Option<VarInt>,
1173 start_object: Option<VarInt>,
1174 end_group: Option<VarInt>,
1175 ) -> Result<(), ConnectionError> {
1176 let msg = self.endpoint.send_publish_ok(
1177 request_id,
1178 forward,
1179 subscriber_priority,
1180 group_order,
1181 filter_type,
1182 start_group,
1183 start_object,
1184 end_group,
1185 )?;
1186 self.send_control(&msg).await
1187 }
1188
1189 /// Reject a PUBLISH the peer sent, which ends the subscription it opened
1190 /// before it was established.
1191 ///
1192 /// The endpoint refuses a second answer to one PUBLISH, so nothing is
1193 /// written on the wire when it does.
1194 pub async fn publish_error(
1195 &mut self,
1196 request_id: VarInt,
1197 error_code: VarInt,
1198 reason_phrase: Vec<u8>,
1199 ) -> Result<(), ConnectionError> {
1200 let msg = self.endpoint.send_publish_error(request_id, error_code, reason_phrase)?;
1201 self.send_control(&msg).await
1202 }
1203
1204 // ── Fetch flow ──────────────────────────────────────────
1205
1206 /// Send a FETCH and return the allocated request ID.
1207 #[allow(clippy::too_many_arguments)]
1208 pub async fn fetch(
1209 &mut self,
1210 track_namespace: TrackNamespace,
1211 track_name: Vec<u8>,
1212 subscriber_priority: u8,
1213 group_order: GroupOrder,
1214 start_group: VarInt,
1215 start_object: VarInt,
1216 end_group: VarInt,
1217 end_object: VarInt,
1218 parameters: Vec<KeyValuePair>,
1219 ) -> Result<VarInt, ConnectionError> {
1220 let (req_id, msg) = self.endpoint.fetch(
1221 track_namespace,
1222 track_name,
1223 subscriber_priority,
1224 group_order,
1225 start_group,
1226 start_object,
1227 end_group,
1228 end_object,
1229 parameters,
1230 )?;
1231 self.send_control(&msg).await?;
1232 Ok(req_id)
1233 }
1234
1235 /// Send a Relative Joining Fetch and return the allocated request ID.
1236 ///
1237 /// `joining_start` counts groups back from the live edge of the
1238 /// subscription it names. Section 8.16.1 computes the range from "the
1239 /// Preceding Group Offset", which is this field under the name it carried
1240 /// two drafts ago; the field list calls it Joining Start and says that for
1241 /// a Relative Joining Fetch "a value of 0 indicates the Fetch starts at
1242 /// the beginning of the Current Group". For the form that names the group
1243 /// outright, see
1244 /// [`absolute_joining_fetch`](Self::absolute_joining_fetch).
1245 pub async fn joining_fetch(
1246 &mut self,
1247 subscriber_priority: u8,
1248 group_order: GroupOrder,
1249 joining_request_id: VarInt,
1250 joining_start: VarInt,
1251 parameters: Vec<KeyValuePair>,
1252 ) -> Result<VarInt, ConnectionError> {
1253 let (req_id, msg) = self.endpoint.joining_fetch(
1254 subscriber_priority,
1255 group_order,
1256 joining_request_id,
1257 joining_start,
1258 parameters,
1259 )?;
1260 self.send_control(&msg).await?;
1261 Ok(req_id)
1262 }
1263
1264 /// Send an Absolute Joining Fetch and return the allocated request ID.
1265 ///
1266 /// `joining_start` is the group to begin at. Section 8.16 has an Absolute
1267 /// Joining Fetch "Identical to a Relative Joining Fetch except that the
1268 /// Start Group is determined by an absolute Group value rather than a
1269 /// relative offset to the subscription", so a subscriber that knows the
1270 /// group it wants can ask for it without first being told a Largest
1271 /// Location to count back from.
1272 ///
1273 /// Two calls rather than one taking a Fetch Type, because these are the
1274 /// only two the joining form admits. The endpoint is named the same way,
1275 /// so no call between an application and the wire has a Fetch Type in it
1276 /// to be given a wrong one.
1277 pub async fn absolute_joining_fetch(
1278 &mut self,
1279 subscriber_priority: u8,
1280 group_order: GroupOrder,
1281 joining_request_id: VarInt,
1282 joining_start: VarInt,
1283 parameters: Vec<KeyValuePair>,
1284 ) -> Result<VarInt, ConnectionError> {
1285 let (req_id, msg) = self.endpoint.absolute_joining_fetch(
1286 subscriber_priority,
1287 group_order,
1288 joining_request_id,
1289 joining_start,
1290 parameters,
1291 )?;
1292 self.send_control(&msg).await?;
1293 Ok(req_id)
1294 }
1295
1296 /// Send a FETCH_CANCEL for the given request ID.
1297 pub async fn fetch_cancel(&mut self, request_id: VarInt) -> Result<(), ConnectionError> {
1298 let msg = self.endpoint.fetch_cancel(request_id)?;
1299 self.send_control(&msg).await
1300 }
1301
1302 /// Accept a fetch the peer opened, sending FETCH_OK.
1303 ///
1304 /// The endpoint refuses a Joining Fetch naming a subscription this session
1305 /// cannot join and refuses a second answer to one FETCH, so nothing is
1306 /// written on the wire when it does either.
1307 pub async fn fetch_ok(
1308 &mut self,
1309 request_id: VarInt,
1310 group_order: GroupOrder,
1311 end_of_track: u8,
1312 end_location: Location,
1313 parameters: Vec<KeyValuePair>,
1314 ) -> Result<(), ConnectionError> {
1315 let msg = self.endpoint.send_fetch_ok(
1316 request_id,
1317 group_order,
1318 end_of_track,
1319 end_location,
1320 parameters,
1321 )?;
1322 self.send_control(&msg).await
1323 }
1324
1325 /// Refuse a fetch the peer opened, sending FETCH_ERROR.
1326 ///
1327 /// The endpoint refuses a second answer to one FETCH, and refuses a
1328 /// Joining Fetch's refusal under any code but the one the draft names for
1329 /// it, so nothing is written on the wire when it does either.
1330 pub async fn fetch_error(
1331 &mut self,
1332 request_id: VarInt,
1333 error_code: VarInt,
1334 reason_phrase: Vec<u8>,
1335 ) -> Result<(), ConnectionError> {
1336 let msg = self.endpoint.send_fetch_error(request_id, error_code, reason_phrase)?;
1337 self.send_control(&msg).await
1338 }
1339
1340 // ── Namespace flows ─────────────────────────────────────
1341
1342 /// Send a SUBSCRIBE_NAMESPACE. Returns the allocated request ID.
1343 pub async fn subscribe_namespace(
1344 &mut self,
1345 track_namespace_prefix: TrackNamespace,
1346 parameters: Vec<KeyValuePair>,
1347 ) -> Result<VarInt, ConnectionError> {
1348 let (req_id, msg) =
1349 self.endpoint.subscribe_namespace(track_namespace_prefix, parameters)?;
1350 self.send_control(&msg).await?;
1351 Ok(req_id)
1352 }
1353
1354 /// Accept a namespace subscription the peer made, sending SUBSCRIBE_NAMESPACE_OK.
1355 ///
1356 /// The endpoint refuses a second answer to one SUBSCRIBE_NAMESPACE, so nothing is
1357 /// written on the wire when it does.
1358 pub async fn subscribe_namespace_ok(
1359 &mut self,
1360 request_id: VarInt,
1361 ) -> Result<(), ConnectionError> {
1362 let msg = self.endpoint.send_subscribe_namespace_ok(request_id)?;
1363 self.send_control(&msg).await
1364 }
1365
1366 /// Refuse a namespace subscription the peer made, sending SUBSCRIBE_NAMESPACE_ERROR.
1367 ///
1368 /// The other half of the same sentence: one answer, and this is the other
1369 /// one it can be.
1370 pub async fn subscribe_namespace_error(
1371 &mut self,
1372 request_id: VarInt,
1373 error_code: VarInt,
1374 reason_phrase: Vec<u8>,
1375 ) -> Result<(), ConnectionError> {
1376 let msg =
1377 self.endpoint.send_subscribe_namespace_error(request_id, error_code, reason_phrase)?;
1378 self.send_control(&msg).await
1379 }
1380
1381 /// Send an ANNOUNCE. Returns the allocated request ID.
1382 pub async fn announce(
1383 &mut self,
1384 track_namespace: TrackNamespace,
1385 parameters: Vec<KeyValuePair>,
1386 ) -> Result<VarInt, ConnectionError> {
1387 let (req_id, msg) = self.endpoint.announce(track_namespace, parameters)?;
1388 self.send_control(&msg).await?;
1389 Ok(req_id)
1390 }
1391
1392 /// Send an UNANNOUNCE.
1393 pub async fn unannounce(
1394 &mut self,
1395 track_namespace: TrackNamespace,
1396 ) -> Result<(), ConnectionError> {
1397 let msg = self.endpoint.unannounce(track_namespace)?;
1398 self.send_control(&msg).await
1399 }
1400
1401 /// Accept an announcement the peer made, sending ANNOUNCE_OK.
1402 ///
1403 /// The endpoint refuses a second answer to one ANNOUNCE, so nothing is
1404 /// written on the wire when it does.
1405 pub async fn announce_ok(&mut self, request_id: VarInt) -> Result<(), ConnectionError> {
1406 let msg = self.endpoint.send_announce_ok(request_id)?;
1407 self.send_control(&msg).await
1408 }
1409
1410 /// Refuse an announcement the peer made, sending ANNOUNCE_ERROR.
1411 ///
1412 /// The other half of the same sentence: one answer, and this is the other
1413 /// one it can be.
1414 pub async fn announce_error(
1415 &mut self,
1416 request_id: VarInt,
1417 error_code: VarInt,
1418 reason_phrase: Vec<u8>,
1419 ) -> Result<(), ConnectionError> {
1420 let msg = self.endpoint.send_announce_error(request_id, error_code, reason_phrase)?;
1421 self.send_control(&msg).await
1422 }
1423
1424 /// Revoke an acceptance, sending ANNOUNCE_CANCEL.
1425 ///
1426 /// The endpoint refuses one for an announcement it never accepted, so
1427 /// nothing is written on the wire when it does.
1428 pub async fn announce_cancel(
1429 &mut self,
1430 track_namespace: TrackNamespace,
1431 error_code: VarInt,
1432 reason_phrase: Vec<u8>,
1433 ) -> Result<(), ConnectionError> {
1434 let msg = self.endpoint.announce_cancel(track_namespace, error_code, reason_phrase)?;
1435 self.send_control(&msg).await
1436 }
1437 // ── Track Status flow ────────────────────────────────────
1438
1439 /// Send a TRACK_STATUS (draft-13 subscribe-like request).
1440 /// Returns the allocated request ID.
1441 #[allow(clippy::too_many_arguments)]
1442 pub async fn track_status(
1443 &mut self,
1444 track_namespace: TrackNamespace,
1445 track_name: Vec<u8>,
1446 subscriber_priority: u8,
1447 group_order: GroupOrder,
1448 forward: Forward,
1449 filter_type: FilterType,
1450 parameters: Vec<KeyValuePair>,
1451 ) -> Result<VarInt, ConnectionError> {
1452 let (req_id, msg) = self.endpoint.track_status(
1453 track_namespace,
1454 track_name,
1455 subscriber_priority,
1456 group_order,
1457 forward,
1458 filter_type,
1459 parameters,
1460 )?;
1461 self.send_control(&msg).await?;
1462 Ok(req_id)
1463 }
1464
1465 /// Accept a track status the peer asked for, sending TRACK_STATUS_OK.
1466 ///
1467 /// The endpoint refuses a second answer to one request, so nothing is
1468 /// written on the wire when it does. It also chooses the Track Alias the
1469 /// message carries, because the draft leaves only one value open.
1470 pub async fn track_status_ok(
1471 &mut self,
1472 request_id: VarInt,
1473 expires: VarInt,
1474 group_order: GroupOrder,
1475 parameters: Vec<KeyValuePair>,
1476 ) -> Result<(), ConnectionError> {
1477 let msg =
1478 self.endpoint.send_track_status_ok(request_id, expires, group_order, parameters)?;
1479 self.send_control(&msg).await
1480 }
1481
1482 /// Refuse a track status the peer asked for, sending TRACK_STATUS_ERROR.
1483 ///
1484 /// The other answer the request can have, and the endpoint holds it to the
1485 /// same count of one.
1486 pub async fn track_status_error(
1487 &mut self,
1488 request_id: VarInt,
1489 error_code: VarInt,
1490 reason_phrase: Vec<u8>,
1491 ) -> Result<(), ConnectionError> {
1492 let msg = self.endpoint.send_track_status_error(request_id, error_code, reason_phrase)?;
1493 self.send_control(&msg).await
1494 }
1495
1496 // ── Malformed Tracks ────────────────────────────────────
1497
1498 /// Answer Section 2.5 for the track `alias` names: withdraw from it, and
1499 /// send the UNSUBSCRIBE that withdrawal is.
1500 ///
1501 /// "When a subscriber detects a Malformed Track, it MUST UNSUBSCRIBE from
1502 /// the Track and SHOULD deliver an error to the application." The caller
1503 /// delivers the error by returning it; this is the other half, and the
1504 /// caller does not have to remember to ask for it.
1505 ///
1506 /// Nothing here ends the session, and that is the point of it. The
1507 /// conditions in Section 2.5 are answered by giving up one track.
1508 ///
1509 /// # Why a write that fails is not reported
1510 ///
1511 /// The error the caller is about to receive is the one that says what
1512 /// went wrong with the track. A control stream that will not take an
1513 /// UNSUBSCRIBE is a session on its way out for a reason of its own, and
1514 /// replacing the condition's report with a transport error would lose the
1515 /// only account of why the track was withdrawn. The rest of the
1516 /// withdrawal is abandoned, because a stream that refused one message
1517 /// will refuse the next.
1518 async fn withdraw_malformed_track(&self, alias: u64, condition: MalformedTrackCondition) {
1519 for msg in self.endpoint.withdraw_malformed_track(alias, condition) {
1520 if self.send_control(&msg).await.is_err() {
1521 break;
1522 }
1523 }
1524 }
1525
1526 /// [`Self::withdraw_malformed_track`] for the track the FETCH `request_id`
1527 /// asked for.
1528 async fn withdraw_malformed_fetch_track(
1529 &self,
1530 request_id: u64,
1531 condition: MalformedTrackCondition,
1532 ) {
1533 for msg in self.endpoint.withdraw_malformed_fetch_track(request_id, condition) {
1534 if self.send_control(&msg).await.is_err() {
1535 break;
1536 }
1537 }
1538 }
1539
1540 /// Record the framing an arriving object was sent with, and withdraw from
1541 /// the track when it is the second framing that track has been sent.
1542 ///
1543 /// The receiving half of a pair. The two writing paths call the endpoint
1544 /// directly and answer a mixed track by refusing to write it, because
1545 /// Section 2.5's sentence is a subscriber's: an endpoint about to send an
1546 /// object is that object's Original Publisher, and a publisher has no
1547 /// subscription of its own to withdraw.
1548 async fn note_received_framing(
1549 &self,
1550 alias: u64,
1551 seen: ObjectForwardingPreference,
1552 ) -> Result<(), ConnectionError> {
1553 let Err(err) = self.endpoint.note_object_forwarding_preference(alias, seen) else {
1554 return Ok(());
1555 };
1556 self.withdraw_malformed_track(alias, MalformedTrackCondition::MixedForwardingPreference)
1557 .await;
1558 Err(err.into())
1559 }
1560
1561 // ── Data streams ────────────────────────────────────────
1562
1563 /// Open a new unidirectional stream for sending subgroup data.
1564 pub async fn open_subgroup_stream(
1565 &self,
1566 header: &AnySubgroupHeader,
1567 ) -> Result<FramedSendStream, ConnectionError> {
1568 // Before the stream is opened: the Original Publisher is who the rule
1569 // binds, so a header that would mix this track's framing is refused
1570 // here rather than written and answered by the peer.
1571 self.endpoint.note_object_forwarding_preference(
1572 header.track_alias(),
1573 ObjectForwardingPreference::Subgroup,
1574 )?;
1575 let send = self.transport.open_uni().await?;
1576 let mut framed = FramedSendStream::new(send);
1577 let sid = framed.stream_id();
1578 framed.write_subgroup_header(header).await?;
1579 self.emit(ClientEvent::StreamOpened {
1580 direction: Direction::Send,
1581 stream_kind: StreamKind::Subgroup,
1582 stream_id: sid,
1583 });
1584 self.emit(ClientEvent::DataStreamHeader {
1585 stream_id: sid,
1586 direction: Direction::Send,
1587 header: header.clone(),
1588 });
1589 Ok(framed)
1590 }
1591
1592 /// Open a new unidirectional stream for sending a FETCH's objects.
1593 ///
1594 /// The objects answering a FETCH do not go on the request's own stream:
1595 /// they go on a unidirectional stream of their own, which opens with a
1596 /// FETCH_HEADER naming the request they belong to. This writes that header
1597 /// and hands back the stream, the same way
1598 /// [`open_subgroup_stream`](Self::open_subgroup_stream) does for a
1599 /// subgroup.
1600 ///
1601 /// The caller owns the stream that comes back. Nothing here remembers
1602 /// which request it belongs to, so an endpoint serving several fetches at
1603 /// once keeps its own map from Request ID to stream.
1604 pub async fn open_fetch_stream(
1605 &self,
1606 header: &AnyFetchHeader,
1607 ) -> Result<FramedSendStream, ConnectionError> {
1608 let send = self.transport.open_uni().await?;
1609 let mut framed = FramedSendStream::new(send);
1610 let sid = framed.stream_id();
1611 framed.write_fetch_header(header).await?;
1612 self.emit(ClientEvent::StreamOpened {
1613 direction: Direction::Send,
1614 stream_kind: StreamKind::Fetch,
1615 stream_id: sid,
1616 });
1617 Ok(framed)
1618 }
1619
1620 /// Accept the next unidirectional stream and read its fetch header.
1621 ///
1622 /// [`accept_subgroup_stream`](Self::accept_subgroup_stream)'s twin. The two
1623 /// are separate because the header decides how every object after it is
1624 /// framed, so a caller has to know which it is expecting before the first
1625 /// byte is read.
1626 ///
1627 /// Objects come off the returned stream with
1628 /// [`FramedRecvStream::read_fetch_object`].
1629 pub async fn accept_fetch_stream(
1630 &self,
1631 ) -> Result<(AnyFetchHeader, FramedRecvStream), ConnectionError> {
1632 let recv = self.transport.accept_uni().await?;
1633 let mut framed = FramedRecvStream::new(recv);
1634 let sid = framed.stream_id();
1635 let header = framed.read_fetch_header().await?;
1636 self.emit(ClientEvent::StreamOpened {
1637 direction: Direction::Receive,
1638 stream_kind: StreamKind::Fetch,
1639 stream_id: sid,
1640 });
1641 self.emit(ClientEvent::FetchStreamHeader {
1642 stream_id: sid,
1643 direction: Direction::Receive,
1644 header: header.clone(),
1645 });
1646 // A fetch header goes out as `FetchStreamHeader`; `DataStreamHeader`
1647 // carries an `AnySubgroupHeader` and cannot express one. What
1648 // `accept_subgroup_stream` does beyond this - the forwarding-preference
1649 // note, the object measurement - is about a subgroup and has no
1650 // counterpart on a fetch stream.
1651 Ok((header, framed))
1652 }
1653
1654 /// Accept an incoming unidirectional data stream and read its subgroup
1655 /// header.
1656 pub async fn accept_subgroup_stream(
1657 &self,
1658 ) -> Result<(AnySubgroupHeader, FramedRecvStream), ConnectionError> {
1659 let recv = self.transport.accept_uni().await?;
1660 let mut framed = FramedRecvStream::new(recv);
1661 let sid = framed.stream_id();
1662 let header = framed.read_subgroup_header().await?;
1663 self.emit(ClientEvent::StreamOpened {
1664 direction: Direction::Receive,
1665 stream_kind: StreamKind::Subgroup,
1666 stream_id: sid,
1667 });
1668 self.emit(ClientEvent::DataStreamHeader {
1669 stream_id: sid,
1670 direction: Direction::Receive,
1671 header: header.clone(),
1672 });
1673 // Every object on a subgroup stream has the Subgroup preference, so
1674 // the header settles the track's framing before a single object is
1675 // read.
1676 self.note_received_framing(header.track_alias(), ObjectForwardingPreference::Subgroup)
1677 .await?;
1678 // The track is resolved here and not inside the stream: it takes the
1679 // endpoint's alias table, which a stream handle has no way back to.
1680 if let Some(objects) = self.endpoint.track_objects(header.track_alias()) {
1681 framed.measure_objects_against(objects, header.group_id());
1682 }
1683 Ok((header, framed))
1684 }
1685
1686 /// Send an object via datagram.
1687 ///
1688 /// The header goes through `AnyDatagramHeader::encode`, which refuses a
1689 /// header whose Object Status the framing it names cannot carry. Such a
1690 /// header errors here and nothing is sent, rather than going out as an
1691 /// ordinary payload datagram with the status quietly dropped.
1692 pub fn send_datagram(
1693 &self,
1694 header: &AnyDatagramHeader,
1695 payload: &[u8],
1696 ) -> Result<(), ConnectionError> {
1697 // Before anything is encoded, for the reason `open_subgroup_stream`
1698 // gives.
1699 self.endpoint.note_object_forwarding_preference(
1700 header.meta().track_alias,
1701 ObjectForwardingPreference::Datagram,
1702 )?;
1703 let mut buf = Vec::new();
1704 header.encode(&mut buf)?;
1705 buf.extend_from_slice(payload);
1706 self.emit(ClientEvent::DatagramReceived {
1707 direction: Direction::Send,
1708 header: header.clone(),
1709 payload_len: payload.len(),
1710 });
1711 self.transport.send_datagram(bytes::Bytes::from(buf))?;
1712 Ok(())
1713 }
1714
1715 /// Receive a datagram and decode it whole.
1716 ///
1717 /// An extension block announced with a length of 0 is returned as
1718 /// [`ConnectionError::EmptyDatagramExtensions`], which
1719 /// [`Connection::close_for_data_stream`] closes the session over.
1720 ///
1721 /// The codec's `Datagram::decode_object` then reads the whole datagram, and its
1722 /// refusals are returned as [`ConnectionError::Codec`]: an extension block that
1723 /// does not parse, a payload after a status, and a Prior Group ID Gap fault
1724 /// (draft-13 Section 10.1). A gap fault, [`CodecError::MalformedTrack`], makes
1725 /// the track malformed, and this withdraws from it before returning, as
1726 /// draft-13 Section 2.5 requires: "When a subscriber detects a Malformed Track,
1727 /// it MUST UNSUBSCRIBE from the Track and SHOULD deliver an error to the
1728 /// application." The session stays open.
1729 pub async fn recv_datagram(&self) -> Result<(AnyDatagramHeader, Bytes), ConnectionError> {
1730 let data = self.transport.recv_datagram().await?;
1731 let mut cursor = &data[..];
1732 let header = match AnyDatagramHeader::decode(DraftVersion::Draft13, &mut cursor) {
1733 Ok(header) => header,
1734 Err(CodecError::InvalidField) => {
1735 return Err(empty_datagram_extensions(&data)
1736 .unwrap_or(ConnectionError::Codec(CodecError::InvalidField)));
1737 }
1738 Err(err) => return Err(err.into()),
1739 };
1740 let consumed = data.len() - cursor.len();
1741 let payload = data.slice(consumed..);
1742 self.emit(ClientEvent::DatagramReceived {
1743 direction: Direction::Receive,
1744 header: header.clone(),
1745 payload_len: payload.len(),
1746 });
1747 if let Err(err) =
1748 moqtap_codec::draft13::data_stream::Datagram::decode_object(&mut &data[..])
1749 {
1750 if let CodecError::MalformedTrack { .. } = err {
1751 self.withdraw_malformed_track(
1752 header.meta().track_alias,
1753 MalformedTrackCondition::PriorGroupIdGap,
1754 )
1755 .await;
1756 }
1757 return Err(err.into());
1758 }
1759 // A datagram is the other framing, and it settles the track's just as a
1760 // subgroup header does.
1761 self.note_received_framing(header.meta().track_alias, ObjectForwardingPreference::Datagram)
1762 .await?;
1763 // A datagram is a whole object, so the connection can measure it
1764 // without help from the caller.
1765 let meta = header.meta();
1766 if let Err(err) = self.endpoint.note_received_object(
1767 meta.track_alias,
1768 ObjectLocation { group: meta.group_id, object: meta.object_id },
1769 object_role(meta.status),
1770 ) {
1771 // One of the two rules that record answers is a Malformed Track,
1772 // and this path can give the answer itself: a datagram is read
1773 // through the connection, which is what an UNSUBSCRIBE takes. The
1774 // other rule ends the session and is the close table's.
1775 if matches!(err, EndpointError::ObjectPastFinalObject { .. }) {
1776 self.withdraw_malformed_track(
1777 meta.track_alias,
1778 MalformedTrackCondition::ObjectPastFinalObject,
1779 )
1780 .await;
1781 }
1782 return Err(err.into());
1783 }
1784 Ok((header, payload))
1785 }
1786
1787 // ── Accessors ───────────────────────────────────────────
1788
1789 /// Access the underlying endpoint state machine.
1790 pub fn endpoint(&self) -> &Endpoint {
1791 &self.endpoint
1792 }
1793
1794 /// Mutable access to the endpoint state machine.
1795 pub fn endpoint_mut(&mut self) -> &mut Endpoint {
1796 &mut self.endpoint
1797 }
1798
1799 /// The SETUP message the server answered the handshake with.
1800 ///
1801 /// `SERVER_SETUP` through draft-16, the server's half of the unified
1802 /// `SETUP` from draft-17. [`AnyControlMessage::fields`] renders it under
1803 /// this draft's own parameter names, in the order they arrived.
1804 pub fn server_setup(&self) -> &AnyControlMessage {
1805 &self.server_setup
1806 }
1807
1808 /// The framed wire bytes of [`Self::server_setup`], as they arrived.
1809 ///
1810 /// Kept beside the decoded form because the encoding is evidence the
1811 /// decoding discards: two relays sending the same parameter can still
1812 /// disagree on how wide a varint they wrote it in.
1813 pub fn server_setup_raw(&self) -> Option<&[u8]> {
1814 self.server_setup_raw.as_deref()
1815 }
1816
1817 /// Get the negotiated MoQT version.
1818 pub fn negotiated_version(&self) -> Option<VarInt> {
1819 self.endpoint.negotiated_version()
1820 }
1821
1822 /// Which of this draft's *own* `ConnectionError` variants this error is,
1823 /// and which kind of thing it says.
1824 ///
1825 /// The ten every draft carries answer `None` here: [`AnyConnectionError`]
1826 /// classifies those itself. Draft-13 adds two:
1827 /// [`ConnectionError::ControlMessageNarrowing`], a defect in this build, and
1828 /// [`ConnectionError::EmptyDatagramExtensions`], a decoder refusal the draft
1829 /// answers with a close.
1830 ///
1831 /// Matched exhaustively, with no wildcard arm and deliberately so: a
1832 /// variant added to this draft's error type has to arrive here as a compile
1833 /// error, beside the doc comment that quotes the sentence it enforces,
1834 /// rather than as a silent [`ErrorCause::Unclassified`] in the facade.
1835 ///
1836 /// [`AnyConnectionError`]: crate::dispatch::AnyConnectionError
1837 /// [`ErrorCause::Unclassified`]: crate::dispatch::ErrorCause::Unclassified
1838 pub fn draft_specific_cause(
1839 err: &ConnectionError,
1840 ) -> Option<crate::above_codec_rules::DraftSpecificCause> {
1841 match err {
1842 ConnectionError::Endpoint(_)
1843 | ConnectionError::Codec(_)
1844 | ConnectionError::Transport(_)
1845 | ConnectionError::VarInt(_)
1846 | ConnectionError::NoControlStream
1847 | ConnectionError::UnexpectedEnd
1848 | ConnectionError::StreamFinished
1849 | ConnectionError::InvalidAddress(_)
1850 | ConnectionError::TlsConfig(_)
1851 | ConnectionError::DataStreamState(_) => None,
1852 // This build decoding a message and then failing to narrow it to
1853 // its own draft. Nothing reached the wire and no peer is
1854 // implicated, which is the whole reason it is not
1855 // `ConnectionError::Codec`: under that name it would carry
1856 // `Some(PROTOCOL_VIOLATION)` out of `codec_session_error_code` and
1857 // publish a relay for this build's defect. See the variant's own
1858 // doc.
1859 ConnectionError::ControlMessageNarrowing => {
1860 Some(crate::above_codec_rules::DraftSpecificCause::LocalRefusal)
1861 }
1862 // The codec refuses the datagram as a bare `InvalidField`, and
1863 // `recv_datagram` names the rule, so `close_for_data_stream` reads
1864 // the close here. See the variant's own doc.
1865 ConnectionError::EmptyDatagramExtensions { .. } => {
1866 Some(crate::above_codec_rules::DraftSpecificCause::Codec {
1867 error: CodecError::InvalidField,
1868 close: Some(
1869 moqtap_codec::draft13::error_codes::SessionErrorCode::ProtocolViolation
1870 .as_u64(),
1871 ),
1872 })
1873 }
1874 }
1875 }
1876
1877 /// The code to close the session with when a message could not be decoded
1878 /// because the peer broke a rule draft-13 answers with a close.
1879 ///
1880 /// Every variant listed here comes from a sentence in this draft that names
1881 /// the consequence, and the list is per draft: answering a bound this draft
1882 /// does not state would close a session over traffic a conforming peer may
1883 /// send.
1884 ///
1885 /// - Reason Phrase, maximum 1024 bytes: "If an endpoint receives a length
1886 /// exceeding the maximum, it MUST close the session with a Protocol
1887 /// Violation."
1888 /// - GOAWAY New Session URI, maximum 8,192 bytes, with the same sentence.
1889 /// Drafts 11 through 19 state it; 07 through 10 state no maximum for
1890 /// the field at all.
1891 /// - Key-Value-Pair value, maximum 2^16-1 bytes, with the same sentence.
1892 /// - Track Namespace tuple size: "If an endpoint receives a Track
1893 /// Namespace tuple with an N of 0 or more than 32, it MUST close the
1894 /// session with a Protocol Violation." Note the lower bound - an empty
1895 /// tuple is refused here, where drafts 17 and later permit one.
1896 /// - Full Track Name, maximum 4,096 bytes, "computed as the sum of the
1897 /// lengths of each Track Namespace tuple field and the Track Name
1898 /// length field". This draft bounds the pair and not the namespace
1899 /// alone; draft-16 widened it.
1900 /// - Duplicate parameters, a SHOULD rather than a MUST: "Receivers SHOULD
1901 /// check that there are no unauthorized duplicate parameters and close
1902 /// the session as a 'Protocol Violation' if found." The rule is
1903 /// asymmetric here - "Receivers MUST allow duplicates of unknown
1904 /// parameters", and one known type is granted repeats - and the codec
1905 /// reports only the repeats this draft actually forbids.
1906 /// - Unknown control message type: "An endpoint that receives an unknown
1907 /// message type MUST close the session."
1908 /// - Extension headers on an Object whose status is Object Does Not
1909 /// Exist, Section 9.2.1.2. That one arrives on a data stream or a
1910 /// datagram, so [`Connection::close_for_data_stream`] is what carries
1911 /// it.
1912 ///
1913 /// **Not** the zero-length Track Namespace Field, the delta-encoded
1914 /// parameter type overflow, or the Object ID delta wrap. Those enter the
1915 /// specification at drafts 16 and 18, and this draft states none of them.
1916 ///
1917 /// **Not** the 2^16-1 control message length either. This draft states the
1918 /// limit - "the total length of a control message is limited to 2^16-1
1919 /// bytes" - and states no consequence for exceeding it, so an oversized
1920 /// message is refused by the decoder and stops there.
1921 ///
1922 /// **Not** [`CodecError::UnexpectedEnd`], which reports no rule at all: the
1923 /// reader raises it whenever a message is still arriving, and
1924 /// `read_control` loops on it. Closing over it would end a session on an
1925 /// ordinary short read.
1926 ///
1927 /// **Not** the unknown Message Parameter rule. Drafts 16 through 19 require
1928 /// a close for a Message Parameter whose type the negotiated version does
1929 /// not define. This draft states the opposite and states it about the same
1930 /// parameters: "Receivers MUST allow duplicates of unknown parameters",
1931 /// which presumes an unknown parameter arrives and is carried. Refusing one
1932 /// here would close a session over an extension this draft leaves room for.
1933 ///
1934 /// `None` for everything else, including [`CodecError::InvalidField`]. That
1935 /// variant is shared by a dozen unrelated malformations, only some of which
1936 /// the draft answers with a close, so a session cannot be ended on it
1937 /// without ending sessions the draft does not ask to be ended. Splitting it
1938 /// is the way to bring the rest of those rules under this function;
1939 /// widening the match is not - the extension-header rule above is
1940 /// answerable here because it has a variant of its own rather than being
1941 /// one more reading of `InvalidField`.
1942 pub fn codec_session_error_code(
1943 err: &CodecError,
1944 ) -> Option<moqtap_codec::draft13::error_codes::SessionErrorCode> {
1945 use moqtap_codec::draft13::error_codes::SessionErrorCode;
1946 use moqtap_codec::kvp::KvpError;
1947 match err {
1948 // The declared Length disagreeing with the fields, which every
1949 // draft answers with a close. Drafts 07 through 10 name no code for
1950 // it, so it takes the one their other unnamed rules take.
1951 CodecError::ControlMessageLengthMismatch { .. } => {
1952 Some(SessionErrorCode::ProtocolViolation)
1953 }
1954 CodecError::ReasonPhraseTooLong
1955 | CodecError::GoAwayUriTooLong
1956 | CodecError::InvalidNamespaceTupleSize(_)
1957 | CodecError::TrackNameTooLong
1958 | CodecError::DuplicateParameter(_)
1959 | CodecError::UnknownMessageType(_)
1960 | CodecError::ExtensionsOnNonExistentObject(_)
1961 | CodecError::Kvp(KvpError::ValueTooLong(_)) => {
1962 Some(SessionErrorCode::ProtocolViolation)
1963 }
1964 // An unknown data-plane type, Section 9: "An endpoint that
1965 // receives an unknown stream or datagram type MUST close the
1966 // session." One sentence covering two tables, which is why both
1967 // variants sit here.
1968 // A Content Exists field that is neither zero nor one,
1969 // Section 8.8 and Section 8.13: "Any other value is a protocol
1970 // error and MUST terminate the session with a Protocol Violation".
1971 CodecError::InvalidContentExists(_) => Some(SessionErrorCode::ProtocolViolation),
1972 // A Forward field that is neither zero nor one. Section 8.7 and
1973 // Section 8.10: "Any other value is a protocol error and MUST
1974 // terminate the session with a Protocol Violation". Section 8.13
1975 // says "Any value other than 0 or 1 is a Protocol Violation".
1976 // Section 8.14 names the two legal values without a consequence and
1977 // is answered the same way, for the reason given on the variant.
1978 CodecError::InvalidForward(_) => Some(SessionErrorCode::ProtocolViolation),
1979 CodecError::UnknownStreamType(_) | CodecError::UnknownDatagramType(_) => {
1980 Some(SessionErrorCode::ProtocolViolation)
1981 }
1982 // A key-value pair whose value is not the serialization its own
1983 // Type defines, Section 1.3.2: "If a receiver understands a Type,
1984 // and the following Value or Length/Value does not match the
1985 // serialization defined by that Type, the receiver MUST terminate the
1986 // session with error code 'Key-Value Formatting Error'."
1987 // Section 8.2.1.1 states the same answer for the one structure this
1988 // draft spells out: "If the Token structure cannot be decoded, the
1989 // receiver MUST close the Session with Key-Value Formatting error."
1990 //
1991 // The one rule in this table that names a code other than Protocol
1992 // Violation.
1993 CodecError::KeyValueFormatting { .. } => {
1994 Some(SessionErrorCode::KeyValueFormattingError)
1995 }
1996 // Everything this draft does not answer, named rather than swept up
1997 // by a wildcard. The arm is exhaustive deliberately: a new
1998 // `CodecError` variant will not compile until it has been placed on
1999 // one side or the other, on this draft, which is the decision a `_`
2000 // arm makes silently and invisibly in every draft module at once.
2001 //
2002 // Adding one variant to `CodecError` produces an `E0004` in every
2003 // draft module that matches it exhaustively, each naming the
2004 // variant that has nowhere to go. That is the whole mechanism.
2005 //
2006 // The nesting stops at `VarInt`, whose variants report how the bytes
2007 // ran out rather than a rule an endpoint states, so there is nothing
2008 // in it for a draft to answer. `Kvp` is spelled out because it does
2009 // carry one.
2010 // Not `ParameterValueOutOfRange`: no parameter this draft defines
2011 // restricts its value's range. Forwarding is a message field here
2012 // and is answered above.
2013 CodecError::ParameterValueOutOfRange { .. }
2014 | CodecError::UnexpectedEnd
2015 | CodecError::MessageTooLong(_)
2016 | CodecError::VarInt(_)
2017 | CodecError::InvalidField
2018 | CodecError::EmptyNamespaceField
2019 | CodecError::InvalidRange(..)
2020 | CodecError::ParameterLengthMismatch(_)
2021 | CodecError::EndOfTrackObjectId(_)
2022 | CodecError::KeyDeltaOverflow(..)
2023 // Not `TrackPropertyValueOutOfRange`: this draft has neither
2024 // namespace the variant is about. Draft-16 opens an extension header
2025 // registry with value rules of its own, and draft-17 renames it to
2026 // the Track Property registry. Before that, everything with a
2027 // restricted range is either a message field or a Message Parameter.
2028 | CodecError::TrackPropertyValueOutOfRange { .. }
2029 | CodecError::ParametersOutOfOrder(..)
2030 | CodecError::ObjectIdOverflow(..)
2031 | CodecError::InvalidRequiredRequestIdDelta(..)
2032 | CodecError::InvalidStreamTypeValue { .. }
2033 | CodecError::InvalidDatagramTypeValue { .. }
2034 | CodecError::UnknownMessageParameter(_)
2035 // Not `ParameterOutOfScope`: this draft states the scope rule and
2036 // answers it the other way. Section 8.2.1 Version Specific Parameters: "Each
2037 // version-specific parameter definition indicates the message types in which it can
2038 // appear. If it appears in some other type of message, it MUST be
2039 // ignored." The codec carries such a parameter on this draft and never
2040 // raises the variant, so this arm records a rule this draft has and
2041 // does not close over, not one it is missing. Draft-17 is where the
2042 // second sentence becomes a close.
2043 | CodecError::ParameterOutOfScope { .. }
2044 // A Filter Type outside the set this draft assigns. Section 8.7
2045 // states the rule and stops there: "A filter type other than the
2046 // above MUST be treated as error." No code, no close, and no
2047 // sentence elsewhere in the draft that turns an error into one — so
2048 // the message is refused and the session stays open.
2049 // Draft-14 Section 9.7 is where the same sentence gained "MUST be
2050 // close the session with PROTOCOL_VIOLATION", and it is answered
2051 // there.
2052 //
2053 // The assigned set is not the same on every draft either: 07 and 08
2054 // assign 0x1 as Latest Group, 09 and 10 withdraw it, and 11 and
2055 // later reinstate it as Next Group Start. The decoder holds each
2056 // draft to its own list; this arm only decides what a refusal does
2057 // to the session.
2058 //
2059 // The two rules below belong to the parameter form of the filter,
2060 // which arrives at draft-15. This draft carries the Filter Type as a
2061 // field of SUBSCRIBE, so there is no parameter for either to be
2062 // about.
2063 | CodecError::InvalidFilterType(_)
2064 | CodecError::SubscriptionFilterMalformed { .. }
2065 | CodecError::FilterEndGroupOverflow { .. }
2066 // A Fetch Type outside the set this draft assigns. Section 8.16
2067 // states the rule and stops there: "A Fetch Type other than 0x1,
2068 // 0x2 or 0x3 MUST be treated as an error", naming no code and no
2069 // close, exactly as this draft's Filter Type sentence does.
2070 // Draft-14 Section 9.16 is where both gained "MUST be close the
2071 // session with a PROTOCOL_VIOLATION", and it answers them there.
2072 | CodecError::InvalidFetchType(_)
2073 // The object payload rule, Section 9.2.1.1: "Any object with a status
2074 // code other than zero MUST have an empty payload." A MUST on the
2075 // sender with no receiver action named anywhere — the "SHOULD be
2076 // treated as a protocol error" in the same paragraph belongs to the
2077 // sentence before it, which is about a status value this draft does
2078 // not assign — so an object carrying a payload it may not is refused
2079 // and the session stays open.
2080 | CodecError::PayloadNotPermitted { .. }
2081 | CodecError::MalformedObjectProperties { .. }
2082 // A Prior Group ID Gap fault makes the track malformed
2083 // (draft-13 Section 10.1), which draft-13 Section 2.5 answers with
2084 // an UNSUBSCRIBE, through `withdraw_for_subgroup_stream`, and not a
2085 // close.
2086 | CodecError::MalformedTrack { .. }
2087 // Raised only by the draft-23 codec.
2088 | CodecError::ControlMessageExceedsLimit { .. }
2089 | CodecError::MissingErrorDetail { .. }
2090 | CodecError::MalformedErrorDetail { .. }
2091 | CodecError::TokenAliasInSetup { .. }
2092 | CodecError::EmptyTrackName
2093 | CodecError::MalformedAuthToken { .. }
2094 | CodecError::TrackPropertiesNotPermitted
2095 | CodecError::DeltaDecodingOverflow { .. }
2096 | CodecError::MalformedObject { .. }
2097 | CodecError::UnknownObjectStatus(_)
2098 | CodecError::UnsupportedDraft(_)
2099 | CodecError::Kvp(
2100 KvpError::MissingLength | KvpError::UnexpectedEnd | KvpError::VarInt(_),
2101 ) => None,
2102 }
2103 }
2104
2105 /// Close the session on the wire when a decode failure is one draft-13
2106 /// answers with a close, and hand the error back unchanged.
2107 /// Without it every bound the decoder enforces would stop at *this endpoint
2108 /// refused the frame* while the peer, which is the one that broke the rule,
2109 /// saw a session that was still open and went on sending. "MUST close the
2110 /// session" is a statement about the wire.
2111 fn close_for_codec(&self, err: ConnectionError) -> ConnectionError {
2112 if let ConnectionError::Codec(inner) = &err {
2113 if let Some(code) = Self::codec_session_error_code(inner) {
2114 // QUIC application error codes are 62-bit; every code in this
2115 // registry is far below `u32::MAX`, and saturating rather than
2116 // truncating means a future code that is not could never be
2117 // reported as a different, assigned one.
2118 let wire_code = u32::try_from(code.as_u64()).unwrap_or(u32::MAX);
2119 self.close(wire_code, inner.to_string().as_bytes());
2120 }
2121 }
2122 err
2123 }
2124
2125 /// Close the session on the wire when the endpoint says a violation is
2126 /// fatal to it, and hand the error back unchanged.
2127 ///
2128 /// [`EndpointError::session_error_code`] answers `Some` for exactly the
2129 /// errors this draft ends the session over, and the endpoint has already
2130 /// moved its own state machine to Closed by the time this runs. Without
2131 /// this step that move is purely internal: the local endpoint refuses to
2132 /// start anything new while the peer, which is the one that broke the
2133 /// rule, sees a session that is still open and goes on sending. A rule
2134 /// that names a session termination code is a statement about the wire,
2135 /// so it takes a CONNECTION_CLOSE to satisfy it.
2136 ///
2137 /// The reason phrase is the error's own `Display` text, which names the
2138 /// rule rather than repeating the numeric code the close already carries.
2139 ///
2140 /// Errors that answer `None` are recoverable and nothing is sent.
2141 fn close_for(&self, err: &EndpointError) {
2142 if let Some(code) = err.session_error_code() {
2143 // QUIC application error codes are 62-bit; every code in this
2144 // registry is far below `u32::MAX`, and saturating rather than
2145 // truncating means a future code that is not could never be
2146 // reported as a different, assigned one.
2147 let wire_code = u32::try_from(code.as_u64()).unwrap_or(u32::MAX);
2148 self.close(wire_code, err.to_string().as_bytes());
2149 }
2150 }
2151
2152 /// [`close_for`](Self::close_for), then the error unchanged, for the
2153 /// common case where the endpoint's error is also what the caller returns.
2154 fn close_if_session_fatal(&self, err: EndpointError) -> ConnectionError {
2155 self.close_for(&err);
2156 ConnectionError::Endpoint(err)
2157 }
2158
2159 /// Withdraw from a track a data stream found malformed, reporting whether
2160 /// it did.
2161 ///
2162 /// The Malformed Track twin of [`Connection::close_for_data_stream`], and
2163 /// separate from it for the same reason and one more. The same one: a
2164 /// [`FramedRecvStream`] holds no connection, so the reader that finds the
2165 /// fault is not the object that can send an UNSUBSCRIBE. The one more: the
2166 /// two answers are opposites — that call ends the session, this one gives
2167 /// up a track and leaves it running — and a single entry point would have
2168 /// to decide between them from the error alone, which is exactly the
2169 /// decision a caller reproducing a capture wants to make itself.
2170 ///
2171 /// The datagram path needs none of this. It is read through the connection,
2172 /// so [`Connection::recv_datagram`] answers the condition where it finds
2173 /// it, and this is only for the objects that arrive on a stream the caller
2174 /// holds.
2175 pub async fn withdraw_for_data_stream(&self, err: &ConnectionError) -> bool {
2176 let ConnectionError::Endpoint(EndpointError::ObjectPastFinalObject { alias, .. }) = err
2177 else {
2178 return false;
2179 };
2180 self.withdraw_malformed_track(*alias, MalformedTrackCondition::ObjectPastFinalObject).await;
2181 true
2182 }
2183
2184 /// [`Connection::withdraw_for_data_stream`] for an error read from the
2185 /// subgroup stream `header` opened, which also withdraws from the track
2186 /// over the [`CodecError::MalformedTrack`] that
2187 /// [`FramedRecvStream::read_subgroup_object`] returns for a Prior Group ID
2188 /// Gap fault (draft-13 Section 10.1). That error names no track, so the
2189 /// header supplies its alias.
2190 ///
2191 /// draft-13 Section 2.5: "When a subscriber detects a Malformed Track, it
2192 /// MUST UNSUBSCRIBE from the Track and SHOULD deliver an error to the
2193 /// application."
2194 pub async fn withdraw_for_subgroup_stream(
2195 &self,
2196 header: &AnySubgroupHeader,
2197 err: &ConnectionError,
2198 ) -> bool {
2199 if let ConnectionError::Codec(CodecError::MalformedTrack { .. }) = err {
2200 self.withdraw_malformed_track(
2201 header.track_alias(),
2202 MalformedTrackCondition::PriorGroupIdGap,
2203 )
2204 .await;
2205 return true;
2206 }
2207 self.withdraw_for_data_stream(err).await
2208 }
2209
2210 /// [`Connection::withdraw_for_data_stream`] for an error read from the fetch
2211 /// stream `header` opened, which also withdraws from the track the FETCH
2212 /// asked for over the [`CodecError::MalformedTrack`] that
2213 /// [`FramedRecvStream::read_fetch_object`] returns for a Prior Group ID Gap
2214 /// fault (draft-13 Section 10.1). That error names no track, so the header's
2215 /// Request ID supplies it.
2216 ///
2217 /// draft-13 Section 2.5: "When a subscriber detects a Malformed Track, it
2218 /// MUST UNSUBSCRIBE from the Track and SHOULD deliver an error to the
2219 /// application."
2220 pub async fn withdraw_for_fetch_stream(
2221 &self,
2222 header: &AnyFetchHeader,
2223 err: &ConnectionError,
2224 ) -> bool {
2225 let ConnectionError::Codec(CodecError::MalformedTrack { .. }) = err else {
2226 return self.withdraw_for_data_stream(err).await;
2227 };
2228 let condition = MalformedTrackCondition::PriorGroupIdGap;
2229 self.withdraw_malformed_fetch_track(header.request_id(), condition).await;
2230 true
2231 }
2232
2233 /// Close the session over a rule broken on a data stream, reporting whether
2234 /// it did.
2235 ///
2236 /// A data stream cannot close for itself the way `recv_control` does:
2237 /// [`Connection::accept_subgroup_stream`] hands the caller a
2238 /// [`FramedRecvStream`] holding no connection, so the reader that finds the
2239 /// violation is not the object that can act on it. Keeping it a separate
2240 /// call is deliberate as well - a permissive caller, one reproducing a
2241 /// capture, can read a violating stream and report it without tearing the
2242 /// session down.
2243 ///
2244 /// The rule this draft answers here is extension headers on an Object whose
2245 /// status is Object Does Not Exist, which reaches subgroup streams, fetch
2246 /// streams and status datagrams alike. It shares `codec_session_error_code`
2247 /// with the control path, so a rule is answered with one code whichever
2248 /// stream carried it.
2249 ///
2250 /// Not every rule that reaches here is the decoder's. A track whose objects
2251 /// mix forwarding preferences is the endpoint's to notice — it takes the
2252 /// alias table to know which track an object belongs to — and it arrives on
2253 /// exactly these streams. Both kinds are asked for a code the same way, and
2254 /// a rule with no code is declined rather than guessed at.
2255 pub fn close_for_data_stream(&self, err: &ConnectionError) -> bool {
2256 match err {
2257 ConnectionError::Codec(inner) => {
2258 let Some(code) = Self::codec_session_error_code(inner) else { return false };
2259 let wire_code = u32::try_from(code.as_u64()).unwrap_or(u32::MAX);
2260 self.close(wire_code, inner.to_string().as_bytes());
2261 true
2262 }
2263 // A rule the endpoint raises rather than the decoder. The two
2264 // reach their codes through different tables and mean the same
2265 // thing here: `Some` is a rule this draft ends the session over.
2266 ConnectionError::Endpoint(inner) => {
2267 let Some(code) = inner.session_error_code() else { return false };
2268 let wire_code = u32::try_from(code.as_u64()).unwrap_or(u32::MAX);
2269 self.close(wire_code, inner.to_string().as_bytes());
2270 true
2271 }
2272 // Not a `Codec` failure: the codec refuses the datagram as a bare
2273 // `InvalidField`, which `recv_datagram` names, so the code comes
2274 // from `draft_specific_cause`.
2275 ConnectionError::EmptyDatagramExtensions { .. } => {
2276 let Some(crate::above_codec_rules::DraftSpecificCause::Codec {
2277 close: Some(code),
2278 ..
2279 }) = Self::draft_specific_cause(err)
2280 else {
2281 return false;
2282 };
2283 self.close(u32::try_from(code).unwrap_or(u32::MAX), err.to_string().as_bytes());
2284 true
2285 }
2286 _ => false,
2287 }
2288 }
2289
2290 /// Close the connection.
2291 pub fn close(&self, code: u32, reason: &[u8]) {
2292 self.emit(ClientEvent::Closed { code, reason: reason.to_vec() });
2293 self.transport.close(code, reason);
2294 }
2295}
2296
2297/// Determine the encoded length of a varint from its first byte.
2298fn varint_len(first_byte: u8) -> usize {
2299 1 << (first_byte >> 6)
2300}
2301
2302#[cfg(test)]
2303mod tests {
2304 use super::*;
2305
2306 /// This build failing to narrow a message it decoded is never a finding
2307 /// about the peer.
2308 ///
2309 /// The arm that raises `ControlMessageNarrowing` is unreachable — this
2310 /// draft's decoder can only hand back this draft's variant — and nothing
2311 /// pins that. What is pinned here is the half that matters.
2312 /// `CodecError::UnknownMessageType(0)` is what the arm must not raise:
2313 /// `codec_session_error_code` answers it `Some(PROTOCOL_VIOLATION)` on
2314 /// every draft in range, so the day the narrowing failed a conformance
2315 /// probe would publish a relay for sending a control message type this
2316 /// draft does not assign — with `0x00` attached as the codepoint that
2317 /// proved it, which is an accusation better evidenced than any real one
2318 /// this build makes. The section stating that rule is numbered differently
2319 /// on every draft, and the point does not turn on the number.
2320 #[test]
2321 fn a_message_this_build_could_not_narrow_names_nobody() {
2322 use crate::dispatch::{AnyConnectionError, ErrorCause};
2323
2324 let err: AnyConnectionError = ConnectionError::ControlMessageNarrowing.into();
2325 assert!(err.is_local(), "a narrowing this build could not do is this build's");
2326 assert_eq!(
2327 err.cause(),
2328 &ErrorCause::Facade,
2329 "nothing reached the wire, so there is no rule and no close code to read"
2330 );
2331 }
2332
2333 /// Types 0x01, 0x03 and 0x05 carry extensions, so a zero byte where their
2334 /// Extension Headers Length sits is the close. Types 0x00, 0x02 and 0x04
2335 /// have no such field. The ruling is on `EmptyDatagramExtensions`.
2336 #[test]
2337 fn an_empty_extension_block_is_named_on_exactly_the_types_with_extensions() {
2338 for datagram_type in [0x00u8, 0x01, 0x02, 0x03, 0x04, 0x05] {
2339 let datagram = [datagram_type, 0x07, 0x01, 0x09, 0x80, 0x00, 0x00];
2340 let got = empty_datagram_extensions(&datagram);
2341 if matches!(datagram_type, 0x01 | 0x03 | 0x05) {
2342 assert!(
2343 matches!(got, Some(ConnectionError::EmptyDatagramExtensions { object_id: 9 })),
2344 "Type {datagram_type:#04x}: expected the close, got {got:?}"
2345 );
2346 } else {
2347 assert!(got.is_none(), "Type {datagram_type:#04x}: carries no extensions");
2348 }
2349 }
2350 }
2351
2352 #[test]
2353 fn client_config_supported_versions_default() {
2354 let config = ClientConfig {
2355 additional_versions: Vec::new(),
2356 transport: TransportType::Quic,
2357 skip_cert_verification: false,
2358 ca_certs: Vec::new(),
2359 setup_parameters: Vec::new(),
2360 };
2361 let versions = config.supported_versions();
2362 assert_eq!(versions.len(), 1);
2363 assert_eq!(versions[0].into_inner(), 0xff000000 + 13);
2364 }
2365
2366 #[test]
2367 fn client_config_alpn_quic() {
2368 let config = ClientConfig {
2369 additional_versions: Vec::new(),
2370 transport: TransportType::Quic,
2371 skip_cert_verification: false,
2372 ca_certs: Vec::new(),
2373 setup_parameters: Vec::new(),
2374 };
2375 assert_eq!(config.alpn(), vec![DraftVersion::Draft13.quic_alpn().to_vec()]);
2376 }
2377
2378 #[test]
2379 fn moqt_alpn_value() {
2380 assert_eq!(MOQT_ALPN, b"moq-00");
2381 }
2382}