Skip to main content

moqtap_client/draft12/
connection.rs

1use bytes::{Buf, Bytes, BytesMut};
2
3use crate::draft12::endpoint::{Endpoint, EndpointError};
4use crate::draft12::event::{ClientEvent, Direction, FetchObject, StreamKind, SubgroupObject};
5use crate::draft12::observer::ConnectionObserver;
6use crate::draft12::session::request_id::Role;
7use crate::draft12::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::draft12::data_stream::{FetchObjectHeader, ObjectHeader, SubgroupGaps};
16use moqtap_codec::draft12::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-12 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-12 and then could not
61    /// narrow to draft-12'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-12 did not narrow to draft-12: 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-12 Section 9, which assigns 0x00-0x03 to OBJECT_DATAGRAM and
103    /// 0x04-0x05 to OBJECT_DATAGRAM_STATUS:
104    ///
105    ///   - draft-12 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-12 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-12 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::draft12::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-12 MoQT client connection.
186pub struct ClientConfig {
187    /// Additional draft versions to offer in CLIENT_SETUP (draft-12 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-12 first, then any additional versions.
203    pub fn supported_versions(&self) -> Vec<VarInt> {
204        let mut versions = vec![DraftVersion::Draft12.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::Draft12.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-12 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-12 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::draft12::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::draft12::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-12 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-12 dispatcher
538        let mut frame = &self.buf[..total];
539        let msg = AnyControlMessage::decode(DraftVersion::Draft12, &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::Draft12, &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::Draft12(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 12 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::Draft12, &mut cursor) {
590                Ok(header) => {
591                    let consumed = self.buf.len() - cursor.remaining();
592                    self.buf.advance(consumed);
593                    self.fetch_gaps = moqtap_codec::draft12::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-12 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-12 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-12 fetch object (header + payload).
657    ///
658    /// A Prior Group ID Gap fault the stream shows (draft-12 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-12 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-12 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::Draft12(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::Draft12(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::Draft12(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::Draft12(msg) => Ok(msg),
960            // `AnyControlMessage` carries one variant per enabled draft feature. With draft 12 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: VarInt,
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 and return the allocated ID.
1013    ///
1014    /// The Filter Type comes from the arguments, so the message cannot name a
1015    /// filter whose fields it does not carry.
1016    #[allow(clippy::too_many_arguments)]
1017    pub async fn subscribe_range(
1018        &mut self,
1019        track_namespace: TrackNamespace,
1020        track_name: Vec<u8>,
1021        subscriber_priority: u8,
1022        group_order: GroupOrder,
1023        start_location: Location,
1024        end_group: Option<VarInt>,
1025        parameters: Vec<KeyValuePair>,
1026    ) -> Result<VarInt, ConnectionError> {
1027        let (req_id, msg) = self.endpoint.subscribe_range(
1028            track_namespace,
1029            track_name,
1030            subscriber_priority,
1031            group_order,
1032            start_location,
1033            end_group,
1034            parameters,
1035        )?;
1036        self.send_control(&msg).await?;
1037        Ok(req_id)
1038    }
1039
1040    /// Send an UNSUBSCRIBE for the given request ID.
1041    pub async fn unsubscribe(&mut self, request_id: VarInt) -> Result<(), ConnectionError> {
1042        let msg = self.endpoint.unsubscribe(request_id)?;
1043        self.send_control(&msg).await
1044    }
1045
1046    /// Accept a subscription the peer opened, sending SUBSCRIBE_OK and giving
1047    /// its track a Track Alias.
1048    ///
1049    /// The endpoint refuses an alias a live track of its own already holds and
1050    /// refuses a second answer to one SUBSCRIBE, so nothing is written on the
1051    /// wire when it does either.
1052    pub async fn subscribe_ok(
1053        &mut self,
1054        request_id: VarInt,
1055        track_alias: VarInt,
1056        expires: VarInt,
1057        group_order: GroupOrder,
1058        parameters: Vec<KeyValuePair>,
1059    ) -> Result<(), ConnectionError> {
1060        let msg = self.endpoint.send_subscribe_ok(
1061            request_id,
1062            track_alias,
1063            expires,
1064            group_order,
1065            parameters,
1066        )?;
1067        self.send_control(&msg).await
1068    }
1069
1070    /// Reject a subscription the peer opened, sending SUBSCRIBE_ERROR.
1071    ///
1072    /// The endpoint refuses a second answer to one SUBSCRIBE, so nothing is
1073    /// written on the wire when it does.
1074    pub async fn subscribe_error(
1075        &mut self,
1076        request_id: VarInt,
1077        error_code: VarInt,
1078        reason_phrase: Vec<u8>,
1079    ) -> Result<(), ConnectionError> {
1080        let msg = self.endpoint.send_subscribe_error(request_id, error_code, reason_phrase)?;
1081        self.send_control(&msg).await
1082    }
1083
1084    /// End a subscription this endpoint accepted, sending SUBSCRIBE_DONE.
1085    pub async fn subscribe_done(
1086        &mut self,
1087        request_id: VarInt,
1088        status_code: VarInt,
1089        stream_count: VarInt,
1090        reason_phrase: Vec<u8>,
1091    ) -> Result<(), ConnectionError> {
1092        let msg = self.endpoint.send_subscribe_done(
1093            request_id,
1094            status_code,
1095            stream_count,
1096            reason_phrase,
1097        )?;
1098        self.send_control(&msg).await
1099    }
1100
1101    /// Narrow a subscription this endpoint opened, sending SUBSCRIBE_UPDATE.
1102    ///
1103    /// No Request ID is spent: on this draft the message's one identifier
1104    /// field names the subscription it modifies.
1105    #[allow(clippy::too_many_arguments)]
1106    pub async fn subscribe_update(
1107        &mut self,
1108        request_id: VarInt,
1109        start_group: VarInt,
1110        start_object: VarInt,
1111        end_group: VarInt,
1112        subscriber_priority: u8,
1113        forward: Forward,
1114        parameters: Vec<KeyValuePair>,
1115    ) -> Result<(), ConnectionError> {
1116        let msg = self.endpoint.subscribe_update(
1117            request_id,
1118            start_group,
1119            start_object,
1120            end_group,
1121            subscriber_priority,
1122            forward,
1123            parameters,
1124        )?;
1125        self.send_control(&msg).await
1126    }
1127
1128    /// Offer the peer a subscription to a track this endpoint publishes, and
1129    /// return the Request ID the offer was allocated.
1130    ///
1131    /// Nothing is written on the wire when the endpoint refuses to build the
1132    /// offer, which it does when the Track Alias is one another live track of
1133    /// this session already holds.
1134    #[allow(clippy::too_many_arguments)]
1135    pub async fn publish(
1136        &mut self,
1137        track_namespace: TrackNamespace,
1138        track_name: Vec<u8>,
1139        track_alias: VarInt,
1140        group_order: GroupOrder,
1141        largest_location: Option<Location>,
1142        forward: Forward,
1143        parameters: Vec<KeyValuePair>,
1144    ) -> Result<VarInt, ConnectionError> {
1145        let (req_id, msg) = self.endpoint.publish(
1146            track_namespace,
1147            track_name,
1148            track_alias,
1149            group_order,
1150            largest_location,
1151            forward,
1152            parameters,
1153        )?;
1154        self.send_control(&msg).await?;
1155        Ok(req_id)
1156    }
1157
1158    /// Accept a PUBLISH the peer sent, which establishes the subscription it
1159    /// opened.
1160    ///
1161    /// The endpoint refuses a second answer to one PUBLISH, so nothing is
1162    /// written on the wire when it does.
1163    #[allow(clippy::too_many_arguments)]
1164    pub async fn publish_ok(
1165        &mut self,
1166        request_id: VarInt,
1167        forward: Forward,
1168        subscriber_priority: u8,
1169        group_order: GroupOrder,
1170        filter_type: VarInt,
1171        start_group: Option<VarInt>,
1172        start_object: Option<VarInt>,
1173        end_group: Option<VarInt>,
1174    ) -> Result<(), ConnectionError> {
1175        let msg = self.endpoint.send_publish_ok(
1176            request_id,
1177            forward,
1178            subscriber_priority,
1179            group_order,
1180            filter_type,
1181            start_group,
1182            start_object,
1183            end_group,
1184        )?;
1185        self.send_control(&msg).await
1186    }
1187
1188    /// Reject a PUBLISH the peer sent, which ends the subscription it opened
1189    /// before it was established.
1190    ///
1191    /// The endpoint refuses a second answer to one PUBLISH, so nothing is
1192    /// written on the wire when it does.
1193    pub async fn publish_error(
1194        &mut self,
1195        request_id: VarInt,
1196        error_code: VarInt,
1197        reason_phrase: Vec<u8>,
1198    ) -> Result<(), ConnectionError> {
1199        let msg = self.endpoint.send_publish_error(request_id, error_code, reason_phrase)?;
1200        self.send_control(&msg).await
1201    }
1202
1203    // ── Fetch flow ──────────────────────────────────────────
1204
1205    /// Send a FETCH and return the allocated request ID.
1206    #[allow(clippy::too_many_arguments)]
1207    pub async fn fetch(
1208        &mut self,
1209        track_namespace: TrackNamespace,
1210        track_name: Vec<u8>,
1211        subscriber_priority: u8,
1212        group_order: GroupOrder,
1213        start_group: VarInt,
1214        start_object: VarInt,
1215        end_group: VarInt,
1216        end_object: VarInt,
1217        parameters: Vec<KeyValuePair>,
1218    ) -> Result<VarInt, ConnectionError> {
1219        let (req_id, msg) = self.endpoint.fetch(
1220            track_namespace,
1221            track_name,
1222            subscriber_priority,
1223            group_order,
1224            start_group,
1225            start_object,
1226            end_group,
1227            end_object,
1228            parameters,
1229        )?;
1230        self.send_control(&msg).await?;
1231        Ok(req_id)
1232    }
1233
1234    /// Send a Relative Joining Fetch and return the allocated request ID.
1235    ///
1236    /// `joining_start` counts groups back from the live edge of the
1237    /// subscription it names. Section 8.16.1 computes the range from "the
1238    /// Preceding Group Offset", which is this field under the name it carried
1239    /// two drafts ago; the field list calls it Joining Start and says that for
1240    /// a Relative Joining Fetch "a value of 0 indicates the Fetch starts at
1241    /// the beginning of the Current Group". For the form that names the group
1242    /// outright, see
1243    /// [`absolute_joining_fetch`](Self::absolute_joining_fetch).
1244    pub async fn joining_fetch(
1245        &mut self,
1246        subscriber_priority: u8,
1247        group_order: GroupOrder,
1248        joining_request_id: VarInt,
1249        joining_start: VarInt,
1250        parameters: Vec<KeyValuePair>,
1251    ) -> Result<VarInt, ConnectionError> {
1252        let (req_id, msg) = self.endpoint.joining_fetch(
1253            subscriber_priority,
1254            group_order,
1255            joining_request_id,
1256            joining_start,
1257            parameters,
1258        )?;
1259        self.send_control(&msg).await?;
1260        Ok(req_id)
1261    }
1262
1263    /// Send an Absolute Joining Fetch and return the allocated request ID.
1264    ///
1265    /// `joining_start` is the group to begin at. Section 8.16 has an Absolute
1266    /// Joining Fetch "Identical to a Relative Joining Fetch except that the
1267    /// Start Group is determined by an absolute Group value rather than a
1268    /// relative offset to the subscription", so a subscriber that knows the
1269    /// group it wants can ask for it without first being told a Largest
1270    /// Location to count back from.
1271    ///
1272    /// Two calls rather than one taking a Fetch Type, because these are the
1273    /// only two the joining form admits. The endpoint is named the same way,
1274    /// so no call between an application and the wire has a Fetch Type in it
1275    /// to be given a wrong one.
1276    pub async fn absolute_joining_fetch(
1277        &mut self,
1278        subscriber_priority: u8,
1279        group_order: GroupOrder,
1280        joining_request_id: VarInt,
1281        joining_start: VarInt,
1282        parameters: Vec<KeyValuePair>,
1283    ) -> Result<VarInt, ConnectionError> {
1284        let (req_id, msg) = self.endpoint.absolute_joining_fetch(
1285            subscriber_priority,
1286            group_order,
1287            joining_request_id,
1288            joining_start,
1289            parameters,
1290        )?;
1291        self.send_control(&msg).await?;
1292        Ok(req_id)
1293    }
1294
1295    /// Send a FETCH_CANCEL for the given request ID.
1296    pub async fn fetch_cancel(&mut self, request_id: VarInt) -> Result<(), ConnectionError> {
1297        let msg = self.endpoint.fetch_cancel(request_id)?;
1298        self.send_control(&msg).await
1299    }
1300
1301    /// Accept a fetch the peer opened, sending FETCH_OK.
1302    ///
1303    /// The endpoint refuses a Joining Fetch naming a subscription this session
1304    /// cannot join and refuses a second answer to one FETCH, so nothing is
1305    /// written on the wire when it does either.
1306    pub async fn fetch_ok(
1307        &mut self,
1308        request_id: VarInt,
1309        group_order: GroupOrder,
1310        end_of_track: u8,
1311        end_location: Location,
1312        parameters: Vec<KeyValuePair>,
1313    ) -> Result<(), ConnectionError> {
1314        let msg = self.endpoint.send_fetch_ok(
1315            request_id,
1316            group_order,
1317            end_of_track,
1318            end_location,
1319            parameters,
1320        )?;
1321        self.send_control(&msg).await
1322    }
1323
1324    /// Refuse a fetch the peer opened, sending FETCH_ERROR.
1325    ///
1326    /// The endpoint refuses a second answer to one FETCH, and refuses a
1327    /// Joining Fetch's refusal under any code but the one the draft names for
1328    /// it, so nothing is written on the wire when it does either.
1329    pub async fn fetch_error(
1330        &mut self,
1331        request_id: VarInt,
1332        error_code: VarInt,
1333        reason_phrase: Vec<u8>,
1334    ) -> Result<(), ConnectionError> {
1335        let msg = self.endpoint.send_fetch_error(request_id, error_code, reason_phrase)?;
1336        self.send_control(&msg).await
1337    }
1338
1339    // ── Namespace flows ─────────────────────────────────────
1340
1341    /// Send a SUBSCRIBE_ANNOUNCES. Returns the allocated request ID.
1342    pub async fn subscribe_announces(
1343        &mut self,
1344        track_namespace_prefix: TrackNamespace,
1345        parameters: Vec<KeyValuePair>,
1346    ) -> Result<VarInt, ConnectionError> {
1347        let (req_id, msg) =
1348            self.endpoint.subscribe_announces(track_namespace_prefix, parameters)?;
1349        self.send_control(&msg).await?;
1350        Ok(req_id)
1351    }
1352
1353    /// Accept a namespace subscription the peer made, sending SUBSCRIBE_ANNOUNCES_OK.
1354    ///
1355    /// The endpoint refuses a second answer to one SUBSCRIBE_ANNOUNCES, so nothing is
1356    /// written on the wire when it does.
1357    pub async fn subscribe_announces_ok(
1358        &mut self,
1359        request_id: VarInt,
1360    ) -> Result<(), ConnectionError> {
1361        let msg = self.endpoint.send_subscribe_announces_ok(request_id)?;
1362        self.send_control(&msg).await
1363    }
1364
1365    /// Refuse a namespace subscription the peer made, sending SUBSCRIBE_ANNOUNCES_ERROR.
1366    ///
1367    /// The other half of the same sentence: one answer, and this is the other
1368    /// one it can be.
1369    pub async fn subscribe_announces_error(
1370        &mut self,
1371        request_id: VarInt,
1372        error_code: VarInt,
1373        reason_phrase: Vec<u8>,
1374    ) -> Result<(), ConnectionError> {
1375        let msg =
1376            self.endpoint.send_subscribe_announces_error(request_id, error_code, reason_phrase)?;
1377        self.send_control(&msg).await
1378    }
1379
1380    /// Send an ANNOUNCE. Returns the allocated request ID.
1381    pub async fn announce(
1382        &mut self,
1383        track_namespace: TrackNamespace,
1384        parameters: Vec<KeyValuePair>,
1385    ) -> Result<VarInt, ConnectionError> {
1386        let (req_id, msg) = self.endpoint.announce(track_namespace, parameters)?;
1387        self.send_control(&msg).await?;
1388        Ok(req_id)
1389    }
1390
1391    /// Send an UNANNOUNCE.
1392    pub async fn unannounce(
1393        &mut self,
1394        track_namespace: TrackNamespace,
1395    ) -> Result<(), ConnectionError> {
1396        let msg = self.endpoint.unannounce(track_namespace)?;
1397        self.send_control(&msg).await
1398    }
1399
1400    /// Accept an announcement the peer made, sending ANNOUNCE_OK.
1401    ///
1402    /// The endpoint refuses a second answer to one ANNOUNCE, so nothing is
1403    /// written on the wire when it does.
1404    pub async fn announce_ok(&mut self, request_id: VarInt) -> Result<(), ConnectionError> {
1405        let msg = self.endpoint.send_announce_ok(request_id)?;
1406        self.send_control(&msg).await
1407    }
1408
1409    /// Refuse an announcement the peer made, sending ANNOUNCE_ERROR.
1410    ///
1411    /// The other half of the same sentence: one answer, and this is the other
1412    /// one it can be.
1413    pub async fn announce_error(
1414        &mut self,
1415        request_id: VarInt,
1416        error_code: VarInt,
1417        reason_phrase: Vec<u8>,
1418    ) -> Result<(), ConnectionError> {
1419        let msg = self.endpoint.send_announce_error(request_id, error_code, reason_phrase)?;
1420        self.send_control(&msg).await
1421    }
1422
1423    /// Revoke an acceptance, sending ANNOUNCE_CANCEL.
1424    ///
1425    /// The endpoint refuses one for an announcement it never accepted, so
1426    /// nothing is written on the wire when it does.
1427    pub async fn announce_cancel(
1428        &mut self,
1429        track_namespace: TrackNamespace,
1430        error_code: VarInt,
1431        reason_phrase: Vec<u8>,
1432    ) -> Result<(), ConnectionError> {
1433        let msg = self.endpoint.announce_cancel(track_namespace, error_code, reason_phrase)?;
1434        self.send_control(&msg).await
1435    }
1436    // ── Track Status flow ────────────────────────────────────
1437
1438    /// Send a TRACK_STATUS_REQUEST. Returns the allocated request ID.
1439    pub async fn track_status_request(
1440        &mut self,
1441        track_namespace: TrackNamespace,
1442        track_name: Vec<u8>,
1443        parameters: Vec<KeyValuePair>,
1444    ) -> Result<VarInt, ConnectionError> {
1445        let (req_id, msg) =
1446            self.endpoint.track_status_request(track_namespace, track_name, parameters)?;
1447        self.send_control(&msg).await?;
1448        Ok(req_id)
1449    }
1450
1451    /// Answer a TRACK_STATUS_REQUEST the peer sent, sending TRACK_STATUS.
1452    ///
1453    /// The endpoint refuses a second answer to one request, so nothing is
1454    /// written on the wire when it does.
1455    pub async fn track_status(
1456        &mut self,
1457        request_id: VarInt,
1458        status_code: VarInt,
1459        largest_location: Location,
1460        parameters: Vec<KeyValuePair>,
1461    ) -> Result<(), ConnectionError> {
1462        let msg = self.endpoint.send_track_status(
1463            request_id,
1464            status_code,
1465            largest_location,
1466            parameters,
1467        )?;
1468        self.send_control(&msg).await
1469    }
1470
1471    // ── Malformed Tracks ────────────────────────────────────
1472
1473    /// Answer Section 2.5 for the track `alias` names: withdraw from it, and
1474    /// send the UNSUBSCRIBE that withdrawal is.
1475    ///
1476    /// "When a subscriber detects a Malformed Track, it MUST UNSUBSCRIBE from
1477    /// the Track and SHOULD deliver an error to the application." The caller
1478    /// delivers the error by returning it; this is the other half, and the
1479    /// caller does not have to remember to ask for it.
1480    ///
1481    /// Nothing here ends the session, and that is the point of it. The
1482    /// conditions in Section 2.5 are answered by giving up one track.
1483    ///
1484    /// # Why a write that fails is not reported
1485    ///
1486    /// The error the caller is about to receive is the one that says what
1487    /// went wrong with the track. A control stream that will not take an
1488    /// UNSUBSCRIBE is a session on its way out for a reason of its own, and
1489    /// replacing the condition's report with a transport error would lose the
1490    /// only account of why the track was withdrawn. The rest of the
1491    /// withdrawal is abandoned, because a stream that refused one message
1492    /// will refuse the next.
1493    async fn withdraw_malformed_track(&self, alias: u64, condition: MalformedTrackCondition) {
1494        for msg in self.endpoint.withdraw_malformed_track(alias, condition) {
1495            if self.send_control(&msg).await.is_err() {
1496                break;
1497            }
1498        }
1499    }
1500
1501    /// [`Self::withdraw_malformed_track`] for the track the FETCH `request_id`
1502    /// asked for.
1503    async fn withdraw_malformed_fetch_track(
1504        &self,
1505        request_id: u64,
1506        condition: MalformedTrackCondition,
1507    ) {
1508        for msg in self.endpoint.withdraw_malformed_fetch_track(request_id, condition) {
1509            if self.send_control(&msg).await.is_err() {
1510                break;
1511            }
1512        }
1513    }
1514
1515    /// Record the framing an arriving object was sent with, and withdraw from
1516    /// the track when it is the second framing that track has been sent.
1517    ///
1518    /// The receiving half of a pair. The two writing paths call the endpoint
1519    /// directly and answer a mixed track by refusing to write it, because
1520    /// Section 2.5's sentence is a subscriber's: an endpoint about to send an
1521    /// object is that object's Original Publisher, and a publisher has no
1522    /// subscription of its own to withdraw.
1523    async fn note_received_framing(
1524        &self,
1525        alias: u64,
1526        seen: ObjectForwardingPreference,
1527    ) -> Result<(), ConnectionError> {
1528        let Err(err) = self.endpoint.note_object_forwarding_preference(alias, seen) else {
1529            return Ok(());
1530        };
1531        self.withdraw_malformed_track(alias, MalformedTrackCondition::MixedForwardingPreference)
1532            .await;
1533        Err(err.into())
1534    }
1535
1536    // ── Data streams ────────────────────────────────────────
1537
1538    /// Open a new unidirectional stream for sending subgroup data.
1539    pub async fn open_subgroup_stream(
1540        &self,
1541        header: &AnySubgroupHeader,
1542    ) -> Result<FramedSendStream, ConnectionError> {
1543        // Before the stream is opened: the Original Publisher is who the rule
1544        // binds, so a header that would mix this track's framing is refused
1545        // here rather than written and answered by the peer.
1546        self.endpoint.note_object_forwarding_preference(
1547            header.track_alias(),
1548            ObjectForwardingPreference::Subgroup,
1549        )?;
1550        let send = self.transport.open_uni().await?;
1551        let mut framed = FramedSendStream::new(send);
1552        let sid = framed.stream_id();
1553        framed.write_subgroup_header(header).await?;
1554        self.emit(ClientEvent::StreamOpened {
1555            direction: Direction::Send,
1556            stream_kind: StreamKind::Subgroup,
1557            stream_id: sid,
1558        });
1559        self.emit(ClientEvent::DataStreamHeader {
1560            stream_id: sid,
1561            direction: Direction::Send,
1562            header: header.clone(),
1563        });
1564        Ok(framed)
1565    }
1566
1567    /// Open a new unidirectional stream for sending a FETCH's objects.
1568    ///
1569    /// The objects answering a FETCH do not go on the request's own stream:
1570    /// they go on a unidirectional stream of their own, which opens with a
1571    /// FETCH_HEADER naming the request they belong to. This writes that header
1572    /// and hands back the stream, the same way
1573    /// [`open_subgroup_stream`](Self::open_subgroup_stream) does for a
1574    /// subgroup.
1575    ///
1576    /// The caller owns the stream that comes back. Nothing here remembers
1577    /// which request it belongs to, so an endpoint serving several fetches at
1578    /// once keeps its own map from Request ID to stream.
1579    pub async fn open_fetch_stream(
1580        &self,
1581        header: &AnyFetchHeader,
1582    ) -> Result<FramedSendStream, ConnectionError> {
1583        let send = self.transport.open_uni().await?;
1584        let mut framed = FramedSendStream::new(send);
1585        let sid = framed.stream_id();
1586        framed.write_fetch_header(header).await?;
1587        self.emit(ClientEvent::StreamOpened {
1588            direction: Direction::Send,
1589            stream_kind: StreamKind::Fetch,
1590            stream_id: sid,
1591        });
1592        Ok(framed)
1593    }
1594
1595    /// Accept the next unidirectional stream and read its fetch header.
1596    ///
1597    /// [`accept_subgroup_stream`](Self::accept_subgroup_stream)'s twin. The two
1598    /// are separate because the header decides how every object after it is
1599    /// framed, so a caller has to know which it is expecting before the first
1600    /// byte is read.
1601    ///
1602    /// Objects come off the returned stream with
1603    /// [`FramedRecvStream::read_fetch_object`].
1604    pub async fn accept_fetch_stream(
1605        &self,
1606    ) -> Result<(AnyFetchHeader, FramedRecvStream), ConnectionError> {
1607        let recv = self.transport.accept_uni().await?;
1608        let mut framed = FramedRecvStream::new(recv);
1609        let sid = framed.stream_id();
1610        let header = framed.read_fetch_header().await?;
1611        self.emit(ClientEvent::StreamOpened {
1612            direction: Direction::Receive,
1613            stream_kind: StreamKind::Fetch,
1614            stream_id: sid,
1615        });
1616        self.emit(ClientEvent::FetchStreamHeader {
1617            stream_id: sid,
1618            direction: Direction::Receive,
1619            header: header.clone(),
1620        });
1621        // A fetch header goes out as `FetchStreamHeader`; `DataStreamHeader`
1622        // carries an `AnySubgroupHeader` and cannot express one. What
1623        // `accept_subgroup_stream` does beyond this - the forwarding-preference
1624        // note, the object measurement - is about a subgroup and has no
1625        // counterpart on a fetch stream.
1626        Ok((header, framed))
1627    }
1628
1629    /// Accept an incoming unidirectional data stream and read its subgroup
1630    /// header.
1631    pub async fn accept_subgroup_stream(
1632        &self,
1633    ) -> Result<(AnySubgroupHeader, FramedRecvStream), ConnectionError> {
1634        let recv = self.transport.accept_uni().await?;
1635        let mut framed = FramedRecvStream::new(recv);
1636        let sid = framed.stream_id();
1637        let header = framed.read_subgroup_header().await?;
1638        self.emit(ClientEvent::StreamOpened {
1639            direction: Direction::Receive,
1640            stream_kind: StreamKind::Subgroup,
1641            stream_id: sid,
1642        });
1643        self.emit(ClientEvent::DataStreamHeader {
1644            stream_id: sid,
1645            direction: Direction::Receive,
1646            header: header.clone(),
1647        });
1648        // Every object on a subgroup stream has the Subgroup preference, so
1649        // the header settles the track's framing before a single object is
1650        // read.
1651        self.note_received_framing(header.track_alias(), ObjectForwardingPreference::Subgroup)
1652            .await?;
1653        // The track is resolved here and not inside the stream: it takes the
1654        // endpoint's alias table, which a stream handle has no way back to.
1655        if let Some(objects) = self.endpoint.track_objects(header.track_alias()) {
1656            framed.measure_objects_against(objects, header.group_id());
1657        }
1658        Ok((header, framed))
1659    }
1660
1661    /// Send an object via datagram.
1662    ///
1663    /// The header goes through `AnyDatagramHeader::encode`, which refuses a
1664    /// header whose Object Status the framing it names cannot carry. Such a
1665    /// header errors here and nothing is sent, rather than going out as an
1666    /// ordinary payload datagram with the status quietly dropped.
1667    pub fn send_datagram(
1668        &self,
1669        header: &AnyDatagramHeader,
1670        payload: &[u8],
1671    ) -> Result<(), ConnectionError> {
1672        // Before anything is encoded, for the reason `open_subgroup_stream`
1673        // gives.
1674        self.endpoint.note_object_forwarding_preference(
1675            header.meta().track_alias,
1676            ObjectForwardingPreference::Datagram,
1677        )?;
1678        let mut buf = Vec::new();
1679        header.encode(&mut buf)?;
1680        buf.extend_from_slice(payload);
1681        self.emit(ClientEvent::DatagramReceived {
1682            direction: Direction::Send,
1683            header: header.clone(),
1684            payload_len: payload.len(),
1685        });
1686        self.transport.send_datagram(bytes::Bytes::from(buf))?;
1687        Ok(())
1688    }
1689
1690    /// Receive a datagram and decode it whole.
1691    ///
1692    /// An extension block announced with a length of 0 is returned as
1693    /// [`ConnectionError::EmptyDatagramExtensions`], which
1694    /// [`Connection::close_for_data_stream`] closes the session over.
1695    ///
1696    /// The codec's `Datagram::decode_object` then reads the whole datagram, and its
1697    /// refusals are returned as [`ConnectionError::Codec`]: an extension block that
1698    /// does not parse, a payload after a status, and a Prior Group ID Gap fault
1699    /// (draft-12 Section 10.1). A gap fault, [`CodecError::MalformedTrack`], makes
1700    /// the track malformed, and this withdraws from it before returning, as
1701    /// draft-12 Section 2.5 requires: "When a subscriber detects a Malformed Track,
1702    /// it MUST UNSUBSCRIBE from the Track and SHOULD deliver an error to the
1703    /// application." The session stays open.
1704    pub async fn recv_datagram(&self) -> Result<(AnyDatagramHeader, Bytes), ConnectionError> {
1705        let data = self.transport.recv_datagram().await?;
1706        let mut cursor = &data[..];
1707        let header = match AnyDatagramHeader::decode(DraftVersion::Draft12, &mut cursor) {
1708            Ok(header) => header,
1709            Err(CodecError::InvalidField) => {
1710                return Err(empty_datagram_extensions(&data)
1711                    .unwrap_or(ConnectionError::Codec(CodecError::InvalidField)));
1712            }
1713            Err(err) => return Err(err.into()),
1714        };
1715        let consumed = data.len() - cursor.len();
1716        let payload = data.slice(consumed..);
1717        self.emit(ClientEvent::DatagramReceived {
1718            direction: Direction::Receive,
1719            header: header.clone(),
1720            payload_len: payload.len(),
1721        });
1722        if let Err(err) =
1723            moqtap_codec::draft12::data_stream::Datagram::decode_object(&mut &data[..])
1724        {
1725            if let CodecError::MalformedTrack { .. } = err {
1726                self.withdraw_malformed_track(
1727                    header.meta().track_alias,
1728                    MalformedTrackCondition::PriorGroupIdGap,
1729                )
1730                .await;
1731            }
1732            return Err(err.into());
1733        }
1734        // A datagram is the other framing, and it settles the track's just as a
1735        // subgroup header does.
1736        self.note_received_framing(header.meta().track_alias, ObjectForwardingPreference::Datagram)
1737            .await?;
1738        // A datagram is a whole object, so the connection can measure it
1739        // without help from the caller.
1740        let meta = header.meta();
1741        if let Err(err) = self.endpoint.note_received_object(
1742            meta.track_alias,
1743            ObjectLocation { group: meta.group_id, object: meta.object_id },
1744            object_role(meta.status),
1745        ) {
1746            // One of the two rules that record answers is a Malformed Track,
1747            // and this path can give the answer itself: a datagram is read
1748            // through the connection, which is what an UNSUBSCRIBE takes. The
1749            // other rule ends the session and is the close table's.
1750            if matches!(err, EndpointError::ObjectPastFinalObject { .. }) {
1751                self.withdraw_malformed_track(
1752                    meta.track_alias,
1753                    MalformedTrackCondition::ObjectPastFinalObject,
1754                )
1755                .await;
1756            }
1757            return Err(err.into());
1758        }
1759        Ok((header, payload))
1760    }
1761
1762    // ── Accessors ───────────────────────────────────────────
1763
1764    /// Access the underlying endpoint state machine.
1765    pub fn endpoint(&self) -> &Endpoint {
1766        &self.endpoint
1767    }
1768
1769    /// Mutable access to the endpoint state machine.
1770    pub fn endpoint_mut(&mut self) -> &mut Endpoint {
1771        &mut self.endpoint
1772    }
1773
1774    /// The SETUP message the server answered the handshake with.
1775    ///
1776    /// `SERVER_SETUP` through draft-16, the server's half of the unified
1777    /// `SETUP` from draft-17. [`AnyControlMessage::fields`] renders it under
1778    /// this draft's own parameter names, in the order they arrived.
1779    pub fn server_setup(&self) -> &AnyControlMessage {
1780        &self.server_setup
1781    }
1782
1783    /// The framed wire bytes of [`Self::server_setup`], as they arrived.
1784    ///
1785    /// Kept beside the decoded form because the encoding is evidence the
1786    /// decoding discards: two relays sending the same parameter can still
1787    /// disagree on how wide a varint they wrote it in.
1788    pub fn server_setup_raw(&self) -> Option<&[u8]> {
1789        self.server_setup_raw.as_deref()
1790    }
1791
1792    /// Get the negotiated MoQT version.
1793    pub fn negotiated_version(&self) -> Option<VarInt> {
1794        self.endpoint.negotiated_version()
1795    }
1796
1797    /// Which of this draft's *own* `ConnectionError` variants this error is,
1798    /// and which kind of thing it says.
1799    ///
1800    /// The ten every draft carries answer `None` here: [`AnyConnectionError`]
1801    /// classifies those itself. Draft-12 adds two:
1802    /// [`ConnectionError::ControlMessageNarrowing`], a defect in this build, and
1803    /// [`ConnectionError::EmptyDatagramExtensions`], a decoder refusal the draft
1804    /// answers with a close.
1805    ///
1806    /// Matched exhaustively, with no wildcard arm and deliberately so: a
1807    /// variant added to this draft's error type has to arrive here as a compile
1808    /// error, beside the doc comment that quotes the sentence it enforces,
1809    /// rather than as a silent [`ErrorCause::Unclassified`] in the facade.
1810    ///
1811    /// [`AnyConnectionError`]: crate::dispatch::AnyConnectionError
1812    /// [`ErrorCause::Unclassified`]: crate::dispatch::ErrorCause::Unclassified
1813    pub fn draft_specific_cause(
1814        err: &ConnectionError,
1815    ) -> Option<crate::above_codec_rules::DraftSpecificCause> {
1816        match err {
1817            ConnectionError::Endpoint(_)
1818            | ConnectionError::Codec(_)
1819            | ConnectionError::Transport(_)
1820            | ConnectionError::VarInt(_)
1821            | ConnectionError::NoControlStream
1822            | ConnectionError::UnexpectedEnd
1823            | ConnectionError::StreamFinished
1824            | ConnectionError::InvalidAddress(_)
1825            | ConnectionError::TlsConfig(_)
1826            | ConnectionError::DataStreamState(_) => None,
1827            // This build decoding a message and then failing to narrow it to
1828            // its own draft. Nothing reached the wire and no peer is
1829            // implicated, which is the whole reason it is not
1830            // `ConnectionError::Codec`: under that name it would carry
1831            // `Some(PROTOCOL_VIOLATION)` out of `codec_session_error_code` and
1832            // publish a relay for this build's defect. See the variant's own
1833            // doc.
1834            ConnectionError::ControlMessageNarrowing => {
1835                Some(crate::above_codec_rules::DraftSpecificCause::LocalRefusal)
1836            }
1837            // The codec refuses the datagram as a bare `InvalidField`, and
1838            // `recv_datagram` names the rule, so `close_for_data_stream` reads
1839            // the close here. See the variant's own doc.
1840            ConnectionError::EmptyDatagramExtensions { .. } => {
1841                Some(crate::above_codec_rules::DraftSpecificCause::Codec {
1842                    error: CodecError::InvalidField,
1843                    close: Some(
1844                        moqtap_codec::draft12::error_codes::SessionErrorCode::ProtocolViolation
1845                            .as_u64(),
1846                    ),
1847                })
1848            }
1849        }
1850    }
1851
1852    /// The code to close the session with when a message could not be decoded
1853    /// because the peer broke a rule draft-12 answers with a close.
1854    ///
1855    /// Every variant listed here comes from a sentence in this draft that names
1856    /// the consequence, and the list is per draft: answering a bound this draft
1857    /// does not state would close a session over traffic a conforming peer may
1858    /// send.
1859    ///
1860    ///   - Reason Phrase, maximum 1024 bytes: "If an endpoint receives a length
1861    ///     exceeding the maximum, it MUST close the session with a Protocol
1862    ///     Violation."
1863    ///   - GOAWAY New Session URI, maximum 8,192 bytes, with the same sentence.
1864    ///     Drafts 11 through 19 state it; 07 through 10 state no maximum for
1865    ///     the field at all.
1866    ///   - Key-Value-Pair value, maximum 2^16-1 bytes, with the same sentence.
1867    ///   - Track Namespace tuple size: "If an endpoint receives a Track
1868    ///     Namespace tuple with an N of 0 or more than 32, it MUST close the
1869    ///     session with a Protocol Violation." Note the lower bound - an empty
1870    ///     tuple is refused here, where drafts 17 and later permit one.
1871    ///   - Full Track Name, maximum 4,096 bytes, "computed as the sum of the
1872    ///     lengths of each Track Namespace tuple field and the Track Name
1873    ///     length field". This draft bounds the pair and not the namespace
1874    ///     alone; draft-16 widened it.
1875    ///   - Duplicate parameters, a SHOULD rather than a MUST: "Receivers SHOULD
1876    ///     check that there are no unauthorized duplicate parameters and close
1877    ///     the session as a 'Protocol Violation' if found." The rule is
1878    ///     asymmetric here - "Receivers MUST allow duplicates of unknown
1879    ///     parameters", and one known type is granted repeats - and the codec
1880    ///     reports only the repeats this draft actually forbids.
1881    ///   - Unknown control message type: "An endpoint that receives an unknown
1882    ///     message type MUST close the session."
1883    ///   - Extension headers on an Object whose status is Object Does Not
1884    ///     Exist, Section 9.2.1.2. That one arrives on a data stream or a
1885    ///     datagram, so [`Connection::close_for_data_stream`] is what carries
1886    ///     it.
1887    ///
1888    /// **Not** the zero-length Track Namespace Field, the delta-encoded
1889    /// parameter type overflow, or the Object ID delta wrap. Those enter the
1890    /// specification at drafts 16 and 18, and this draft states none of them.
1891    ///
1892    /// **Not** the 2^16-1 control message length either. This draft states the
1893    /// limit - "the total length of a control message is limited to 2^16-1
1894    /// bytes" - and states no consequence for exceeding it, so an oversized
1895    /// message is refused by the decoder and stops there.
1896    ///
1897    /// **Not** [`CodecError::UnexpectedEnd`], which reports no rule at all: the
1898    /// reader raises it whenever a message is still arriving, and
1899    /// `read_control` loops on it. Closing over it would end a session on an
1900    /// ordinary short read.
1901    ///
1902    /// **Not** the unknown Message Parameter rule. Drafts 16 through 19 require
1903    /// a close for a Message Parameter whose type the negotiated version does
1904    /// not define. This draft states the opposite and states it about the same
1905    /// parameters: "Receivers MUST allow duplicates of unknown parameters",
1906    /// which presumes an unknown parameter arrives and is carried. Refusing one
1907    /// here would close a session over an extension this draft leaves room for.
1908    ///
1909    /// `None` for everything else, including [`CodecError::InvalidField`]. That
1910    /// variant is shared by a dozen unrelated malformations, only some of which
1911    /// the draft answers with a close, so a session cannot be ended on it
1912    /// without ending sessions the draft does not ask to be ended. Splitting it
1913    /// is the way to bring the rest of those rules under this function;
1914    /// widening the match is not - the extension-header rule above is
1915    /// answerable here because it has a variant of its own rather than being
1916    /// one more reading of `InvalidField`.
1917    pub fn codec_session_error_code(
1918        err: &CodecError,
1919    ) -> Option<moqtap_codec::draft12::error_codes::SessionErrorCode> {
1920        use moqtap_codec::draft12::error_codes::SessionErrorCode;
1921        use moqtap_codec::kvp::KvpError;
1922        match err {
1923            // The declared Length disagreeing with the fields, which every
1924            // draft answers with a close. Drafts 07 through 10 name no code for
1925            // it, so it takes the one their other unnamed rules take.
1926            CodecError::ControlMessageLengthMismatch { .. } => {
1927                Some(SessionErrorCode::ProtocolViolation)
1928            }
1929            CodecError::ReasonPhraseTooLong
1930            | CodecError::GoAwayUriTooLong
1931            | CodecError::InvalidNamespaceTupleSize(_)
1932            | CodecError::TrackNameTooLong
1933            | CodecError::DuplicateParameter(_)
1934            | CodecError::UnknownMessageType(_)
1935            | CodecError::ExtensionsOnNonExistentObject(_)
1936            | CodecError::Kvp(KvpError::ValueTooLong(_)) => {
1937                Some(SessionErrorCode::ProtocolViolation)
1938            }
1939            // An unknown data-plane type, Section 9: "An endpoint that
1940            // receives an unknown stream or datagram type MUST close the
1941            // session." One sentence covering two tables, which is why both
1942            // variants sit here.
1943            // A Content Exists field that is neither zero nor one,
1944            // Section 8.8 and Section 8.13: "Any other value is a protocol
1945            // error and MUST terminate the session with a Protocol Violation".
1946            CodecError::InvalidContentExists(_) => Some(SessionErrorCode::ProtocolViolation),
1947            // A Forward field that is neither zero nor one. Section 8.7 and
1948            // Section 8.10: "Any other value is a protocol error and MUST
1949            // terminate the session with a Protocol Violation". Section 8.13
1950            // says "Any value other than 0 or 1 is a Protocol Violation".
1951            // Section 8.14 names the two legal values without a consequence and
1952            // is answered the same way, for the reason given on the variant.
1953            CodecError::InvalidForward(_) => Some(SessionErrorCode::ProtocolViolation),
1954            CodecError::UnknownStreamType(_) | CodecError::UnknownDatagramType(_) => {
1955                Some(SessionErrorCode::ProtocolViolation)
1956            }
1957            // A key-value pair whose value is not the serialization its own
1958            // Type defines, Section 1.3.2: "If a receiver understands a Type,
1959            // and the following Value or Length/Value does not match the
1960            // serialization defined by that Type, the receiver MUST terminate the
1961            // session with error code 'Key-Value Formatting Error'."
1962            // Section 8.2.1.1 states the same answer for the one structure this
1963            // draft spells out: "If the Token structure cannot be decoded, the
1964            // receiver MUST close the Session with Key-Value Formatting error."
1965            //
1966            // The one rule in this table that names a code other than Protocol
1967            // Violation.
1968            CodecError::KeyValueFormatting { .. } => {
1969                Some(SessionErrorCode::KeyValueFormattingError)
1970            }
1971            // Everything this draft does not answer, named rather than swept up
1972            // by a wildcard. The arm is exhaustive deliberately: a new
1973            // `CodecError` variant will not compile until it has been placed on
1974            // one side or the other, on this draft, which is the decision a `_`
1975            // arm makes silently and invisibly in every draft module at once.
1976            //
1977            // Adding one variant to `CodecError` produces an `E0004` in every
1978            // draft module that matches it exhaustively, each naming the
1979            // variant that has nowhere to go. That is the whole mechanism.
1980            //
1981            // The nesting stops at `VarInt`, whose variants report how the bytes
1982            // ran out rather than a rule an endpoint states, so there is nothing
1983            // in it for a draft to answer. `Kvp` is spelled out because it does
1984            // carry one.
1985            // Not `ParameterValueOutOfRange`: no parameter this draft defines
1986            // restricts its value's range. Forwarding is a message field here
1987            // and is answered above.
1988            CodecError::ParameterValueOutOfRange { .. }
1989            | CodecError::UnexpectedEnd
1990            | CodecError::MessageTooLong(_)
1991            | CodecError::VarInt(_)
1992            | CodecError::InvalidField
1993            | CodecError::EmptyNamespaceField
1994            | CodecError::InvalidRange(..)
1995            | CodecError::ParameterLengthMismatch(_)
1996            | CodecError::EndOfTrackObjectId(_)
1997            | CodecError::KeyDeltaOverflow(..)
1998            // Not `TrackPropertyValueOutOfRange`: this draft has neither
1999            // namespace the variant is about. Draft-16 opens an extension header
2000            // registry with value rules of its own, and draft-17 renames it to
2001            // the Track Property registry. Before that, everything with a
2002            // restricted range is either a message field or a Message Parameter.
2003            | CodecError::TrackPropertyValueOutOfRange { .. }
2004            | CodecError::ParametersOutOfOrder(..)
2005            | CodecError::ObjectIdOverflow(..)
2006            | CodecError::InvalidRequiredRequestIdDelta(..)
2007            | CodecError::InvalidStreamTypeValue { .. }
2008            | CodecError::InvalidDatagramTypeValue { .. }
2009            | CodecError::UnknownMessageParameter(_)
2010            // Not `ParameterOutOfScope`: this draft states the scope rule and
2011            // answers it the other way. Section 8.2.1 Version Specific Parameters: "Each
2012            // version-specific parameter definition indicates the message types in which it can
2013            // appear. If it appears in some other type of message, it MUST be
2014            // ignored." The codec carries such a parameter on this draft and never
2015            // raises the variant, so this arm records a rule this draft has and
2016            // does not close over, not one it is missing. Draft-17 is where the
2017            // second sentence becomes a close.
2018            | CodecError::ParameterOutOfScope { .. }
2019            // A Filter Type outside the set this draft assigns. Section 8.7
2020            // states the rule and stops there: "A filter type other than the
2021            // above MUST be treated as error." No code, no close, and no
2022            // sentence elsewhere in the draft that turns an error into one — so
2023            // the message is refused and the session stays open.
2024            // Draft-14 Section 9.7 is where the same sentence gained "MUST be
2025            // close the session with PROTOCOL_VIOLATION", and it is answered
2026            // there.
2027            //
2028            // The assigned set is not the same on every draft either: 07 and 08
2029            // assign 0x1 as Latest Group, 09 and 10 withdraw it, and 11 and
2030            // later reinstate it as Next Group Start. The decoder holds each
2031            // draft to its own list; this arm only decides what a refusal does
2032            // to the session.
2033            //
2034            // The two rules below belong to the parameter form of the filter,
2035            // which arrives at draft-15. This draft carries the Filter Type as a
2036            // field of SUBSCRIBE, so there is no parameter for either to be
2037            // about.
2038            | CodecError::InvalidFilterType(_)
2039            | CodecError::SubscriptionFilterMalformed { .. }
2040            | CodecError::FilterEndGroupOverflow { .. }
2041            // A Fetch Type outside the set this draft assigns. Section 8.16
2042            // states the rule and stops there: "A Fetch Type other than 0x1,
2043            // 0x2 or 0x3 MUST be treated as an error", naming no code and no
2044            // close, exactly as this draft's Filter Type sentence does.
2045            // Draft-14 Section 9.16 is where both gained "MUST be close the
2046            // session with a PROTOCOL_VIOLATION", and it answers them there.
2047            | CodecError::InvalidFetchType(_)
2048            // The object payload rule, Section 9.2.1.1: "Any object with a status
2049            // code other than zero MUST have an empty payload." A MUST on the
2050            // sender with no receiver action named anywhere — the "SHOULD be
2051            // treated as a protocol error" in the same paragraph belongs to the
2052            // sentence before it, which is about a status value this draft does
2053            // not assign — so an object carrying a payload it may not is refused
2054            // and the session stays open.
2055            | CodecError::PayloadNotPermitted { .. }
2056            | CodecError::MalformedObjectProperties { .. }
2057            // A Prior Group ID Gap fault makes the track malformed
2058            // (draft-12 Section 10.1), which draft-12 Section 2.5 answers with
2059            // an UNSUBSCRIBE, through `withdraw_for_subgroup_stream`, and not a
2060            // close.
2061            | CodecError::MalformedTrack { .. }
2062            // Raised only by the draft-23 codec.
2063            | CodecError::ControlMessageExceedsLimit { .. }
2064            | CodecError::MissingErrorDetail { .. }
2065            | CodecError::MalformedErrorDetail { .. }
2066            | CodecError::TokenAliasInSetup { .. }
2067            | CodecError::EmptyTrackName
2068            | CodecError::MalformedAuthToken { .. }
2069            | CodecError::TrackPropertiesNotPermitted
2070            | CodecError::DeltaDecodingOverflow { .. }
2071            | CodecError::MalformedObject { .. }
2072            | CodecError::UnknownObjectStatus(_)
2073            | CodecError::UnsupportedDraft(_)
2074            | CodecError::Kvp(
2075                KvpError::MissingLength | KvpError::UnexpectedEnd | KvpError::VarInt(_),
2076            ) => None,
2077        }
2078    }
2079
2080    /// Close the session on the wire when a decode failure is one draft-12
2081    /// answers with a close, and hand the error back unchanged.
2082    /// Without it every bound the decoder enforces would stop at *this endpoint
2083    /// refused the frame* while the peer, which is the one that broke the rule,
2084    /// saw a session that was still open and went on sending. "MUST close the
2085    /// session" is a statement about the wire.
2086    fn close_for_codec(&self, err: ConnectionError) -> ConnectionError {
2087        if let ConnectionError::Codec(inner) = &err {
2088            if let Some(code) = Self::codec_session_error_code(inner) {
2089                // QUIC application error codes are 62-bit; every code in this
2090                // registry is far below `u32::MAX`, and saturating rather than
2091                // truncating means a future code that is not could never be
2092                // reported as a different, assigned one.
2093                let wire_code = u32::try_from(code.as_u64()).unwrap_or(u32::MAX);
2094                self.close(wire_code, inner.to_string().as_bytes());
2095            }
2096        }
2097        err
2098    }
2099
2100    /// Close the session on the wire when the endpoint says a violation is
2101    /// fatal to it, and hand the error back unchanged.
2102    ///
2103    /// [`EndpointError::session_error_code`] answers `Some` for exactly the
2104    /// errors this draft ends the session over, and the endpoint has already
2105    /// moved its own state machine to Closed by the time this runs. Without
2106    /// this step that move is purely internal: the local endpoint refuses to
2107    /// start anything new while the peer, which is the one that broke the
2108    /// rule, sees a session that is still open and goes on sending. A rule
2109    /// that names a session termination code is a statement about the wire,
2110    /// so it takes a CONNECTION_CLOSE to satisfy it.
2111    ///
2112    /// The reason phrase is the error's own `Display` text, which names the
2113    /// rule rather than repeating the numeric code the close already carries.
2114    ///
2115    /// Errors that answer `None` are recoverable and nothing is sent.
2116    fn close_for(&self, err: &EndpointError) {
2117        if let Some(code) = err.session_error_code() {
2118            // QUIC application error codes are 62-bit; every code in this
2119            // registry is far below `u32::MAX`, and saturating rather than
2120            // truncating means a future code that is not could never be
2121            // reported as a different, assigned one.
2122            let wire_code = u32::try_from(code.as_u64()).unwrap_or(u32::MAX);
2123            self.close(wire_code, err.to_string().as_bytes());
2124        }
2125    }
2126
2127    /// [`close_for`](Self::close_for), then the error unchanged, for the
2128    /// common case where the endpoint's error is also what the caller returns.
2129    fn close_if_session_fatal(&self, err: EndpointError) -> ConnectionError {
2130        self.close_for(&err);
2131        ConnectionError::Endpoint(err)
2132    }
2133
2134    /// Withdraw from a track a data stream found malformed, reporting whether
2135    /// it did.
2136    ///
2137    /// The Malformed Track twin of [`Connection::close_for_data_stream`], and
2138    /// separate from it for the same reason and one more. The same one: a
2139    /// [`FramedRecvStream`] holds no connection, so the reader that finds the
2140    /// fault is not the object that can send an UNSUBSCRIBE. The one more: the
2141    /// two answers are opposites — that call ends the session, this one gives
2142    /// up a track and leaves it running — and a single entry point would have
2143    /// to decide between them from the error alone, which is exactly the
2144    /// decision a caller reproducing a capture wants to make itself.
2145    ///
2146    /// The datagram path needs none of this. It is read through the connection,
2147    /// so [`Connection::recv_datagram`] answers the condition where it finds
2148    /// it, and this is only for the objects that arrive on a stream the caller
2149    /// holds.
2150    pub async fn withdraw_for_data_stream(&self, err: &ConnectionError) -> bool {
2151        let ConnectionError::Endpoint(EndpointError::ObjectPastFinalObject { alias, .. }) = err
2152        else {
2153            return false;
2154        };
2155        self.withdraw_malformed_track(*alias, MalformedTrackCondition::ObjectPastFinalObject).await;
2156        true
2157    }
2158
2159    /// [`Connection::withdraw_for_data_stream`] for an error read from the
2160    /// subgroup stream `header` opened, which also withdraws from the track
2161    /// over the [`CodecError::MalformedTrack`] that
2162    /// [`FramedRecvStream::read_subgroup_object`] returns for a Prior Group ID
2163    /// Gap fault (draft-12 Section 10.1). That error names no track, so the
2164    /// header supplies its alias.
2165    ///
2166    /// draft-12 Section 2.5: "When a subscriber detects a Malformed Track, it
2167    /// MUST UNSUBSCRIBE from the Track and SHOULD deliver an error to the
2168    /// application."
2169    pub async fn withdraw_for_subgroup_stream(
2170        &self,
2171        header: &AnySubgroupHeader,
2172        err: &ConnectionError,
2173    ) -> bool {
2174        if let ConnectionError::Codec(CodecError::MalformedTrack { .. }) = err {
2175            self.withdraw_malformed_track(
2176                header.track_alias(),
2177                MalformedTrackCondition::PriorGroupIdGap,
2178            )
2179            .await;
2180            return true;
2181        }
2182        self.withdraw_for_data_stream(err).await
2183    }
2184
2185    /// [`Connection::withdraw_for_data_stream`] for an error read from the fetch
2186    /// stream `header` opened, which also withdraws from the track the FETCH
2187    /// asked for over the [`CodecError::MalformedTrack`] that
2188    /// [`FramedRecvStream::read_fetch_object`] returns for a Prior Group ID Gap
2189    /// fault (draft-12 Section 10.1). That error names no track, so the header's
2190    /// Request ID supplies it.
2191    ///
2192    /// draft-12 Section 2.5: "When a subscriber detects a Malformed Track, it
2193    /// MUST UNSUBSCRIBE from the Track and SHOULD deliver an error to the
2194    /// application."
2195    pub async fn withdraw_for_fetch_stream(
2196        &self,
2197        header: &AnyFetchHeader,
2198        err: &ConnectionError,
2199    ) -> bool {
2200        let ConnectionError::Codec(CodecError::MalformedTrack { .. }) = err else {
2201            return self.withdraw_for_data_stream(err).await;
2202        };
2203        let condition = MalformedTrackCondition::PriorGroupIdGap;
2204        self.withdraw_malformed_fetch_track(header.request_id(), condition).await;
2205        true
2206    }
2207
2208    /// Close the session over a rule broken on a data stream, reporting whether
2209    /// it did.
2210    ///
2211    /// A data stream cannot close for itself the way `recv_control` does:
2212    /// [`Connection::accept_subgroup_stream`] hands the caller a
2213    /// [`FramedRecvStream`] holding no connection, so the reader that finds the
2214    /// violation is not the object that can act on it. Keeping it a separate
2215    /// call is deliberate as well - a permissive caller, one reproducing a
2216    /// capture, can read a violating stream and report it without tearing the
2217    /// session down.
2218    ///
2219    /// The rule this draft answers here is extension headers on an Object whose
2220    /// status is Object Does Not Exist, which reaches subgroup streams, fetch
2221    /// streams and status datagrams alike. It shares `codec_session_error_code`
2222    /// with the control path, so a rule is answered with one code whichever
2223    /// stream carried it.
2224    ///
2225    /// Not every rule that reaches here is the decoder's. A track whose objects
2226    /// mix forwarding preferences is the endpoint's to notice — it takes the
2227    /// alias table to know which track an object belongs to — and it arrives on
2228    /// exactly these streams. Both kinds are asked for a code the same way, and
2229    /// a rule with no code is declined rather than guessed at.
2230    pub fn close_for_data_stream(&self, err: &ConnectionError) -> bool {
2231        match err {
2232            ConnectionError::Codec(inner) => {
2233                let Some(code) = Self::codec_session_error_code(inner) else { return false };
2234                let wire_code = u32::try_from(code.as_u64()).unwrap_or(u32::MAX);
2235                self.close(wire_code, inner.to_string().as_bytes());
2236                true
2237            }
2238            // A rule the endpoint raises rather than the decoder. The two
2239            // reach their codes through different tables and mean the same
2240            // thing here: `Some` is a rule this draft ends the session over.
2241            ConnectionError::Endpoint(inner) => {
2242                let Some(code) = inner.session_error_code() else { return false };
2243                let wire_code = u32::try_from(code.as_u64()).unwrap_or(u32::MAX);
2244                self.close(wire_code, inner.to_string().as_bytes());
2245                true
2246            }
2247            // Not a `Codec` failure: the codec refuses the datagram as a bare
2248            // `InvalidField`, which `recv_datagram` names, so the code comes
2249            // from `draft_specific_cause`.
2250            ConnectionError::EmptyDatagramExtensions { .. } => {
2251                let Some(crate::above_codec_rules::DraftSpecificCause::Codec {
2252                    close: Some(code),
2253                    ..
2254                }) = Self::draft_specific_cause(err)
2255                else {
2256                    return false;
2257                };
2258                self.close(u32::try_from(code).unwrap_or(u32::MAX), err.to_string().as_bytes());
2259                true
2260            }
2261            _ => false,
2262        }
2263    }
2264
2265    /// Close the connection.
2266    pub fn close(&self, code: u32, reason: &[u8]) {
2267        self.emit(ClientEvent::Closed { code, reason: reason.to_vec() });
2268        self.transport.close(code, reason);
2269    }
2270}
2271
2272/// Determine the encoded length of a varint from its first byte.
2273fn varint_len(first_byte: u8) -> usize {
2274    1 << (first_byte >> 6)
2275}
2276
2277#[cfg(test)]
2278mod tests {
2279    use super::*;
2280
2281    /// This build failing to narrow a message it decoded is never a finding
2282    /// about the peer.
2283    ///
2284    /// The arm that raises `ControlMessageNarrowing` is unreachable — this
2285    /// draft's decoder can only hand back this draft's variant — and nothing
2286    /// pins that. What is pinned here is the half that matters.
2287    /// `CodecError::UnknownMessageType(0)` is what the arm must not raise:
2288    /// `codec_session_error_code` answers it `Some(PROTOCOL_VIOLATION)` on
2289    /// every draft in range, so the day the narrowing failed a conformance
2290    /// probe would publish a relay for sending a control message type this
2291    /// draft does not assign — with `0x00` attached as the codepoint that
2292    /// proved it, which is an accusation better evidenced than any real one
2293    /// this build makes. The section stating that rule is renumbered several
2294    /// times across the series, and the point does not turn on the
2295    /// number.
2296    ///
2297    /// Fails if the arm raises
2298    /// `ConnectionError::Codec(CodecError::UnknownMessageType(0))`, as does the
2299    /// probe's own `violation::a_message_this_build_could_not_narrow_names_nobody`.
2300    #[test]
2301    fn a_message_this_build_could_not_narrow_names_nobody() {
2302        use crate::dispatch::{AnyConnectionError, ErrorCause};
2303
2304        let err: AnyConnectionError = ConnectionError::ControlMessageNarrowing.into();
2305        assert!(err.is_local(), "a narrowing this build could not do is this build's");
2306        assert_eq!(
2307            err.cause(),
2308            &ErrorCause::Facade,
2309            "nothing reached the wire, so there is no rule and no close code to read"
2310        );
2311    }
2312
2313    /// Types 0x01, 0x03 and 0x05 carry extensions, so a zero byte where their
2314    /// Extension Headers Length sits is the close. Types 0x00, 0x02 and 0x04
2315    /// have no such field. The ruling is on `EmptyDatagramExtensions`.
2316    #[test]
2317    fn an_empty_extension_block_is_named_on_exactly_the_types_with_extensions() {
2318        for datagram_type in [0x00u8, 0x01, 0x02, 0x03, 0x04, 0x05] {
2319            let datagram = [datagram_type, 0x07, 0x01, 0x09, 0x80, 0x00, 0x00];
2320            let got = empty_datagram_extensions(&datagram);
2321            if matches!(datagram_type, 0x01 | 0x03 | 0x05) {
2322                assert!(
2323                    matches!(got, Some(ConnectionError::EmptyDatagramExtensions { object_id: 9 })),
2324                    "Type {datagram_type:#04x}: expected the close, got {got:?}"
2325                );
2326            } else {
2327                assert!(got.is_none(), "Type {datagram_type:#04x}: carries no extensions");
2328            }
2329        }
2330    }
2331
2332    #[test]
2333    fn client_config_supported_versions_default() {
2334        let config = ClientConfig {
2335            additional_versions: Vec::new(),
2336            transport: TransportType::Quic,
2337            skip_cert_verification: false,
2338            ca_certs: Vec::new(),
2339            setup_parameters: Vec::new(),
2340        };
2341        let versions = config.supported_versions();
2342        assert_eq!(versions.len(), 1);
2343        assert_eq!(versions[0].into_inner(), 0xff000000 + 12);
2344    }
2345
2346    #[test]
2347    fn client_config_alpn_quic() {
2348        let config = ClientConfig {
2349            additional_versions: Vec::new(),
2350            transport: TransportType::Quic,
2351            skip_cert_verification: false,
2352            ca_certs: Vec::new(),
2353            setup_parameters: Vec::new(),
2354        };
2355        assert_eq!(config.alpn(), vec![DraftVersion::Draft12.quic_alpn().to_vec()]);
2356    }
2357
2358    #[test]
2359    fn moqt_alpn_value() {
2360        assert_eq!(MOQT_ALPN, b"moq-00");
2361    }
2362}