Skip to main content

moqtap_client/draft21/
connection.rs

1use std::collections::VecDeque;
2use std::sync::Mutex;
3
4use bytes::{Buf, Bytes, BytesMut};
5
6use crate::draft21::endpoint::{Endpoint, EndpointError};
7use crate::draft21::event::{ClientEvent, Direction, StreamKind};
8use crate::draft21::fill::LocationFilter;
9use crate::draft21::observer::ConnectionObserver;
10use crate::draft21::session::request_id::Role;
11use crate::draft21::session::setup;
12use crate::malformed_tracks::MalformedTrackCondition;
13use crate::track_locations::{ObjectLocation, ObjectRole, TrackObjects};
14use crate::transport::{RecvStream, SendStream, Transport, TransportError};
15use moqtap_codec::dispatch::{
16    AnyControlMessage, AnyDatagramHeader, AnyFetchHeader, AnySubgroupHeader,
17};
18use moqtap_codec::draft21::data_stream::{
19    FetchHeader, FetchObject, FetchObjectHeader, FetchObjectReader, GroupOrder, SubgroupObject,
20    SubgroupObjectReader,
21};
22use moqtap_codec::draft21::error_codes::StreamResetErrorCode;
23use moqtap_codec::draft21::message::{
24    ControlMessage, FetchOk, MessageType, Namespace, NamespaceDone, PublishSkipped, RequestError,
25    RequestOk, SubscribeOk,
26};
27use moqtap_codec::error::CodecError;
28use moqtap_codec::kvp::KeyValuePair;
29use moqtap_codec::types::*;
30use moqtap_codec::varint::VarInt;
31use moqtap_codec::version::DraftVersion;
32
33/// The ALPN identifier draft-21 uses on raw QUIC, `moqt-21`.
34///
35/// Drafts 07 to 14 share one ALPN, `moq-00`, and a peer that offers it has
36/// said nothing about which of the eight it speaks. Draft-15 ended that:
37/// from there each draft has an ALPN of its own, so the version is settled
38/// by the TLS handshake before a byte of MoQT is written.
39///
40/// This is [`DraftVersion::Draft21`]'s own
41/// [`quic_alpn`](DraftVersion::quic_alpn), which is what
42/// [`ClientConfig::alpn`] offers; the test below holds the two together.
43pub const MOQT_ALPN: &[u8] = b"moqt-21";
44
45/// The unidirectional stream type that marks one direction of the control
46/// plane, and the SETUP message type. On draft-21 they are one number,
47/// 0x2F00: Section 6.4.1 (Unidirectional Stream Types) lists it as the type of
48/// a SETUP stream, and Section 9.1 gives it as the SETUP message's own type
49/// field.
50///
51/// Because they are the same number a control stream carries no separate
52/// stream header. The varint a reader uses to recognise the stream is the
53/// first field of the SETUP message it then decodes, and a writer that
54/// encodes a SETUP onto a fresh unidirectional stream has already written the
55/// stream type by writing the message.
56///
57/// Encoded with MoQT's variable-length integer, whose width is the number of
58/// leading 1 bits in the first byte, 0x2F00 is the two bytes `AF 00` — four
59/// under RFC 9000's encoding, which this draft does not use. Read it through
60/// [`DraftVersion::decode_varint`] rather than assuming a width.
61pub const CONTROL_STREAM_TYPE: u64 = 0x2F00;
62
63/// The unidirectional stream type of FETCH_HEADER, 0x05 (draft-21 Section 6.4.1).
64///
65/// A fill fetch stream opens with it too: draft-21 Section 3.4 has a
66/// subscription carrying FILL_PARAMETERS open "a unidirectional stream
67/// beginning with a FETCH_HEADER".
68const FETCH_STREAM_TYPE: u64 = 0x05;
69
70/// The application error code a request stream is reset with when the
71/// requester abandons it: `CANCELLED`, 0x1.
72///
73/// Draft-17 removed UNSUBSCRIBE and FETCH_CANCEL and draft-21 has not brought
74/// them back. Cancelling a request is resetting the bidirectional stream it
75/// was made on, and `CANCELLED` is the code draft-21 assigns for "the stream
76/// was cancelled by either endpoint" — see [`StreamResetErrorCode::Cancelled`].
77/// Taken from the codec's own registry rather than written as a literal so a
78/// renumbering in a later draft cannot be missed here.
79///
80/// This is what [`RequestStream::cancel`] uses when no code is chosen for it,
81/// and what `RequestStream`'s [`Drop`] sends.
82pub const REQUEST_CANCELLED: u64 = StreamResetErrorCode::Cancelled as u64;
83
84/// The application error code a request stream **the peer opened** is reset
85/// with when this endpoint abandons it: `INTERNAL_ERROR`, 0x0.
86///
87/// Dropping an inbound request is not the act [`REQUEST_CANCELLED`] describes.
88/// Draft-21 Section 6.4.2.3 grants a responder a cancel — "Receivers cancel
89/// requests if they are unable to or choose not to respond" — but a handle
90/// that fell out of scope chose nothing; it failed to serve, which is what
91/// [`StreamResetErrorCode::InternalError`], "an implementation specific
92/// error", names. The two codes are on the wire, so a peer counting refusals
93/// can tell a deliberate rejection from a dropped request only if they differ.
94///
95/// It is also what a responder that already answered is reset with when it is
96/// dropped without finishing. A FIN there would claim the request completed,
97/// and Section 6.4.2.2 says when it has not: "the publisher of an Established
98/// subscription MUST send PUBLISH_DONE, before sending a FIN."
99pub const REQUEST_UNANSWERED: u64 = StreamResetErrorCode::InternalError as u64;
100
101/// Errors from the connection layer.
102#[derive(Debug, thiserror::Error)]
103pub enum ConnectionError {
104    /// Endpoint state machine error.
105    #[error("endpoint error: {0}")]
106    Endpoint(#[from] EndpointError),
107    /// Wire codec error.
108    #[error("codec error: {0}")]
109    Codec(#[from] CodecError),
110    /// Transport-level error.
111    #[error("transport error: {0}")]
112    Transport(#[from] TransportError),
113    /// Variable-length integer decoding error.
114    #[error("varint error: {0}")]
115    VarInt(#[from] moqtap_codec::varint::VarIntError),
116    /// Control stream was not opened.
117    #[error("control stream not open")]
118    NoControlStream,
119    /// Stream ended before a complete message was read.
120    #[error("unexpected end of stream")]
121    UnexpectedEnd,
122    /// Stream was finished by the peer.
123    #[error("stream finished")]
124    StreamFinished,
125    /// Invalid server address string.
126    #[error("invalid server address: {0}")]
127    InvalidAddress(String),
128    /// TLS configuration error.
129    #[error("TLS config error: {0}")]
130    TlsConfig(String),
131    /// Data stream used out of order (e.g. object before header).
132    #[error("data stream state error: {0}")]
133    DataStreamState(&'static str),
134    /// A control message this build decoded for draft-21 and then could not
135    /// narrow to draft-21's own message type.
136    ///
137    /// Unreachable, and that is not the same as harmless. `read_control`
138    /// decodes with this connection's own draft, so the `AnyControlMessage` it
139    /// hands back can only carry this draft's variant — but the narrowing arm
140    /// is compiled in every configuration anyway, under
141    /// `#[allow(unreachable_patterns)]` rather than a `cfg` naming the other
142    /// drafts, because such a list has to be edited in every per-draft
143    /// module whenever a draft is added and a copy that omits one leaves the
144    /// match non-exhaustive.
145    ///
146    /// Spelled as `CodecError::UnknownMessageType(0)` it would not stay inert:
147    /// every draft's
148    /// [`codec_session_error_code`](Connection::codec_session_error_code)
149    /// answers that variant `Some(PROTOCOL_VIOLATION)`. So the day the
150    /// narrowing did fail, this build's own defect would reach a caller as *the
151    /// peer sent a control message type this draft does not assign, and the
152    /// session must be closed with a Protocol Violation* — carrying `0x00` as
153    /// the codepoint that proved it. A conformance report reading that
154    /// publishes a named, well-evidenced accusation against a relay for
155    /// something no relay did.
156    ///
157    /// A variant of its own is what stops that.
158    /// [`draft_specific_cause`](Connection::draft_specific_cause) answers it
159    /// [`LocalRefusal`], the facade turns that into [`ErrorCause::Facade`], and
160    /// nothing downstream can read a rule out of a cause that says nothing
161    /// reached the wire. What is pinned is the consequence rather than the
162    /// unreachability: nothing pins the arm's reachability, which is exactly
163    /// why the consequence must not be an accusation.
164    ///
165    /// [`LocalRefusal`]: crate::above_codec_rules::DraftSpecificCause::LocalRefusal
166    /// [`ErrorCause::Facade`]: crate::dispatch::ErrorCause::Facade
167    #[error(
168        "a control message decoded for draft-21 did not narrow to draft-21: a defect in this build, and evidence about nothing the peer did"
169    )]
170    ControlMessageNarrowing,
171    /// A message that begins a request stream was handed to
172    /// [`Connection::send_control`]. Nothing was written.
173    #[error(
174        "{0:?} begins a request stream of its own and must not be written on the control stream"
175    )]
176    RequestOnControlStream(MessageType),
177    /// A message draft-21 places on a request stream was handed to
178    /// [`Connection::send_control`]. Nothing was written.
179    ///
180    /// Distinct from [`ConnectionError::RequestOnControlStream`], which is about
181    /// a message that would *begin* a request stream of its own. This one is
182    /// about a message that belongs on a request stream already open, and so has
183    /// no meaning without one around it.
184    #[error("{0:?} belongs on a request stream, not on the control stream")]
185    RequestStreamMessageOnControlStream(MessageType),
186    /// The codec refused a datagram with [`CodecError::MalformedTrack`], for a
187    /// Prior Group ID Gap or Prior Object ID Gap fault (draft-21 Section 10.8,
188    /// draft-21 Section 10.9), or with [`CodecError::MalformedObjectProperties`],
189    /// for a property block that does not parse (draft-21 Section 10.7). Either
190    /// makes the datagram's track malformed.
191    ///
192    /// Carries the datagram's Track Alias, which the codec's error does not
193    /// name, so [`Connection::requests_to_cancel`] can name the requests to
194    /// cancel. The session stays open.
195    #[error("datagram for track alias {track_alias}: {error}")]
196    MalformedTrackDatagram {
197        /// The Track Alias the datagram named.
198        track_alias: u64,
199        /// The codec's refusal.
200        error: CodecError,
201    },
202    /// A datagram with the PROPERTIES bit set arrived with a Properties Length
203    /// of 0.
204    ///
205    /// draft-21 Section 11.2.1: "If an endpoint receives a datagram with the
206    /// PROPERTIES bit set and an Properties Length of 0, it MUST close the
207    /// session with a PROTOCOL_VIOLATION."
208    ///
209    /// [`Connection::recv_datagram`] checks the decoded header for it, and
210    /// [`Connection::close_for_data_stream`] closes the session over it.
211    #[error(
212        "the datagram for object {object_id} sets the PROPERTIES bit and has a Properties Length of 0"
213    )]
214    EmptyDatagramProperties {
215        /// The Object ID the datagram named.
216        object_id: u64,
217    },
218    /// A datagram carrying an Object Status arrived with bytes after its
219    /// header.
220    /// Draft-21 Section 11.1.2: "An Object MUST have an empty payload unless
221    /// its Object Status value is registered as permitting a payload in the
222    /// Object Status registry" Section 11.2.1 says the same thing about the
223    /// framing: a datagram with the STATUS bit set "is present and there is no
224    /// Object Payload."
225    ///
226    /// The codec cannot see this. `DatagramHeader::decode` stops at the end of
227    /// the header and never owns the datagram's tail, so the only layer that
228    /// holds both the status and the bytes after it is this one. Without the
229    /// check the application is handed, say, an End-of-Group object carrying
230    /// four bytes of payload — a combination the draft forbids outright.
231    ///
232    /// Recoverable: the drafts state the rule as a property of a conforming
233    /// object, not as one of the "MUST close the session" cases, so the datagram
234    /// is refused and the session left running.
235    #[error(
236        "datagram for object {object_id} carries {payload_len} bytes after a header \
237         whose status is {status:?}, which permits no payload"
238    )]
239    PayloadOnStatusDatagram {
240        /// Object ID from the datagram header.
241        object_id: u64,
242        /// How many bytes followed the header.
243        payload_len: usize,
244        /// The status the header declared.
245        ///
246        /// Spelled out in full because the glob import of `moqtap_codec::types`
247        /// brings a different `ObjectStatus` into this module.
248        status: Option<moqtap_codec::draft21::types::ObjectStatus>,
249    },
250    /// An Object arrived carrying properties on a status that is not Normal.
251    ///
252    /// Draft-21 Section 11.1.3: "Any Object with status Normal can have
253    /// properties (Section 8.4). If an endpoint receives properties on an
254    /// Object with status that is not Normal, it MUST close the session with a
255    /// PROTOCOL_VIOLATION."
256    ///
257    /// The codec's `read_object` refuses such an Object as a bare
258    /// `InvalidField`. Its `read_object_meta` frames it, which is how the
259    /// receive path names the rule here and stays in step with the wire.
260    #[error(
261        "object {object_id} carries {properties_len} bytes of properties on status {status:?}, \
262         which is not Normal"
263    )]
264    PropertiesOnNonNormalStatus {
265        /// The Object ID the properties arrived on.
266        object_id: u64,
267        /// Length in bytes of the properties block.
268        properties_len: usize,
269        /// The Object's status, resolved through the encoding's elision rule.
270        ///
271        /// Spelled out in full because the glob import of `moqtap_codec::types`
272        /// brings a different `ObjectStatus` into this module.
273        status: moqtap_codec::draft21::types::ObjectStatus,
274    },
275    /// A bidirectional stream the peer opened began with a message type that
276    /// does not open a request stream.
277    ///
278    /// Draft-21 Section 6.3: "Bidirectional streams MUST NOT begin with any
279    /// other message type unless negotiated. If they do, the peer MUST close
280    /// the Session with a PROTOCOL_VIOLATION." The session has already been
281    /// closed on the wire by the time this is returned, and the offending
282    /// stream reset.
283    #[error(
284        "a bidirectional stream the peer opened began with {0:?}, which does not begin a request stream; the session was closed"
285    )]
286    NonRequestOnRequestStream(MessageType),
287    /// A `respond_*` helper was handed a request stream this endpoint opened.
288    /// Nothing was written and no state moved.
289    #[error(
290        "this endpoint opened request {0}; only the endpoint a request stream was opened toward may answer it"
291    )]
292    RespondedToOwnRequest(u64),
293    /// [`RequestStream::finish`] was called on a request stream the peer opened
294    /// before a response had been written on it. Nothing was written.
295    ///
296    /// Draft-21 Section 6.4.2.2: "An endpoint MUST NOT send a FIN on a direction
297    /// of a request stream until it has sent all required messages on that
298    /// direction for its request type. In particular, an endpoint sending a
299    /// response to a request MUST send the corresponding response message ...
300    /// before sending a FIN." The section arrived in draft-19 and draft-21
301    /// keeps it verbatim; drafts 17 and 18 have no such rule and no such
302    /// guard.
303    #[error(
304        "request {0} has not been answered; draft-21 Section 6.4.2.2 forbids finishing a request stream before its response"
305    )]
306    FinBeforeResponse(u64),
307    /// [`RequestStream::finish`] was called on a subscription this endpoint is
308    /// the publisher of, before PUBLISH_DONE. Nothing was written.
309    ///
310    /// The second half of the same sentence in draft-21 Section 6.4.2.2: "the
311    /// publisher of an Established subscription MUST send PUBLISH_DONE, before
312    /// sending a FIN." It applies to the accepted SUBSCRIBE a responder
313    /// answered with SUBSCRIBE_OK and to the PUBLISH this endpoint sent, which
314    /// is why [`Connection::publish_done`] and
315    /// [`Connection::publish_done_on`] are the only routes that clear it.
316    #[error(
317        "request {0} is an established subscription; draft-21 Section 6.4.2.2 requires PUBLISH_DONE before a FIN"
318    )]
319    FinBeforePublishDone(u64),
320}
321
322impl From<crate::transport::DialError> for ConnectionError {
323    /// Maps a dial failure onto the variants this error already has, so a
324    /// caller matches `InvalidAddress` or `TlsConfig`.
325    ///
326    /// A `LocalSocket` failure maps to `InvalidAddress`, which the facade reads
327    /// as this side's failure
328    /// ([`ErrorCause::Facade`](crate::dispatch::ErrorCause::Facade)). The dial
329    /// phase stays on [`DialError::phase`](crate::transport::DialError::phase).
330    fn from(e: crate::transport::DialError) -> Self {
331        match e {
332            // Two variants, one arm, deliberately — see above.
333            crate::transport::DialError::InvalidAddress(s)
334            | crate::transport::DialError::LocalSocket(s) => ConnectionError::InvalidAddress(s),
335            crate::transport::DialError::TlsConfig(s) => ConnectionError::TlsConfig(s),
336            crate::transport::DialError::Transport(e) => ConnectionError::Transport(e),
337        }
338    }
339}
340
341/// Transport type for the connection.
342#[derive(Debug, Clone)]
343pub enum TransportType {
344    /// Raw QUIC via quinn. The `addr` field should be `host:port`.
345    Quic,
346    /// WebTransport via wtransport. The `url` field is the WebTransport URL.
347    WebTransport {
348        /// The WebTransport endpoint URL (e.g., `https://host:port/path`).
349        url: String,
350    },
351}
352
353/// Configuration for a MoQT client connection.
354///
355/// Both `draft` and `transport` are required -- there is no `Default` impl.
356pub struct ClientConfig {
357    /// The MoQT draft version to use (primary, determines codec/framing).
358    pub draft: DraftVersion,
359    /// The transport type (QUIC or WebTransport).
360    pub transport: TransportType,
361    /// Whether to skip TLS certificate verification (for testing).
362    pub skip_cert_verification: bool,
363    /// Custom CA certificates to trust (DER-encoded).
364    pub ca_certs: Vec<Vec<u8>>,
365    /// Setup parameters to include in CLIENT_SETUP (e.g., auth tokens).
366    pub setup_parameters: Vec<KeyValuePair>,
367}
368
369impl ClientConfig {
370    /// Returns the ALPN protocol identifiers for the transport.
371    pub fn alpn(&self) -> Vec<Vec<u8>> {
372        match &self.transport {
373            TransportType::Quic => vec![self.draft.quic_alpn().to_vec()],
374            TransportType::WebTransport { .. } => vec![b"h3".to_vec()],
375        }
376    }
377}
378
379/// A framed writer for a send stream. Handles MoQT length-prefixed framing.
380pub struct FramedSendStream {
381    inner: SendStream,
382    draft: DraftVersion,
383    /// Stateful subgroup object writer.
384    subgroup_io: Option<SubgroupObjectReader>,
385}
386
387impl FramedSendStream {
388    /// Create a new framed send stream for the given draft version.
389    pub fn new(inner: SendStream, draft: DraftVersion) -> Self {
390        Self { inner, draft, subgroup_io: None }
391    }
392
393    /// Get the transport-level stream ID.
394    pub fn stream_id(&self) -> u64 {
395        self.inner.stream_id()
396    }
397
398    /// Write a control message to the stream with type+length framing.
399    /// Returns the raw bytes that were written (for event capture).
400    pub async fn write_control(
401        &mut self,
402        msg: &AnyControlMessage,
403    ) -> Result<Vec<u8>, ConnectionError> {
404        let mut buf = Vec::new();
405        msg.encode(&mut buf)?;
406        self.inner.write_all(&buf).await?;
407        Ok(buf)
408    }
409
410    /// Write a subgroup stream header. Also initializes the internal
411    /// delta-encoding state used by
412    /// [`FramedSendStream::write_subgroup_object`].
413    ///
414    /// The header is refused, and nothing is written, if its fields disagree
415    /// with its own stream type. That check has to happen here rather than at
416    /// the first object: the type is what every object after it is framed
417    /// against, so a header that went out saying the wrong thing cannot be
418    /// taken back.
419    pub async fn write_subgroup_header(
420        &mut self,
421        header: &AnySubgroupHeader,
422    ) -> Result<(), ConnectionError> {
423        let mut buf = Vec::new();
424        header.encode_stream_checked(&mut buf)?;
425        self.inner.write_all(&buf).await?;
426        // Clippy would rather see these two arms as an `if let`, and rustc rejects
427        // that in a single-draft build, where the pattern is irrefutable. Only a
428        // `match` satisfies both.
429        #[allow(clippy::single_match)]
430        match header {
431            AnySubgroupHeader::Draft21(ref header) => {
432                self.subgroup_io = Some(SubgroupObjectReader::new(header));
433            }
434            // Only this draft's header seeds the object reader. With draft 21 the only enabled
435            // draft `AnySubgroupHeader` has a single variant, the arm above is exhaustive and this
436            // one unreachable. Compiled in every configuration with the lint allowed, rather than
437            // gated on a `cfg` naming the other drafts: such a list has to be edited in
438            // every draft module whenever a draft is added, and a copy that omits one leaves this
439            // match non-exhaustive.
440            #[allow(unreachable_patterns)]
441            _ => {}
442        }
443        Ok(())
444    }
445
446    /// Write a fetch response header.
447    pub async fn write_fetch_header(
448        &mut self,
449        header: &AnyFetchHeader,
450    ) -> Result<(), ConnectionError> {
451        let mut buf = Vec::new();
452        header.encode_stream(&mut buf);
453        self.inner.write_all(&buf).await?;
454        Ok(())
455    }
456
457    /// Append a draft-21 subgroup object to the stream using the
458    /// stateful writer seeded from
459    /// [`FramedSendStream::write_subgroup_header`].
460    pub async fn write_subgroup_object(
461        &mut self,
462        object: &SubgroupObject,
463    ) -> Result<(), ConnectionError> {
464        let writer = self
465            .subgroup_io
466            .as_mut()
467            .ok_or(ConnectionError::DataStreamState("subgroup header not written yet"))?;
468        let mut buf = Vec::new();
469        writer.write_object(object, &mut buf)?;
470        self.inner.write_all(&buf).await?;
471        Ok(())
472    }
473
474    /// Append a fetch object to the stream.
475    ///
476    /// The fetch stream had a header writer and no object writer, so a caller
477    /// could open one and put nothing on it through this type. The subgroup
478    /// stream has had both since the writer was introduced.
479    ///
480    /// The declared length comes from the payload rather than from the caller's
481    /// field: a header that disagrees with the bytes beside it desynchronises
482    /// every object after it on the stream, and nothing downstream can recover.
483    ///
484    /// # Errors
485    ///
486    /// [`ConnectionError::Codec`] if the header's fields disagree with the
487    /// Serialization Flags that announce them, which the encoder refuses rather
488    /// than writing a frame its own reader cannot take apart.
489    pub async fn write_fetch_object(
490        &mut self,
491        header: &FetchObjectHeader,
492        payload: &[u8],
493    ) -> Result<(), ConnectionError> {
494        let mut header = header.clone();
495        header.payload_length = VarInt::from_usize(payload.len());
496        let mut buf = Vec::new();
497        header.encode(&mut buf)?;
498        buf.extend_from_slice(payload);
499        self.inner.write_all(&buf).await?;
500        Ok(())
501    }
502
503    /// Finish the stream (send FIN).
504    pub async fn finish(&mut self) -> Result<(), ConnectionError> {
505        self.inner.finish()?;
506        Ok(())
507    }
508
509    /// Reset the stream with `code`, telling the peer transmission was
510    /// abandoned rather than completed.
511    ///
512    /// Dropping a send stream sends a FIN, which claims the stream ended
513    /// cleanly; this is the only way to say the opposite. See
514    /// [`SendStream::reset`].
515    pub fn reset(&mut self, code: u64) -> Result<(), ConnectionError> {
516        self.inner.reset(code)?;
517        Ok(())
518    }
519
520    /// Returns the draft version this stream is framed for.
521    pub fn draft(&self) -> DraftVersion {
522        self.draft
523    }
524}
525
526/// What an Object Status makes of an object here.
527///
528/// Two answers where drafts 08 through 13 have three, and the missing one is
529/// the point: the end-of-track status settles where the track ended and is
530/// judged against nothing, because the rule about where one may be placed is
531/// not in this draft. `a_track_may_end_where_it_has_already_been.rs` asserts
532/// that acceptance.
533///
534/// Every other status is a statement about objects rather than one of them.
535fn object_role(status: Option<u64>) -> ObjectRole {
536    match status {
537        None | Some(0x0) => ObjectRole::Produced,
538        Some(0x4) => ObjectRole::EndsTrack(None),
539        _ => ObjectRole::Neither,
540    }
541}
542
543/// A framed reader for a recv stream. Handles MoQT varint-length decoding.
544pub struct FramedRecvStream {
545    inner: RecvStream,
546    buf: BytesMut,
547    draft: DraftVersion,
548    /// Stateful subgroup object reader.
549    subgroup_io: Option<SubgroupObjectReader>,
550    /// Stateful fetch object reader, started by
551    /// [`FramedRecvStream::begin_fetch_objects`] rather than by the fetch
552    /// header, which does not carry the order.
553    fetch_io: Option<FetchObjectReader>,
554    /// The record this stream's objects are measured against, and the Group ID
555    /// its header named.
556    ///
557    /// One group for the whole stream: a subgroup header names it once and no
558    /// object header repeats it. `None` on a stream that was never given one -
559    /// a stream for an alias no live binding names, and every stream built
560    /// outside [`Connection::accept_subgroup_stream`].
561    tracking: Option<(TrackObjects, u64)>,
562}
563
564impl FramedRecvStream {
565    /// Create a new framed receive stream for the given draft version.
566    pub fn new(inner: RecvStream, draft: DraftVersion) -> Self {
567        Self {
568            inner,
569            buf: BytesMut::with_capacity(4096),
570            draft,
571            subgroup_io: None,
572            fetch_io: None,
573            tracking: None,
574        }
575    }
576
577    /// Get the transport-level stream ID.
578    pub fn stream_id(&self) -> u64 {
579        self.inner.stream_id()
580    }
581
582    /// Measure this stream's objects against `objects`, all of them in `group`.
583    fn measure_objects_against(&mut self, objects: TrackObjects, group: u64) {
584        self.tracking = Some((objects, group));
585    }
586
587    /// Judge one object this stream carried against where its track ended.
588    fn note_subgroup_object(
589        &self,
590        object: u64,
591        status: Option<u64>,
592    ) -> Result<(), ConnectionError> {
593        let Some((objects, group)) = &self.tracking else { return Ok(()) };
594        let at = ObjectLocation { group: *group, object };
595        objects.note_past_final(at, object_role(status)).map_err(|end| {
596            ConnectionError::Endpoint(EndpointError::ObjectPastFinalObject {
597                alias: objects.alias(),
598                group: at.group,
599                object: at.object,
600                final_group: end.group,
601                final_object: end.object,
602            })
603        })
604    }
605
606    /// Read more data from the stream into the internal buffer.
607    async fn fill(&mut self) -> Result<bool, ConnectionError> {
608        let mut tmp = [0u8; 4096];
609        match self.inner.read(&mut tmp).await {
610            Ok(Some(n)) => {
611                self.buf.extend_from_slice(&tmp[..n]);
612                Ok(true)
613            }
614            Ok(None) => Ok(false),
615            Err(e) => Err(ConnectionError::Transport(e)),
616        }
617    }
618
619    /// Ensure at least `n` bytes are available in the buffer.
620    async fn ensure(&mut self, n: usize) -> Result<(), ConnectionError> {
621        while self.buf.len() < n {
622            if !self.fill().await? {
623                return Err(ConnectionError::UnexpectedEnd);
624            }
625        }
626        Ok(())
627    }
628
629    /// Read this stream's leading variable-length integer **without
630    /// consuming it**, and return its value.
631    ///
632    /// Every unidirectional MoQT stream on draft-21 opens with a varint
633    /// naming what it is (Section 6.4.1): 0x05 for FETCH_HEADER, 0x10-0x1D for
634    /// SUBGROUP_HEADER, and [`CONTROL_STREAM_TYPE`] for SETUP. Telling the
635    /// peer's control stream apart from a data stream means reading that
636    /// varint, and taking it off the transport would destroy it: the control
637    /// stream's type varint *is* the SETUP message's type field, so a stream
638    /// whose type had been stripped would no longer decode as a SETUP.
639    ///
640    /// Nothing is stripped. The bytes land in this reader's own buffer, and
641    /// every other method here — [`read_control`](Self::read_control),
642    /// [`read_subgroup_header`](Self::read_subgroup_header),
643    /// [`read_fetch_header`](Self::read_fetch_header) — decodes out of that
644    /// buffer and advances it only on a successful decode. A stream this was
645    /// called on is indistinguishable from one it was not, which is what
646    /// makes it safe to peek a stream and then hand it to whichever reader
647    /// the type turned out to call for.
648    ///
649    /// It reads, so it can block: a peer that opens a stream and then writes
650    /// nothing leaves this pending until a byte arrives or the stream ends.
651    ///
652    /// # Errors
653    ///
654    /// - [`ConnectionError::UnexpectedEnd`] if the stream ends before a whole
655    ///   varint has arrived.
656    /// - [`ConnectionError::Transport`] if the peer reset the stream.
657    /// - [`ConnectionError::VarInt`] if the bytes are not a valid varint.
658    ///
659    /// Whatever did arrive stays in the buffer in every case.
660    pub async fn peek_stream_type(&mut self) -> Result<u64, ConnectionError> {
661        self.ensure(1).await?;
662        let type_len = self.draft.varint_len(self.buf[0]);
663        self.ensure(type_len).await?;
664        let mut cursor = &self.buf[..type_len];
665        Ok(self.draft.decode_varint(&mut cursor)?.into_inner())
666    }
667
668    /// Read a control message from the stream.
669    ///
670    /// When `capture_raw` is true, the returned tuple includes a clone of the
671    /// framed wire bytes (for observer emission). When false, the second
672    /// element is `None` and the payload clone is skipped.
673    pub async fn read_control(
674        &mut self,
675        capture_raw: bool,
676    ) -> Result<(AnyControlMessage, Option<Vec<u8>>), ConnectionError> {
677        // Read type ID varint
678        self.ensure(1).await?;
679        let type_len = self.draft.varint_len(self.buf[0]);
680        self.ensure(type_len).await?;
681
682        let mut cursor = &self.buf[..type_len];
683        let _type_id = self.draft.decode_varint(&mut cursor)?;
684
685        // Draft-21: 16-bit BE payload length
686        let (payload_len, len_field_size) = if self.draft.uses_fixed_length_framing() {
687            self.ensure(type_len + 2).await?;
688            let hi = self.buf[type_len] as usize;
689            let lo = self.buf[type_len + 1] as usize;
690            ((hi << 8) | lo, 2)
691        } else {
692            self.ensure(type_len + 1).await?;
693            let payload_len_start = type_len;
694            let payload_len_varint_len = self.draft.varint_len(self.buf[payload_len_start]);
695            self.ensure(type_len + payload_len_varint_len).await?;
696            let mut cursor = &self.buf[payload_len_start..type_len + payload_len_varint_len];
697            let payload_len = self.draft.decode_varint(&mut cursor)?.into_inner() as usize;
698            (payload_len, payload_len_varint_len)
699        };
700
701        // Read full payload
702        let total = type_len + len_field_size + payload_len;
703        self.ensure(total).await?;
704
705        // Capture raw bytes only if requested (observer attached).
706        let raw = capture_raw.then(|| self.buf[..total].to_vec());
707
708        // Now decode the whole message
709        let mut frame = &self.buf[..total];
710        let msg = AnyControlMessage::decode(self.draft, &mut frame)?;
711        self.buf.advance(total);
712        Ok((msg, raw))
713    }
714
715    /// Read a subgroup stream header. Also initializes the internal
716    /// delta-decoding state.
717    pub async fn read_subgroup_header(&mut self) -> Result<AnySubgroupHeader, ConnectionError> {
718        self.ensure(1).await?;
719        loop {
720            let mut cursor = &self.buf[..];
721            match AnySubgroupHeader::decode(self.draft, &mut cursor) {
722                Ok(header) => {
723                    let consumed = self.buf.len() - cursor.remaining();
724                    self.buf.advance(consumed);
725                    // Clippy would rather see these two arms as an `if let`, and rustc rejects
726                    // that in a single-draft build, where the pattern is irrefutable. Only a
727                    // `match` satisfies both.
728                    #[allow(clippy::single_match)]
729                    match header {
730                        AnySubgroupHeader::Draft21(ref header) => {
731                            self.subgroup_io = Some(SubgroupObjectReader::new(header));
732                        }
733                        // Only this draft's header seeds the object reader. With draft 21 the only
734                        // enabled draft `AnySubgroupHeader` has a single variant, the arm above is
735                        // exhaustive and this one unreachable. Compiled in every configuration with
736                        // the lint allowed, rather than gated on a `cfg` naming every other
737                        // draft: such a list has to be edited in every draft module whenever a
738                        // draft is added, and a copy that omits one leaves this match
739                        // non-exhaustive.
740                        #[allow(unreachable_patterns)]
741                        _ => {}
742                    }
743                    return Ok(header);
744                }
745                Err(e) if e.is_incomplete() => {
746                    if !self.fill().await? {
747                        return Err(ConnectionError::UnexpectedEnd);
748                    }
749                }
750                Err(e) => return Err(ConnectionError::Codec(e)),
751            }
752        }
753    }
754
755    /// Read a fetch response header.
756    pub async fn read_fetch_header(&mut self) -> Result<AnyFetchHeader, ConnectionError> {
757        self.ensure(1).await?;
758        loop {
759            let mut cursor = &self.buf[..];
760            match AnyFetchHeader::decode(self.draft, &mut cursor) {
761                Ok(header) => {
762                    let consumed = self.buf.len() - cursor.remaining();
763                    self.buf.advance(consumed);
764                    return Ok(header);
765                }
766                Err(e) if e.is_incomplete() => {
767                    if !self.fill().await? {
768                        return Err(ConnectionError::UnexpectedEnd);
769                    }
770                }
771                Err(e) => return Err(ConnectionError::Codec(e)),
772            }
773        }
774    }
775
776    /// Read the next draft-21 subgroup object from this stream using
777    /// the stateful reader seeded by
778    /// [`FramedRecvStream::read_subgroup_header`].
779    ///
780    /// Errors with [`ConnectionError::PropertiesOnNonNormalStatus`] on an
781    /// Object that carries properties on a status other than Normal, which
782    /// draft-21 Section 11.1.3 answers with a session close. The object is
783    /// consumed from the stream before the check, so the reader stays in step
784    /// with the wire and a caller that reports the violation and reads on sees
785    /// the following object rather than a re-parse of this one.
786    pub async fn read_subgroup_object(&mut self) -> Result<SubgroupObject, ConnectionError> {
787        if self.subgroup_io.is_none() {
788            return Err(ConnectionError::DataStreamState("subgroup header not read yet"));
789        }
790        loop {
791            let reader = self.subgroup_io.as_mut().unwrap();
792            let mut probe = reader.clone();
793            let mut cursor = &self.buf[..];
794            match probe.read_object(&mut cursor) {
795                Ok(obj) => {
796                    let consumed = self.buf.len() - cursor.remaining();
797                    self.buf.advance(consumed);
798                    *reader = probe;
799                    if !obj.properties_permitted() {
800                        return Err(ConnectionError::PropertiesOnNonNormalStatus {
801                            object_id: obj.object_id.into_inner(),
802                            properties_len: obj.extension_headers.len(),
803                            status: obj.status(),
804                        });
805                    }
806                    self.note_subgroup_object(
807                        obj.object_id.into_inner(),
808                        obj.object_status.map(|s| s as u64),
809                    )?;
810                    return Ok(obj);
811                }
812                Err(e) if e.is_incomplete() => {
813                    if !self.fill().await? {
814                        return Err(ConnectionError::UnexpectedEnd);
815                    }
816                }
817                // The codec refuses properties on a non-Normal status as
818                // `InvalidField`, one of many readings of that variant. Its
819                // framing-only reader accepts them, which tells this case apart
820                // from the others and keeps the stream in step.
821                Err(CodecError::InvalidField) => {
822                    let mut framing = reader.clone();
823                    let mut cursor = &self.buf[..];
824                    if let Ok(meta) = framing.read_object_meta(&mut cursor) {
825                        let status = meta
826                            .status
827                            .and_then(moqtap_codec::draft21::types::ObjectStatus::from_u64);
828                        if let Some(status) = status.filter(|s| {
829                            meta.extension_headers_len > 0
830                                && *s != moqtap_codec::draft21::types::ObjectStatus::Normal
831                        }) {
832                            let consumed = self.buf.len() - cursor.remaining();
833                            self.buf.advance(consumed);
834                            *reader = framing;
835                            return Err(ConnectionError::PropertiesOnNonNormalStatus {
836                                object_id: meta.object_id,
837                                properties_len: meta.extension_headers_len as usize,
838                                status,
839                            });
840                        }
841                    }
842                    return Err(ConnectionError::Codec(CodecError::InvalidField));
843                }
844                Err(e) => return Err(ConnectionError::Codec(e)),
845            }
846        }
847    }
848
849    /// Read the next draft-21 fetch header from this stream.
850    pub async fn read_fetch_stream_header(&mut self) -> Result<FetchHeader, ConnectionError> {
851        loop {
852            let mut cursor = &self.buf[..];
853            match FetchHeader::decode(&mut cursor) {
854                Ok(hdr) => {
855                    let consumed = self.buf.len() - cursor.remaining();
856                    self.buf.advance(consumed);
857                    return Ok(hdr);
858                }
859                Err(e) if e.is_incomplete() => {
860                    if !self.fill().await? {
861                        return Err(ConnectionError::UnexpectedEnd);
862                    }
863                }
864                Err(e) => return Err(ConnectionError::Codec(e)),
865            }
866        }
867    }
868
869    /// Stop accepting data on this stream with `code` as the `STOP_SENDING`
870    /// application error code, discarding anything unread.
871    ///
872    /// Dropping a receive stream also stops it, but with a hard-coded 0. See
873    /// [`RecvStream::stop`].
874    pub fn stop(&mut self, code: u64) -> Result<(), ConnectionError> {
875        self.inner.stop(code)?;
876        Ok(())
877    }
878
879    /// Wait for the peer to reset this stream, consuming nothing.
880    ///
881    /// See [`RecvStream::received_reset`] for what `Ok(None)` means and why a
882    /// caller must not re-poll after it.
883    pub async fn received_reset(&mut self) -> Result<Option<u64>, ConnectionError> {
884        Ok(self.inner.received_reset().await?)
885    }
886
887    /// Start reading fetch objects on this stream, in a response whose Groups
888    /// arrive in `group_order`.
889    ///
890    /// Draft-21 has to be told, as draft-18 does. Section 11.4.1.1 makes a
891    /// Group ID Delta count downward under Descending and upward under
892    /// Ascending, so the same bytes are two different Locations and nothing on
893    /// the data stream says which. The order is the one the **request** asked
894    /// for — Section 9.11: "The publisher responding to a FETCH is
895    /// responsible for delivering all available Objects in the requested range
896    /// in the requested order (see Section 9.20.9)" — carried by the
897    /// GROUP_ORDER parameter on the FETCH, or by its absence, which Section
898    /// 9.20.9 reads as Ascending. Either way it is a control message this
899    /// stream never sees. Drafts 15, 16 and 17 resolve their fetch objects
900    /// without an order, because none of those drafts encodes an ID as a
901    /// difference.
902    ///
903    /// Call it after [`FramedRecvStream::read_fetch_header`] and before the
904    /// first [`FramedRecvStream::read_fetch_object`]; calling it again restarts
905    /// the running state, which is what a second fetch stream on the same
906    /// connection would want and what the middle of one would not.
907    pub fn begin_fetch_objects(&mut self, group_order: GroupOrder) {
908        self.fetch_io = Some(FetchObjectReader::new(group_order));
909    }
910
911    /// Read the next draft-21 fetch object and its payload.
912    ///
913    /// The mirror of [`FramedSendStream::write_fetch_object`]. What comes back
914    /// is a [`FetchObject`] rather than a header: draft-21's reader resolves the
915    /// delta-encoded fields, so the Group ID, Subgroup ID, Object ID and
916    /// Priority it carries are the frame's own values rather than differences
917    /// from the frame before. `object.header` is the frame exactly as it
918    /// arrived, for a caller forwarding the bytes on.
919    ///
920    /// The payload comes back with it for the reason the codec leaves it on the
921    /// wire: `payload_length` says how many bytes follow, and a reader that
922    /// takes the wrong number of them desynchronises every later object on the
923    /// stream. Doing it here is the only place that count and the buffer are
924    /// both in hand.
925    ///
926    /// # Errors
927    ///
928    /// [`ConnectionError::DataStreamState`] when
929    /// [`FramedRecvStream::begin_fetch_objects`] has not been called,
930    /// [`ConnectionError::UnexpectedEnd`] when the stream ends inside the header
931    /// or inside the payload it declared, and [`ConnectionError::Codec`] on
932    /// every rule Section 11.4.1.1 states — a first Object that inherits, a
933    /// delta that runs off either end of the space, or an Object ID above
934    /// 2^64-1.
935    ///
936    /// A Prior Group ID Gap or Prior Object ID Gap fault the stream shows is
937    /// returned as [`CodecError::MalformedTrack`], and a property block that
938    /// does not parse as [`CodecError::MalformedObjectProperties`];
939    /// [`Connection::requests_to_cancel_for_fetch_stream`] names the requests to
940    /// cancel.
941    pub async fn read_fetch_object(&mut self) -> Result<(FetchObject, Vec<u8>), ConnectionError> {
942        if self.fetch_io.is_none() {
943            return Err(ConnectionError::DataStreamState("fetch object reader not started"));
944        }
945        let object = loop {
946            let reader = self.fetch_io.as_mut().unwrap();
947            // Advanced on a probe and committed only once the whole header was
948            // there to read: a reader advanced by a short read would resolve
949            // the next Object against a half-read one.
950            let mut probe = reader.clone();
951            let mut cursor = &self.buf[..];
952            match probe.read_object_header(&mut cursor) {
953                Ok(object) => {
954                    let consumed = self.buf.len() - cursor.remaining();
955                    self.buf.advance(consumed);
956                    *reader = probe;
957                    break object;
958                }
959                Err(e) if e.is_incomplete() => {
960                    if !self.fill().await? {
961                        return Err(ConnectionError::UnexpectedEnd);
962                    }
963                }
964                Err(e) => return Err(ConnectionError::Codec(e)),
965            }
966        };
967        let payload = self.read_object_payload(&object.header.payload_length).await?;
968        Ok((object, payload))
969    }
970
971    /// Take the `length` payload bytes that follow a fetch object's header.
972    ///
973    /// Separate from the header read because the header is decoded from a probe
974    /// cursor that may have to be retried after a fill, and the payload is a
975    /// flat byte count that never is.
976    async fn read_object_payload(&mut self, length: &VarInt) -> Result<Vec<u8>, ConnectionError> {
977        let length = length.into_inner() as usize;
978        self.ensure(length).await?;
979        let payload = self.buf[..length].to_vec();
980        self.buf.advance(length);
981        Ok(payload)
982    }
983
984    /// Returns the draft version this stream is framed for.
985    pub fn draft(&self) -> DraftVersion {
986        self.draft
987    }
988}
989
990/// Which of the seven message types draft-21 Section 6.3 lets a bidirectional
991/// stream begin with opened a request stream.
992///
993/// Draft-21 Section 6.3: "A request stream begins with one of these seven
994/// message types: TRACK_STATUS, SUBSCRIBE, PUBLISH, FETCH, PUBLISH_NAMESPACE,
995/// SUBSCRIBE_NAMESPACE, and SUBSCRIBE_TRACKS. Bidirectional streams MUST NOT
996/// begin with any other message type unless negotiated."
997///
998/// The set is per draft and is not stable across drafts: draft-17 had six of
999/// these, and draft-18 — whose set draft-21 keeps — both added
1000/// SUBSCRIBE_TRACKS and renumbered SUBSCRIBE_NAMESPACE from 0x11 to 0x50. A
1001/// seven-variant enum here is what makes it impossible to label a draft-21
1002/// request stream with a kind this draft does not have.
1003#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1004pub enum RequestKind {
1005    /// TRACK_STATUS, 0x0D.
1006    TrackStatus,
1007    /// SUBSCRIBE, 0x03.
1008    Subscribe,
1009    /// PUBLISH, 0x1D.
1010    Publish,
1011    /// FETCH, 0x16. Draft-21 has one shape of FETCH: Section 9.11 has no
1012    /// `Fetch Type` field and so no standalone/joining distinction (draft-20
1013    /// removed both).
1014    Fetch,
1015    /// PUBLISH_NAMESPACE, 0x06.
1016    PublishNamespace,
1017    /// SUBSCRIBE_NAMESPACE, 0x50 on this draft — 0x11 on draft-17.
1018    SubscribeNamespace,
1019    /// SUBSCRIBE_TRACKS, 0x51. Added in draft-18; draft-17 has no such
1020    /// message and no such request stream.
1021    SubscribeTracks,
1022}
1023
1024impl RequestKind {
1025    /// The message type a request stream of this kind begins with.
1026    pub const fn message_type(self) -> MessageType {
1027        match self {
1028            RequestKind::TrackStatus => MessageType::TrackStatus,
1029            RequestKind::Subscribe => MessageType::Subscribe,
1030            RequestKind::Publish => MessageType::Publish,
1031            RequestKind::Fetch => MessageType::Fetch,
1032            RequestKind::PublishNamespace => MessageType::PublishNamespace,
1033            RequestKind::SubscribeNamespace => MessageType::SubscribeNamespace,
1034            RequestKind::SubscribeTracks => MessageType::SubscribeTracks,
1035        }
1036    }
1037
1038    /// The kind of request stream `ty` opens, or `None` when it opens none.
1039    ///
1040    /// The inverse of [`message_type`](Self::message_type) and the classifier
1041    /// the accept path runs on the first message of a bidirectional stream the
1042    /// peer opened. `None` is the PROTOCOL_VIOLATION case of draft-21
1043    /// Section 6.3.
1044    ///
1045    /// Like [`starts_a_request_stream`] the match is exhaustive over
1046    /// [`MessageType`] with **no wildcard arm**, so a message type added in a
1047    /// later draft stops this compiling until someone classifies it; the unit
1048    /// test below holds the two functions to the same answer for every
1049    /// assigned type, so neither can drift from the other.
1050    pub const fn from_message_type(ty: MessageType) -> Option<RequestKind> {
1051        match ty {
1052            MessageType::TrackStatus => Some(RequestKind::TrackStatus),
1053            MessageType::Subscribe => Some(RequestKind::Subscribe),
1054            MessageType::Publish => Some(RequestKind::Publish),
1055            MessageType::Fetch => Some(RequestKind::Fetch),
1056            MessageType::PublishNamespace => Some(RequestKind::PublishNamespace),
1057            MessageType::SubscribeNamespace => Some(RequestKind::SubscribeNamespace),
1058            MessageType::SubscribeTracks => Some(RequestKind::SubscribeTracks),
1059            MessageType::Setup
1060            | MessageType::GoAway
1061            | MessageType::Namespace
1062            | MessageType::NamespaceDone
1063            | MessageType::PublishSkipped
1064            | MessageType::RequestUpdate
1065            | MessageType::SubscribeOk
1066            | MessageType::RequestOk
1067            | MessageType::RequestError
1068            | MessageType::FetchOk
1069            | MessageType::PublishDone
1070            // New in draft-20. Section 9.10 puts it on "a subscription's
1071            // bidirectional stream", which is a stream a SUBSCRIBE or a PUBLISH
1072            // already opened, so it begins none of its own.
1073            | MessageType::PublishStateNotify => None,
1074        }
1075    }
1076}
1077
1078/// Which side opened the bidirectional stream a request travels on.
1079///
1080/// Draft-21 Section 6.3 gives every request a bidirectional stream, and either
1081/// endpoint may open one. The two directions are not symmetric — one side owes
1082/// a response and the other is waiting for it — so a [`RequestStream`] carries
1083/// this to say which side of that it is on.
1084#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1085pub enum RequestOrigin {
1086    /// This endpoint opened the stream and wrote the request on it. What comes
1087    /// back is a response, and dropping the handle cancels the request.
1088    Local,
1089    /// The peer opened the stream; this endpoint owes it a response. What
1090    /// comes back is a follow-up to the peer's request, never a response, and
1091    /// dropping the handle abandons a request that was asked of us.
1092    Peer,
1093}
1094/// Whether draft-21 Table 5 places this message on a request stream that is
1095/// already open.
1096///
1097/// All five of the messages Table 5 marks "Request" without their beginning one:
1098/// REQUEST_UPDATE modifies the request its stream carries (Section 9.5),
1099/// NAMESPACE and NAMESPACE_DONE report namespaces on the SUBSCRIBE_NAMESPACE
1100/// stream that asked for them (Section 9.16 and Section 9.17), PUBLISH_SKIPPED
1101/// names a track on the SUBSCRIBE_TRACKS stream that asked for it (Section
1102/// 9.18), and PUBLISH_STATE_NOTIFY — new in draft-20 — reports a change on the
1103/// subscription's own stream (Section 9.10).
1104///
1105/// `Endpoint::receive_message` already closes the session over all five when
1106/// they arrive on the control stream. Without this the client would write on the
1107/// control stream exactly what its own peer half refuses to read there.
1108fn belongs_on_a_request_stream(ty: MessageType) -> bool {
1109    matches!(
1110        ty,
1111        MessageType::RequestUpdate
1112            | MessageType::Namespace
1113            | MessageType::NamespaceDone
1114            | MessageType::PublishSkipped
1115            | MessageType::PublishStateNotify
1116    )
1117}
1118
1119/// Whether `ty` is one of the seven message types draft-21 Section 6.3 lets a
1120/// bidirectional stream begin with.
1121///
1122/// The match is exhaustive over [`MessageType`] and deliberately has **no
1123/// wildcard arm**. That is the drift guard: `MessageType` is not
1124/// `#[non_exhaustive]`, so the day a draft gains a message type this stops
1125/// compiling until someone says here whether the new type opens a request
1126/// stream. A wildcard would silently answer "no" for it.
1127///
1128/// Classification is over the typed `MessageType`, never over a raw `u64`,
1129/// because the number alone does not say which registry it came from: on
1130/// draft-21, 0x50 is SUBSCRIBE_NAMESPACE as a control message type and also a
1131/// SUBGROUP_HEADER as a unidirectional stream type.
1132pub const fn starts_a_request_stream(ty: MessageType) -> bool {
1133    match ty {
1134        // The seven that begin a request stream.
1135        MessageType::TrackStatus
1136        | MessageType::Subscribe
1137        | MessageType::Publish
1138        | MessageType::Fetch
1139        | MessageType::PublishNamespace
1140        | MessageType::SubscribeNamespace
1141        | MessageType::SubscribeTracks => true,
1142        // Messages that cannot begin a request stream. SETUP is the control
1143        // stream's own type varint. NAMESPACE, NAMESPACE_DONE, PUBLISH_SKIPPED
1144        // and REQUEST_UPDATE all travel ON a request stream — Table 5 gives
1145        // every one of them the Stream value "Request" — but none of them
1146        // opens one: the first three report on the namespace or publication of
1147        // the stream that is already there, and REQUEST_UPDATE modifies a
1148        // request that already has a stream, draft-21 Section 9.5 putting it
1149        // "on the same bidi stream as the request". This function answers
1150        // *does this message open a stream*, not *does it belong on one*.
1151        //
1152        // GOAWAY is here because it opens nothing, not because it is confined
1153        // to the control stream: draft-18 gave it an optional Request ID
1154        // present only on the control stream, draft-19 removed the field
1155        // outright and draft-21 keeps it gone, leaving one wire form for both
1156        // places. It may follow a
1157        // request on an already-open request stream — see
1158        // [`Connection::send_on_request_stream`], which refuses nothing.
1159        MessageType::Setup
1160        | MessageType::GoAway
1161        | MessageType::Namespace
1162        | MessageType::NamespaceDone
1163        | MessageType::PublishSkipped
1164        | MessageType::RequestUpdate => false,
1165        // Responses. They cannot begin a stream: they arrive on the request
1166        // stream their request opened, which is why they carry no request id
1167        // of their own on this draft. There is no PublishOk here — draft-18
1168        // folded PUBLISH_OK into REQUEST_OK and draft-21 keeps it that way.
1169        MessageType::SubscribeOk
1170        | MessageType::RequestOk
1171        | MessageType::RequestError
1172        | MessageType::FetchOk
1173        | MessageType::PublishDone => false,
1174        // Not a response — Section 9.10 makes it unilateral, answered with
1175        // nothing — but it opens no stream either: it travels on the
1176        // subscription's, which a SUBSCRIBE or a PUBLISH already opened.
1177        MessageType::PublishStateNotify => false,
1178    }
1179}
1180
1181/// One request and its answer, on a bidirectional stream of their own.
1182///
1183/// Draft-21 Section 6.3 keeps requests off the control plane: each request is
1184/// the first message on a bidirectional stream it opens, and the response
1185/// comes back on that same stream. Responses carry no request id on this
1186/// draft — **the stream is the correlation**, which is why this handle exists
1187/// and why a bare request id is no longer enough to find an answer.
1188///
1189/// # Reading and writing go through the connection
1190///
1191/// This handle owns both halves of the stream but not the session, so the
1192/// endpoint state machine and the observer stay where they were. Read a
1193/// response with [`Connection::recv_on_request_stream`], write a follow-up with
1194/// [`Connection::send_on_request_stream`], and cancel with
1195/// [`Connection::cancel_request_stream`].
1196///
1197/// [`cancel`](Self::cancel) and [`peer_cancelled`](Self::peer_cancelled) are on
1198/// the handle because they touch the stream and nothing else, and [`Drop`]
1199/// needs the first of them. Neither moves the endpoint's record of the request,
1200/// which is why the connection carries a pair of its own.
1201///
1202/// # Dropping this cancels the request
1203///
1204/// A dropped handle resets the send half and sends `STOP_SENDING` on the
1205/// receive half, both with [`REQUEST_CANCELLED`], unless the stream was
1206/// already cancelled or finished. Letting the default drop stand would send a
1207/// FIN instead, telling the peer the request ended *cleanly* when it was
1208/// abandoned.
1209///
1210/// The consequence is sharp and worth stating: a live subscription's request
1211/// stream must be **held for the subscription's life**, because PUBLISH_DONE
1212/// arrives on it. Keeping only [`request_id`](Self::request_id) and letting
1213/// the handle fall out of scope cancels the subscription.
1214///
1215/// What a drop cannot do is say so at the endpoint. [`Drop`] holds the stream
1216/// and not the session, so the request stays where it was in the endpoint's
1217/// record while the stream it travelled on is gone. Call
1218/// [`Connection::cancel_request_stream`] wherever that record matters.
1219///
1220/// # Which side opened it changes what this handle does
1221///
1222/// [`origin`](Self::origin) says whether this endpoint opened the stream or
1223/// accepted it, and three behaviours turn on it: reads dispatch as responses
1224/// or as follow-ups to the peer's request, the `respond_*` helpers refuse a
1225/// stream this endpoint opened, and [`Drop`] resets with
1226/// [`REQUEST_UNANSWERED`] rather than [`REQUEST_CANCELLED`]. Everything else —
1227/// [`cancel`](Self::cancel), [`peer_cancelled`](Self::peer_cancelled),
1228/// [`Connection::send_on_request_stream`] — is the same in both directions.
1229/// Draft-21 Section 6.4.2.3 is explicit that a cancel is available to both:
1230/// "Senders cancel requests if the response is no longer of interest;
1231/// Receivers cancel requests if they are unable to or choose not to respond."
1232///
1233/// [`finish`](Self::finish) is the one act that is constrained rather than
1234/// merely different: Section 6.4.2.2 forbids a FIN before the messages that
1235/// direction still owes.
1236///
1237/// All fields are private so the shape can grow without breaking callers.
1238#[must_use = "dropping a request stream cancels the request; hold it until the response arrives"]
1239pub struct RequestStream {
1240    send: FramedSendStream,
1241    recv: FramedRecvStream,
1242    request_id: VarInt,
1243    kind: RequestKind,
1244    /// The unidirectional stream this request's objects are being served on.
1245    ///
1246    /// Only a FETCH has one, and only once the caller has opened it through
1247    /// [`Connection::open_fetch_stream_on`]. Held here rather than in a table
1248    /// on the connection because the request stream is already the thing that
1249    /// knows what this request still owes, and because a handle kept beside
1250    /// the request cannot outlive it.
1251    fetch_data: Option<FramedSendStream>,
1252    draft: DraftVersion,
1253    stream_id: u64,
1254    cancelled: bool,
1255    finished: bool,
1256    origin: RequestOrigin,
1257    /// Whether a `respond_*` helper has written a response on this stream.
1258    /// True on a [`RequestOrigin::Peer`] stream from the response written on
1259    /// it, and on a [`RequestOrigin::Local`] one from the answer to an update
1260    /// the peer sent, which is the only response this endpoint writes on a
1261    /// stream of its own.
1262    responded: bool,
1263    /// Whether this endpoint is the publisher of a subscription established on
1264    /// this stream and has not yet sent PUBLISH_DONE.
1265    ///
1266    /// True from the PUBLISH this endpoint sent, and from the SUBSCRIBE_OK it
1267    /// wrote answering a peer's SUBSCRIBE; false again once PUBLISH_DONE is
1268    /// out. It is what draft-21 Section 6.4.2.2's second clause is checked
1269    /// against in [`finish`](Self::finish).
1270    owes_publish_done: bool,
1271}
1272
1273impl RequestStream {
1274    /// The request id the endpoint allocated for this request.
1275    ///
1276    /// Useful for logging and for endpoint calls that still take one. It is
1277    /// not enough to find the response: draft-21 responses carry no request
1278    /// id, so only this stream identifies them.
1279    pub fn request_id(&self) -> VarInt {
1280        self.request_id
1281    }
1282
1283    /// Which of the seven request types opened this stream.
1284    pub fn kind(&self) -> RequestKind {
1285        self.kind
1286    }
1287
1288    /// The transport-level stream identifier, the same one
1289    /// [`ClientEvent::StreamOpened`] reports for data streams.
1290    pub fn stream_id(&self) -> u64 {
1291        self.stream_id
1292    }
1293
1294    /// The draft version this stream is framed for.
1295    pub fn draft(&self) -> DraftVersion {
1296        self.draft
1297    }
1298
1299    /// Which side opened this stream.
1300    ///
1301    /// [`RequestOrigin::Peer`] means this endpoint owes a response and the
1302    /// `respond_*` helpers apply; [`RequestOrigin::Local`] means it is waiting
1303    /// for one.
1304    pub fn origin(&self) -> RequestOrigin {
1305        self.origin
1306    }
1307
1308    /// Whether a response has been written on this stream by one of the
1309    /// `respond_*` helpers.
1310    ///
1311    /// On a [`RequestOrigin::Local`] stream this says an update the peer sent
1312    /// was answered here, not that the request itself was: that one is
1313    /// answered by the peer.
1314    pub fn responded(&self) -> bool {
1315        self.responded
1316    }
1317
1318    /// Whether this endpoint still owes the peer a PUBLISH_DONE on this stream.
1319    ///
1320    /// True for a PUBLISH this endpoint sent and for a peer's SUBSCRIBE it
1321    /// answered with SUBSCRIBE_OK — the two ways draft-21 Section 6.4.2.2's
1322    /// "publisher of an Established subscription" is reached — until
1323    /// [`Connection::publish_done`] or [`Connection::publish_done_on`] has run.
1324    /// While it is true, [`finish`](Self::finish) refuses.
1325    pub fn owes_publish_done(&self) -> bool {
1326        self.owes_publish_done
1327    }
1328
1329    /// The stream this request's objects are being served on, if one is open.
1330    ///
1331    /// Only a FETCH answered through
1332    /// [`Connection::open_fetch_stream_on`](Connection::open_fetch_stream_on)
1333    /// has one. Writing objects goes through this rather than through a handle
1334    /// the caller keeps, so that the connection can still reach the stream
1335    /// when a rule says to reset it.
1336    pub fn fetch_data(&mut self) -> Option<&mut FramedSendStream> {
1337        self.fetch_data.as_mut()
1338    }
1339
1340    /// Reset the fetch data stream, if one was opened, and forget it.
1341    ///
1342    /// The sentence that requires this names no error code, so the code comes
1343    /// from the registry rather than from here: CANCELLED is "the stream was
1344    /// cancelled by either endpoint", which is what a publisher abandoning the
1345    /// objects it was serving has done.
1346    fn reset_fetch_data(&mut self) {
1347        if let Some(mut framed) = self.fetch_data.take() {
1348            let _ = framed.reset(StreamResetErrorCode::Cancelled as u64);
1349        }
1350    }
1351
1352    /// Whether [`cancel`](Self::cancel) has already run on this handle.
1353    ///
1354    /// Says nothing about the peer: a peer reset is learned from
1355    /// [`peer_cancelled`](Self::peer_cancelled) or from the next read.
1356    pub fn is_cancelled(&self) -> bool {
1357        self.cancelled
1358    }
1359
1360    /// Cancel the request by resetting the stream, handing the peer `code`.
1361    ///
1362    /// Draft-17 removed UNSUBSCRIBE and FETCH_CANCEL and draft-21 has not
1363    /// brought them back: resetting the request stream is how a request is
1364    /// withdrawn. Both halves are shut — a QUIC bidirectional stream has two
1365    /// independent halves, so resetting only the send half would leave the
1366    /// peer free to keep writing a response nobody will read. The send half is
1367    /// reset with `code` and the receive half is stopped with the same value.
1368    ///
1369    /// [`REQUEST_CANCELLED`] is the ordinary choice. Draft-21 Section 12.5
1370    /// says an application SHOULD take the code from the Stream Reset Error
1371    /// Codes registry when resetting, or sending STOP_SENDING on, any stream —
1372    /// request streams included — so [`StreamResetErrorCode`] is where a value
1373    /// other than the default should come from. The parameter is a plain `u64`
1374    /// because the registry reserves greasing code points that have no variant;
1375    /// a caller with a named code has [`StreamResetErrorCode::as_u64`].
1376    ///
1377    /// **This is the stream and nothing else.** The endpoint's record of the
1378    /// request does not move, so a response already in flight is still accepted
1379    /// after this returns. [`Connection::cancel_request_stream`] does both and
1380    /// is what a caller holding a connection should reach for; this stays
1381    /// because [`Drop`] has no connection to reach.
1382    ///
1383    /// Idempotent, and it retires the [`Drop`] behaviour: a cancelled handle
1384    /// does nothing further when it goes out of scope. Errors from a stream
1385    /// that was already reset or stopped are swallowed for the same reason —
1386    /// the request is cancelled either way.
1387    ///
1388    /// # Errors
1389    ///
1390    /// [`ConnectionError::Transport`] carrying [`TransportError::Write`] if
1391    /// `code` is outside the QUIC varint range (`0..2^62`). Nothing is sent
1392    /// in that case, and the handle is *not* marked cancelled, so a caller
1393    /// can retry with a representable code.
1394    pub fn cancel(&mut self, code: u64) -> Result<(), ConnectionError> {
1395        if self.cancelled {
1396            return Ok(());
1397        }
1398        // Reject an unrepresentable code before either half is touched, so a
1399        // failed call leaves the stream exactly as it was.
1400        if code > MAX_QUIC_VARINT {
1401            return Err(ConnectionError::Transport(TransportError::Write(format!(
1402                "error code {code} exceeds the varint range"
1403            ))));
1404        }
1405        self.cancelled = true;
1406        // Already-finished or already-reset halves report StreamClosed; the
1407        // request ends up cancelled regardless, so neither is worth raising.
1408        let _ = self.send.reset(code);
1409        let _ = self.recv.stop(code);
1410        Ok(())
1411    }
1412
1413    /// Wait for the peer to cancel this request, consuming nothing.
1414    ///
1415    /// A caller applying backpressure is deliberately not calling
1416    /// [`Connection::recv_on_request_stream`], which is the only other place a
1417    /// peer reset surfaces — so without this the abandonment goes unobserved
1418    /// for as long as the backpressure lasts. This grants no flow-control
1419    /// credit and is cancel-safe.
1420    ///
1421    /// Returns `Ok(Some(code))` with the peer's application error code, or
1422    /// `Ok(None)` meaning **no reset is observable, now or ever — stop
1423    /// asking**. A caller that re-polls after `Ok(None)` spins.
1424    ///
1425    /// Like [`cancel`](Self::cancel), this records nothing at the endpoint.
1426    /// [`Connection::peer_cancelled_on_request_stream`] is the same wait with
1427    /// the record attached.
1428    ///
1429    /// On WebTransport this always answers `Ok(None)`: `wtransport` exposes no
1430    /// reset-only observable, so a WebTransport caller learns of a peer cancel
1431    /// on its next read and not before.
1432    pub async fn peer_cancelled(&mut self) -> Result<Option<u64>, ConnectionError> {
1433        self.recv.received_reset().await
1434    }
1435
1436    /// Finish the send half cleanly, leaving the receive half open.
1437    ///
1438    /// Draft-21 Section 6.4.2.2 settles what a FIN means, which earlier drafts
1439    /// left open: "A FIN only indicates that an endpoint will send no further
1440    /// messages in that direction; it is not a request cancellation." A
1441    /// requester may therefore FIN before its response arrives — "A requester,
1442    /// with the exception of the sender of PUBLISH, MAY FIN immediately after
1443    /// sending a message if it will not send a REQUEST_UPDATE" — and the
1444    /// receive half stays open to carry the response, which is why this touches
1445    /// only the send half.
1446    ///
1447    /// What the same section forbids is finishing early: "An endpoint MUST NOT
1448    /// send a FIN on a direction of a request stream until it has sent all
1449    /// required messages on that direction for its request type", and "An
1450    /// endpoint that receives a FIN before all required messages have arrived
1451    /// treats the request as failed." The section names the two messages that
1452    /// are always required — "an endpoint sending a response to a request MUST
1453    /// send the corresponding response message, and the publisher of an
1454    /// Established subscription MUST send PUBLISH_DONE" — and both are things
1455    /// this handle knows about itself, so both are checked here and **nothing
1456    /// is written** when either is outstanding.
1457    ///
1458    /// A responder that owes a response has not sent one:
1459    /// [`ConnectionError::FinBeforeResponse`]. A publisher that owes a
1460    /// PUBLISH_DONE, whether from a PUBLISH it sent or a peer's SUBSCRIBE it
1461    /// accepted, gets [`ConnectionError::FinBeforePublishDone`] — which is why
1462    /// [`Connection::publish_done`] and [`Connection::publish_done_on`] are the
1463    /// routes that end a publication, rather than a bare `finish`.
1464    ///
1465    /// What is not checked is everything the caller alone knows: a
1466    /// SUBSCRIBE_NAMESPACE responder deciding it has no more namespaces to
1467    /// announce, or a requester deciding it will send no REQUEST_UPDATE. The
1468    /// section leaves those to the endpoint, and so does this.
1469    ///
1470    /// Drafts 17 and 18 have no Section 6.4.2.2 and no guard: their `finish` is
1471    /// unconditional. A porter must not carry this one back to them.
1472    ///
1473    /// A finished handle, like a cancelled one, does nothing further on
1474    /// [`Drop`]. That matters here: the default drop resets both halves, which
1475    /// Section 6.4.2.2 contrasts with a FIN as the abrupt close, so a request
1476    /// that ended cleanly must come through this to avoid being reported as
1477    /// cancelled.
1478    pub async fn finish(&mut self) -> Result<(), ConnectionError> {
1479        if self.finished || self.cancelled {
1480            return Ok(());
1481        }
1482        if self.origin == RequestOrigin::Peer && !self.responded {
1483            return Err(ConnectionError::FinBeforeResponse(self.request_id.into_inner()));
1484        }
1485        if self.owes_publish_done {
1486            return Err(ConnectionError::FinBeforePublishDone(self.request_id.into_inner()));
1487        }
1488        self.finished = true;
1489        self.send.finish().await
1490    }
1491}
1492
1493impl Drop for RequestStream {
1494    /// Reset the request unless it was already cancelled or finished.
1495    ///
1496    /// See the type-level note: the default drop would FIN the send half,
1497    /// which claims a clean end for a request the caller walked away from —
1498    /// and on draft-21 a FIN is a stronger claim than on earlier drafts, since
1499    /// Section 6.4.2.2 has the receiver of one *treat the request as failed*
1500    /// only when messages are still owed and complete otherwise.
1501    ///
1502    /// The code says which walking away it was. A stream this endpoint opened
1503    /// is cancelled — [`REQUEST_CANCELLED`] — which is the requester act
1504    /// Section 6.4.2.3 describes. A stream the peer opened is reset with
1505    /// [`REQUEST_UNANSWERED`] whether or not a response was already written:
1506    /// before one, the request was never served; after one, the obligations
1507    /// that follow it are still outstanding.
1508    fn drop(&mut self) {
1509        if self.cancelled || self.finished {
1510            return;
1511        }
1512        let code = match self.origin {
1513            RequestOrigin::Local => REQUEST_CANCELLED,
1514            RequestOrigin::Peer => REQUEST_UNANSWERED,
1515        };
1516        let _ = self.send.reset(code);
1517        let _ = self.recv.stop(code);
1518    }
1519}
1520
1521/// Holds a peer-opened stream pair while its first message is being read, and
1522/// puts it back on the connection's queue if that read is abandoned.
1523///
1524/// [`Connection::accept_request_stream`] awaits a whole control message, and a
1525/// caller may drop that future — a `select!` against a shutdown signal is the
1526/// ordinary reason. Without this the stream, and every byte already read off
1527/// it into the reader's buffer, would go with the future: the peer would see a
1528/// request stream reset for no reason it could act on.
1529///
1530/// [`Drop`] is the only place this can run, because a cancelled future is
1531/// never polled again. Every path that finishes — success or error — takes the
1532/// pair out first, so a pair still present when this drops was cancelled.
1533struct PendingInbound<'a> {
1534    pair: Option<(FramedSendStream, FramedRecvStream)>,
1535    queue: &'a Mutex<VecDeque<(FramedSendStream, FramedRecvStream)>>,
1536}
1537
1538impl Drop for PendingInbound<'_> {
1539    fn drop(&mut self) {
1540        if let Some(pair) = self.pair.take() {
1541            // Front, not back: this stream arrived before anything still
1542            // queued behind it, and a partially read message must not be
1543            // handed out after a stream that arrived later.
1544            self.queue.lock().unwrap_or_else(|p| p.into_inner()).push_front(pair);
1545        }
1546    }
1547}
1548
1549/// The largest value a QUIC application error code can carry, `2^62 - 1`.
1550///
1551/// Checked by [`RequestStream::cancel`] before either half of the stream is
1552/// touched, so an unrepresentable code cannot half-cancel a request.
1553const MAX_QUIC_VARINT: u64 = (1u64 << 62) - 1;
1554
1555/// A live MoQT connection over QUIC or WebTransport, combining the endpoint
1556/// state machine with actual network I/O.
1557pub struct Connection {
1558    transport: Transport,
1559    endpoint: Endpoint,
1560    draft: DraftVersion,
1561    control_send: Option<FramedSendStream>,
1562    control_recv: Option<FramedRecvStream>,
1563    observer: Option<Box<dyn ConnectionObserver>>,
1564    /// Setup events buffered during `connect()` and replayed when an
1565    /// observer attaches via `set_observer` — without this, an observer
1566    /// attached after `connect` returns would never see the handshake.
1567    pending_events: Vec<ClientEvent>,
1568    /// The server's half of the setup handshake, kept whole.
1569    ///
1570    /// The endpoint acts on the parameters it recognises and retains none of
1571    /// them, and which parameters a server sends — in what order, with what
1572    /// values — is the sharpest thing a session says about the implementation
1573    /// behind it.
1574    server_setup: AnyControlMessage,
1575    /// The framed wire bytes of [`Self::server_setup`].
1576    server_setup_raw: Option<Vec<u8>>,
1577    /// Unidirectional streams accepted while `connect` was looking for the
1578    /// peer's control stream, in arrival order, and then any stream that is
1579    /// not a FETCH_HEADER one that a fetch or fill accept met.
1580    ///
1581    /// Data streams are allowed to arrive before the control streams on this
1582    /// draft, so the search cannot assume the first unidirectional stream is
1583    /// the control one — and dropping the ones that are not would silently
1584    /// lose objects the peer already sent.
1585    /// [`accept_subgroup_stream`](Connection::accept_subgroup_stream) empties
1586    /// this before it accepts anything new.
1587    ///
1588    /// Behind a mutex because that method takes `&self`. The lock is only
1589    /// ever held for a push or a pop, never across an await.
1590    deferred_uni: Mutex<VecDeque<FramedRecvStream>>,
1591    /// FETCH_HEADER streams, fetch and fill alike, accepted by a call that
1592    /// wanted another kind, in arrival order. The type varint is still on
1593    /// the front of each.
1594    /// [`accept_fetch_stream`](Connection::accept_fetch_stream) and
1595    /// [`accept_fill_stream`](Connection::accept_fill_stream) empty this
1596    /// before they accept anything new.
1597    deferred_fetch: Mutex<VecDeque<FramedRecvStream>>,
1598    /// Bidirectional streams the peer opened that
1599    /// [`accept_request_stream`](Connection::accept_request_stream) took off
1600    /// the transport but did not finish reading a first message from, because
1601    /// its future was dropped. In arrival order.
1602    ///
1603    /// Without this a caller could not put `accept_request_stream` in a
1604    /// `select!` at all: losing the race would lose a stream the peer had
1605    /// already opened and, with it, whatever of the request had arrived.
1606    /// [`accept_request_stream`](Connection::accept_request_stream) empties
1607    /// this before it accepts anything new.
1608    ///
1609    /// Behind a mutex for the same reason `deferred_uni` is: the lock is only
1610    /// ever held for a push or a pop, never across an await.
1611    pending_inbound: Mutex<VecDeque<(FramedSendStream, FramedRecvStream)>>,
1612}
1613
1614impl Connection {
1615    /// Connect to a MoQT server as a client.
1616    ///
1617    /// Establishes a QUIC or WebTransport connection (based on
1618    /// `config.transport`), brings up the control plane, performs the SETUP
1619    /// handshake, and returns a ready-to-use connection.
1620    ///
1621    /// # The control plane is a pair of unidirectional streams
1622    ///
1623    /// Draft-21 Section 6.3: "MOQT uses a pair of unidirectional streams for
1624    /// creating the session and exchanging control messages. Each peer opens
1625    /// one control stream beginning with a SETUP message." So each direction
1626    /// is a separate stream opened by the peer that writes on it. This opens
1627    /// one with `open_uni` and writes SETUP on it, then finds the peer's by
1628    /// accepting unidirectional streams until one leads with
1629    /// [`CONTROL_STREAM_TYPE`].
1630    ///
1631    /// Nothing is written ahead of the SETUP: 0x2F00 is both the SETUP
1632    /// message type and the unidirectional stream type for a control stream,
1633    /// so the message's own first field is the stream header. See
1634    /// [`CONTROL_STREAM_TYPE`].
1635    ///
1636    /// A bidirectional stream is *not* the control stream here — the same
1637    /// section makes it a request stream, one that begins with TRACK_STATUS,
1638    /// SUBSCRIBE, PUBLISH, FETCH, PUBLISH_NAMESPACE, SUBSCRIBE_NAMESPACE or
1639    /// SUBSCRIBE_TRACKS: "Bidirectional streams MUST NOT begin with any other
1640    /// message type unless negotiated. If they do, the peer MUST close the
1641    /// Session with a PROTOCOL_VIOLATION." A SETUP written on a bidirectional
1642    /// stream is exactly that case, so a peer that enforces the topology
1643    /// answers it by closing the session.
1644    ///
1645    /// # Unidirectional streams that arrive before the peer's control stream
1646    ///
1647    /// They are kept, not dropped. Section 6.3 expects them: "Unidirectional
1648    /// streams containing Objects or bidirectional stream(s) beginning with a
1649    /// request message could arrive prior to the control streams, in which
1650    /// case the data SHOULD be buffered until both control streams arrive and
1651    /// setup is complete." Each such stream is set aside and handed to
1652    /// [`accept_subgroup_stream`](Self::accept_subgroup_stream) in arrival
1653    /// order, ahead of any newly accepted stream. Only the leading type
1654    /// varint is read from them here; the rest stays on the transport, unread
1655    /// and still flow-controlled, so nothing is buffered in this process
1656    /// beyond those few bytes.
1657    ///
1658    /// One limit worth knowing: the search waits for each stream's type
1659    /// varint in turn, so a peer that opens a unidirectional stream and then
1660    /// writes nothing on it stalls the handshake behind that stream.
1661    pub async fn connect(addr: &str, config: ClientConfig) -> Result<Self, ConnectionError> {
1662        // PATH is for native QUIC only, and the transport is known here and
1663        // nowhere further in. Refusing before dialling means a session that
1664        // the server would close on sight is never opened.
1665        setup::validate_client_path_transport(
1666            &config.setup_parameters,
1667            matches!(config.transport, TransportType::WebTransport { .. }),
1668        )
1669        .map_err(EndpointError::from)?;
1670
1671        let transport = match &config.transport {
1672            TransportType::Quic => Self::connect_quic(addr, &config).await?,
1673            TransportType::WebTransport { url } => {
1674                let url = url.clone();
1675                Self::connect_webtransport(&url, &config).await?
1676            }
1677        };
1678
1679        Self::adopt(transport, config).await
1680    }
1681
1682    /// Run the MoQT setup handshake over a transport somebody else established.
1683    ///
1684    /// For choosing the draft from what the server selected: dial once through
1685    /// [`crate::transport::dial_quic`] offering every ALPN, then bring the
1686    /// connection to the module its answer names. [`Self::connect`] cannot do
1687    /// this — it derives its single ALPN from the draft it was given.
1688    ///
1689    /// `config.draft` must match this module. The transport is adopted as
1690    /// given; nothing here re-checks the ALPN it was negotiated with.
1691    pub async fn adopt(
1692        transport: Transport,
1693        config: ClientConfig,
1694    ) -> Result<Self, ConnectionError> {
1695        let draft = config.draft;
1696        // PATH is for native QUIC only, and the transport is known here and
1697        // nowhere further in. Refusing before dialling means a session that
1698        // the server would close on sight is never opened.
1699        setup::validate_client_path_transport(
1700            &config.setup_parameters,
1701            matches!(config.transport, TransportType::WebTransport { .. }),
1702        )
1703        .map_err(EndpointError::from)?;
1704
1705        // Send half of the control plane: one unidirectional stream whose
1706        // first message is SETUP, which is also its stream header.
1707        let send = transport.open_uni().await?;
1708        let mut control_send = FramedSendStream::new(send, draft);
1709
1710        // Perform setup handshake (draft-21: no versions)
1711        let mut endpoint = Endpoint::new(Role::Client);
1712        endpoint.connect()?;
1713        let setup_msg = endpoint.send_setup(config.setup_parameters.clone())?;
1714        let any_setup = AnyControlMessage::Draft21(setup_msg);
1715        let raw_setup = control_send.write_control(&any_setup).await?;
1716
1717        // Receive half: the peer's control stream is whichever unidirectional
1718        // stream leads with CONTROL_STREAM_TYPE.
1719        let mut deferred_uni: VecDeque<FramedRecvStream> = VecDeque::new();
1720        let mut deferred_fetch: VecDeque<FramedRecvStream> = VecDeque::new();
1721        let mut control_recv = loop {
1722            let recv = transport.accept_uni().await?;
1723            let mut framed = FramedRecvStream::new(recv, draft);
1724            match framed.peek_stream_type().await {
1725                Ok(CONTROL_STREAM_TYPE) => break framed,
1726                Ok(FETCH_STREAM_TYPE) => deferred_fetch.push_back(framed),
1727                // Every other type is a data stream — and so is a stream that
1728                // ended or failed before its type arrived, not because it is
1729                // one but because there is nothing left to decide with. The
1730                // data path sees the same end one read later and reports it
1731                // the way it reports every other. Treating it as the control
1732                // stream would hand the session's control plane to a stream
1733                // that carried nothing.
1734                _ => deferred_uni.push_back(framed),
1735            }
1736        };
1737
1738        let (server_setup, raw_server_setup) = control_recv.read_control(true).await?;
1739        // Unified SETUP in draft-21: server responds with the same message type.
1740        match &server_setup {
1741            AnyControlMessage::Draft21(ControlMessage::Setup(ref s)) => {
1742                endpoint.receive_setup(s)?;
1743            }
1744            _ => {
1745                return Err(ConnectionError::Endpoint(EndpointError::NotActive));
1746            }
1747        }
1748
1749        let pending_events = vec![
1750            ClientEvent::ControlMessage {
1751                direction: Direction::Send,
1752                message: any_setup,
1753                stream_id: None,
1754                raw: Some(raw_setup),
1755            },
1756            ClientEvent::ControlMessage {
1757                direction: Direction::Receive,
1758                message: server_setup.clone(),
1759                stream_id: None,
1760                raw: raw_server_setup.clone(),
1761            },
1762            ClientEvent::SetupComplete { negotiated_version: 0xff000000 + 21 },
1763        ];
1764
1765        Ok(Self {
1766            transport,
1767            endpoint,
1768            draft,
1769            control_send: Some(control_send),
1770            control_recv: Some(control_recv),
1771            observer: None,
1772            pending_events,
1773            server_setup,
1774            server_setup_raw: raw_server_setup,
1775            deferred_uni: Mutex::new(deferred_uni),
1776            deferred_fetch: Mutex::new(deferred_fetch),
1777            pending_inbound: Mutex::new(VecDeque::new()),
1778        })
1779    }
1780
1781    /// Establish a raw QUIC connection.
1782    ///
1783    /// Offers this draft's ALPN alone; [`crate::transport::dial_quic`] holds the
1784    /// TLS and endpoint setup.
1785    async fn connect_quic(addr: &str, config: &ClientConfig) -> Result<Transport, ConnectionError> {
1786        let (transport, _negotiated) = crate::transport::dial_quic(
1787            addr,
1788            &crate::transport::QuicDialOptions {
1789                skip_cert_verification: config.skip_cert_verification,
1790                ca_certs: config.ca_certs.clone(),
1791                ..crate::transport::QuicDialOptions::new(config.alpn())
1792            },
1793        )
1794        .await?;
1795        Ok(transport)
1796    }
1797
1798    /// Establish a WebTransport connection.
1799    ///
1800    /// [`crate::transport::dial_webtransport`] holds the TLS and endpoint
1801    /// setup, exactly as `connect_quic` above defers its own. That is not
1802    /// only deduplication: both dials must trust the same roots. Settling trust
1803    /// at this call site instead — from `wtransport`'s own builder settings, or
1804    /// from a second config of this draft's own — puts the decision in two
1805    /// places, where it can stop matching what the QUIC dial trusts, so one
1806    /// relay would pass on one transport and fail on the other and a caller's
1807    /// private CA would reach only the dials whose call site installed it.
1808    /// Both ask the same function what to trust.
1809    #[cfg(feature = "webtransport")]
1810    async fn connect_webtransport(
1811        url: &str,
1812        config: &ClientConfig,
1813    ) -> Result<Transport, ConnectionError> {
1814        Ok(crate::transport::dial_webtransport(
1815            url,
1816            &crate::transport::QuicDialOptions {
1817                skip_cert_verification: config.skip_cert_verification,
1818                ca_certs: config.ca_certs.clone(),
1819                // The draft's own protocol identifier, which this draft
1820                // negotiates in `WT-Available-Protocols` rather than in
1821                // CLIENT_SETUP: "The client includes MOQT protocol identifiers
1822                // in the WT-Available-Protocols header". `config.alpn()` above
1823                // is `h3`, which is the HTTP/3 name and settles no version.
1824                wt_protocols: vec![config.draft.quic_alpn().to_vec()],
1825                ..crate::transport::QuicDialOptions::new(config.alpn())
1826            },
1827        )
1828        .await?)
1829    }
1830
1831    /// Stub for when the webtransport feature is not enabled.
1832    #[cfg(not(feature = "webtransport"))]
1833    async fn connect_webtransport(
1834        _url: &str,
1835        _config: &ClientConfig,
1836    ) -> Result<Transport, ConnectionError> {
1837        Err(ConnectionError::Transport(TransportError::Connect(
1838            "webtransport feature not enabled".into(),
1839        )))
1840    }
1841
1842    // -- Observer ---------------------------------------------------
1843
1844    /// Attach an observer. Buffered handshake events from `connect()` are
1845    /// flushed in arrival order before this returns.
1846    pub fn set_observer(&mut self, observer: Box<dyn ConnectionObserver>) {
1847        self.observer = Some(observer);
1848        for event in self.pending_events.drain(..) {
1849            if let Some(ref obs) = self.observer {
1850                obs.on_event_owned(event);
1851            }
1852        }
1853    }
1854
1855    /// Remove the observer.
1856    pub fn clear_observer(&mut self) {
1857        self.observer = None;
1858    }
1859
1860    /// Emit an event to the observer, if one is attached.
1861    fn emit(&self, event: ClientEvent) {
1862        if let Some(ref obs) = self.observer {
1863            obs.on_event_owned(event);
1864        }
1865    }
1866
1867    // -- Control message I/O ----------------------------------------
1868
1869    /// Send a control message on the control stream.
1870    ///
1871    /// Wraps the draft-21 message in `AnyControlMessage::Draft21` for framing.
1872    /// Of the messages draft-21 Table 5 does not place on a request stream,
1873    /// exactly two reach the wire: SETUP, written by
1874    /// [`connect`](Self::connect) as the control stream's own type varint, and
1875    /// GOAWAY, which is the one message the table gives the Stream value
1876    /// "Control, Request" and which belongs here when it drains the session.
1877    ///
1878    /// # Four messages that this refuses
1879    ///
1880    /// Table 5 gives NAMESPACE (0x8), NAMESPACE_DONE (0xE), PUBLISH_SKIPPED
1881    /// (0xF) and REQUEST_UPDATE (0x2) the Stream value **Request**, not
1882    /// Control. REQUEST_UPDATE is sent "on the same bidi stream as the request"
1883    /// it modifies (Section 9.5); the other three report on the namespace or
1884    /// the publication of the request stream they arrive on. A conforming peer
1885    /// answers any of the four on the control stream by closing the session,
1886    /// and so does this client's own [`Endpoint::receive_message`] — writing
1887    /// one here produces a frame this implementation would itself refuse.
1888    ///
1889    /// All four have somewhere better to go, and none of them should come
1890    /// through here. REQUEST_UPDATE goes on the stream its request opened, with
1891    /// [`send_on_request_stream`](Self::send_on_request_stream). NAMESPACE and
1892    /// NAMESPACE_DONE go on a peer's SUBSCRIBE_NAMESPACE stream, with
1893    /// [`namespace_on`](Self::namespace_on) and
1894    /// [`namespace_done_on`](Self::namespace_done_on); PUBLISH_SKIPPED goes on
1895    /// a peer's SUBSCRIBE_TRACKS stream, with
1896    /// [`publish_skipped_on`](Self::publish_skipped_on). This method refuses
1897    /// all four with [`ConnectionError::RequestStreamMessageOnControlStream`]
1898    /// and writes nothing.
1899    ///
1900    /// [`Endpoint::receive_message`]: crate::draft21::endpoint::Endpoint::receive_message
1901    ///
1902    /// GOAWAY is correct here and is not confined here. Draft-18 gave it an
1903    /// optional Request ID present only on the control stream, and draft-20
1904    /// removed the field, so its control-stream and request-stream forms are
1905    /// now one wire form; [`send_on_request_stream`](Self::send_on_request_stream)
1906    /// will put it on an open request stream.
1907    ///
1908    /// # Requests are refused here
1909    ///
1910    /// Draft-21 Section 6.3 keeps requests off the control plane: "In addition
1911    /// to the control streams, this specification uses bidirectional streams
1912    /// to carry requests. A request stream begins with one of these seven
1913    /// message types: TRACK_STATUS, SUBSCRIBE, PUBLISH, FETCH,
1914    /// PUBLISH_NAMESPACE, SUBSCRIBE_NAMESPACE, and SUBSCRIBE_TRACKS." The
1915    /// response comes back on that same bidirectional stream, and resetting it
1916    /// cancels the request.
1917    ///
1918    /// Handing one of those seven to this method returns
1919    /// [`ConnectionError::RequestOnControlStream`] and writes **nothing** —
1920    /// an enforcing peer sees no bytes at all, not a misplaced request. Use
1921    /// the typed helpers, which open a bidirectional stream each:
1922    /// [`subscribe`](Self::subscribe), [`fetch`](Self::fetch),
1923    /// [`publish`](Self::publish), [`track_status`](Self::track_status),
1924    /// [`publish_namespace`](Self::publish_namespace),
1925    /// [`subscribe_namespace`](Self::subscribe_namespace) and
1926    /// [`subscribe_tracks`](Self::subscribe_tracks).
1927    ///
1928    /// Response types are still permitted here, and need not be. A
1929    /// response written here will be refused by a conforming peer, whose
1930    /// endpoint answers a response on the control stream with an error; the
1931    /// route that is correct is
1932    /// [`accept_request_stream`](Self::accept_request_stream) and the
1933    /// `respond_*` helpers, which write on the stream the request arrived on
1934    /// and take the Request ID off the handle rather than from the caller.
1935    /// [`publish_done`](Self::publish_done) and
1936    /// [`publish_done_on`](Self::publish_done_on) do not come through here
1937    /// either: each takes the request stream its publication travels on.
1938    pub async fn send_control(&mut self, msg: &ControlMessage) -> Result<(), ConnectionError> {
1939        let ty = msg.message_type();
1940        if starts_a_request_stream(ty) {
1941            return Err(ConnectionError::RequestOnControlStream(ty));
1942        }
1943        // What this endpoint refuses to receive on the control stream it must
1944        // not write there either, or the client emits frames its own peer half
1945        // would close the session over.
1946        if belongs_on_a_request_stream(ty) {
1947            return Err(ConnectionError::RequestStreamMessageOnControlStream(ty));
1948        }
1949        let any = AnyControlMessage::Draft21(msg.clone());
1950        let send = self.control_send.as_mut().ok_or(ConnectionError::NoControlStream)?;
1951        let raw = send.write_control(&any).await?;
1952        self.emit(ClientEvent::ControlMessage {
1953            direction: Direction::Send,
1954            message: any,
1955            stream_id: None,
1956            raw: Some(raw),
1957        });
1958        Ok(())
1959    }
1960
1961    /// Read the next control message from the control stream.
1962    ///
1963    /// Returns the `AnyControlMessage` and also extracts the draft-21
1964    /// `ControlMessage` for internal endpoint dispatch.
1965    pub async fn recv_control(&mut self) -> Result<ControlMessage, ConnectionError> {
1966        let recv = self.control_recv.as_mut().ok_or(ConnectionError::NoControlStream)?;
1967        let capture_raw = self.observer.is_some();
1968        let read = recv.read_control(capture_raw).await;
1969        let (any, raw) = match read {
1970            Ok(v) => v,
1971            Err(e) => return Err(self.close_for_codec(e)),
1972        };
1973        if capture_raw {
1974            self.emit(ClientEvent::ControlMessage {
1975                direction: Direction::Receive,
1976                message: any.clone(),
1977                stream_id: None,
1978                raw,
1979            });
1980        }
1981        // Unwrap to draft-21 for the endpoint
1982        match any {
1983            AnyControlMessage::Draft21(msg) => Ok(msg),
1984            // `AnyControlMessage` carries one variant per enabled draft feature. With draft 21 the
1985            // only one enabled the arm above is exhaustive and this rejection arm unreachable.
1986            // Compiled in every configuration with the lint allowed, rather than gated on a `cfg`
1987            // naming the other drafts: such a list has to be edited in every draft module
1988            // whenever a draft is added, and a copy that omits one leaves this match
1989            // non-exhaustive.
1990            #[allow(unreachable_patterns)]
1991            _ => Err(ConnectionError::ControlMessageNarrowing),
1992        }
1993    }
1994
1995    /// Read and dispatch the next incoming control message through the
1996    /// endpoint state machine. Returns the decoded message for inspection.
1997    ///
1998    /// Responses never arrive here. Draft-21 responses carry no request id
1999    /// and belong on the request stream that asked for them, so the endpoint
2000    /// refuses a response that turns up on the control stream. Read them with
2001    /// [`recv_on_request_stream`](Self::recv_on_request_stream).
2002    ///
2003    /// A violation the draft answers with a session close is closed on the
2004    /// wire here, before the error is returned: the QUIC connection is closed
2005    /// with the code [`EndpointError::session_error_code`] names, so the peer
2006    /// that broke the rule learns of it rather than only the local endpoint.
2007    pub async fn recv_and_dispatch(&mut self) -> Result<ControlMessage, ConnectionError> {
2008        let msg = self.recv_control().await?;
2009        self.endpoint.receive_message(msg.clone()).map_err(|e| self.close_if_session_fatal(e))?;
2010
2011        // Emit draining event if this was a GoAway
2012        if let ControlMessage::GoAway(ref ga) = msg {
2013            self.emit(ClientEvent::Draining { new_session_uri: ga.new_session_uri.clone() });
2014        }
2015
2016        Ok(msg)
2017    }
2018
2019    // -- Request streams --------------------------------------------
2020
2021    /// Open the bidirectional stream a request will be carried on.
2022    ///
2023    /// Opened *before* the endpoint allocates a request id, so a transport
2024    /// that refuses a new stream — the peer's `initial_max_streams_bidi` is
2025    /// exhausted, the connection is gone — costs nothing. The endpoint has no
2026    /// way to abandon a request it has already allocated, so every failure
2027    /// that can be moved ahead of the allocation is.
2028    ///
2029    /// Nothing is written here. A request stream carries no stream-type
2030    /// header: its first field is the leading message's own type field, which
2031    /// is what [`begin_request`](Self::begin_request) writes.
2032    async fn open_request_bi(
2033        &self,
2034    ) -> Result<(FramedSendStream, FramedRecvStream), ConnectionError> {
2035        let (send, recv) = self.transport.open_bi().await?;
2036        Ok((FramedSendStream::new(send, self.draft), FramedRecvStream::new(recv, self.draft)))
2037    }
2038
2039    /// Reset a request stream that was opened but whose request could not be
2040    /// built, and pass the endpoint's error through.
2041    ///
2042    /// Without this, an endpoint refusal — the session is draining, the
2043    /// request-id range is exhausted — would leave a bidirectional stream
2044    /// open that never carries a first message, and dropping it would FIN it,
2045    /// telling the peer an empty stream ended cleanly.
2046    fn or_abandon<T>(
2047        halves: &mut (FramedSendStream, FramedRecvStream),
2048        built: Result<T, EndpointError>,
2049    ) -> Result<T, ConnectionError> {
2050        match built {
2051            Ok(value) => Ok(value),
2052            Err(e) => {
2053                let _ = halves.0.reset(REQUEST_CANCELLED);
2054                let _ = halves.1.stop(REQUEST_CANCELLED);
2055                Err(ConnectionError::Endpoint(e))
2056            }
2057        }
2058    }
2059
2060    /// Write `msg` as the first message on an opened bidirectional stream and
2061    /// hand back the [`RequestStream`] that owns both halves.
2062    ///
2063    /// This is the one place a request reaches the wire. Every request helper
2064    /// funnels through it, so the ordering — open, allocate, write, emit — is
2065    /// stated once.
2066    ///
2067    /// A failed write resets both halves rather than leaving a half-written
2068    /// request stream behind. What it cannot undo is the endpoint's
2069    /// allocation: the request id and its state machine already exist, and
2070    /// there is no way to retract them, so a write that fails here leaves one
2071    /// pending request the endpoint will never see answered.
2072    async fn begin_request(
2073        &mut self,
2074        halves: (FramedSendStream, FramedRecvStream),
2075        kind: RequestKind,
2076        request_id: VarInt,
2077        msg: &ControlMessage,
2078    ) -> Result<RequestStream, ConnectionError> {
2079        debug_assert_eq!(
2080            msg.message_type(),
2081            kind.message_type(),
2082            "a request stream's first message must be the one its kind names"
2083        );
2084        let (mut send, mut recv) = halves;
2085        let stream_id = send.stream_id();
2086        self.emit(ClientEvent::StreamOpened {
2087            direction: Direction::Send,
2088            stream_kind: StreamKind::Request,
2089            stream_id,
2090        });
2091        let any = AnyControlMessage::Draft21(msg.clone());
2092        let raw = match send.write_control(&any).await {
2093            Ok(raw) => raw,
2094            Err(e) => {
2095                let _ = send.reset(REQUEST_CANCELLED);
2096                let _ = recv.stop(REQUEST_CANCELLED);
2097                return Err(e);
2098            }
2099        };
2100        self.emit(ClientEvent::ControlMessage {
2101            direction: Direction::Send,
2102            message: any,
2103            stream_id: Some(stream_id),
2104            raw: Some(raw),
2105        });
2106        Ok(RequestStream {
2107            send,
2108            recv,
2109            request_id,
2110            kind,
2111            draft: self.draft,
2112            stream_id,
2113            cancelled: false,
2114            finished: false,
2115            origin: RequestOrigin::Local,
2116            responded: false,
2117            fetch_data: None,
2118            // The sender of a PUBLISH is the one requester draft-21 Section
2119            // 6.4.2.2 excludes from "MAY FIN immediately after sending a
2120            // message": it is the publisher of the subscription the PUBLISH
2121            // establishes, so it owes a PUBLISH_DONE from the moment the
2122            // request goes out.
2123            owes_publish_done: matches!(kind, RequestKind::Publish),
2124        })
2125    }
2126
2127    /// Read the next message off a request stream and dispatch it through the
2128    /// endpoint with that stream's own request id.
2129    ///
2130    /// On draft-21 a response carries no request id; the stream is the
2131    /// correlation, so the id comes from the handle and not from the wire.
2132    ///
2133    /// This blocks until a whole message has arrived. Backpressure is per
2134    /// request: a stream nobody reads stays unread, and the peer stays flow
2135    /// controlled on it alone. A peer that reset the stream surfaces as
2136    /// [`ConnectionError::Transport`] carrying
2137    /// [`TransportError::StreamReset`] with the peer's code; a caller that is
2138    /// deliberately not reading should watch
2139    /// [`RequestStream::peer_cancelled`] instead.
2140    ///
2141    /// # Errors
2142    ///
2143    /// [`ConnectionError::Endpoint`] if the message is not one of this
2144    /// draft's response types, or if it does not fit the request's state.
2145    /// The message has already been emitted to the observer by then — what
2146    /// arrived is reported whether or not the endpoint accepts it.
2147    pub async fn recv_on_request_stream(
2148        &mut self,
2149        stream: &mut RequestStream,
2150    ) -> Result<ControlMessage, ConnectionError> {
2151        let capture_raw = self.observer.is_some();
2152        let (any, raw) = match stream.recv.read_control(capture_raw).await {
2153            Ok(read) => read,
2154            Err(e) => {
2155                // A peer that reset this stream cancelled the request on it,
2156                // and this is where a caller reading normally learns of it. The
2157                // record is made and its verdict dropped: the read's own error
2158                // is what the caller has to act on, and returning a state error
2159                // in its place would hide a reset behind it.
2160                if matches!(e, ConnectionError::Transport(TransportError::StreamReset(_))) {
2161                    let _ = self.endpoint.cancel_request(stream.request_id);
2162                }
2163                return Err(e);
2164            }
2165        };
2166        if capture_raw {
2167            self.emit(ClientEvent::ControlMessage {
2168                direction: Direction::Receive,
2169                message: any.clone(),
2170                stream_id: Some(stream.stream_id()),
2171                raw,
2172            });
2173        }
2174        let msg = match any {
2175            AnyControlMessage::Draft21(msg) => Ok::<_, ConnectionError>(msg),
2176            // `AnyControlMessage` carries one variant per enabled draft feature. With draft 21 the
2177            // only one enabled the arm above is exhaustive and this rejection arm unreachable.
2178            // Compiled in every configuration with the lint allowed, rather than gated on a `cfg`
2179            // naming the other drafts: such a list has to be edited in every draft module
2180            // whenever a draft is added, and a copy that omits one leaves this match
2181            // non-exhaustive.
2182            #[allow(unreachable_patterns)]
2183            _ => Err(ConnectionError::ControlMessageNarrowing),
2184        }?;
2185        // Which dispatcher this belongs to is decided by who opened the
2186        // stream, not by the message. On a stream this endpoint opened the
2187        // next message is the answer to our request; on one the peer opened it
2188        // cannot be, because we are the one who owes an answer. Feeding a
2189        // peer's REQUEST_UPDATE to the response dispatcher would look up a
2190        // request we never made.
2191        let dispatched = match stream.origin {
2192            RequestOrigin::Local => {
2193                self.endpoint.receive_response_on_stream(stream.request_id, msg.clone())
2194            }
2195            RequestOrigin::Peer => {
2196                self.endpoint.receive_on_peer_request_stream(stream.request_id, msg.clone())
2197            }
2198        };
2199        dispatched.map_err(|e| self.close_if_session_fatal(e))?;
2200        // Emitted after the dispatch rather than before it, so an observer sees
2201        // only a notify the endpoint accepted: one from the subscriber, or for
2202        // a request that is not a subscription, ends the session instead
2203        // (Section 9.10) and reporting it as a state change would be a lie.
2204        // The generic `ControlMessage` event above carries it either way.
2205        if let ControlMessage::PublishStateNotify(ref notify) = msg {
2206            self.emit(ClientEvent::PublishStateNotify {
2207                request_id: stream.request_id.into_inner(),
2208                stream_id: stream.stream_id(),
2209                parameters: notify.parameters.clone(),
2210            });
2211        }
2212        // A rejected request establishes nothing, so whatever the request type
2213        // would have owed on this direction is no longer owed. Without this a
2214        // PUBLISH the peer refused could never be finished cleanly — the
2215        // publisher's PUBLISH_DONE obligation would outlive the subscription
2216        // that was never created, and the only way out would be a reset.
2217        if matches!(msg, ControlMessage::RequestError(_)) {
2218            stream.owes_publish_done = false;
2219        }
2220        Ok(msg)
2221    }
2222
2223    /// Write a follow-up message on an already-open request stream.
2224    ///
2225    /// The request itself was written when the stream was opened; this is for
2226    /// what comes after it on the same stream, PUBLISH_DONE among them — see
2227    /// [`publish_done`](Self::publish_done), which uses this.
2228    ///
2229    /// It does not refuse any message type. Which messages may follow a
2230    /// request on its own stream is not something this implementation can
2231    /// settle, so the choice is left to the caller rather than guessed at.
2232    pub async fn send_on_request_stream(
2233        &mut self,
2234        stream: &mut RequestStream,
2235        msg: &ControlMessage,
2236    ) -> Result<(), ConnectionError> {
2237        let any = AnyControlMessage::Draft21(msg.clone());
2238        let raw = stream.send.write_control(&any).await?;
2239        self.emit(ClientEvent::ControlMessage {
2240            direction: Direction::Send,
2241            message: any,
2242            stream_id: Some(stream.stream_id()),
2243            raw: Some(raw),
2244        });
2245        Ok(())
2246    }
2247
2248    /// Cancel a request: record it at the endpoint, then terminate its stream.
2249    /// Section 6.4.2.3 puts the cancel at the stream — "Implementations cancel a
2250    /// request by abruptly terminating any directions of the stream that are
2251    /// still open" — while the request's own state lives in the endpoint, so
2252    /// the two have to move together. This is the only place that moves both.
2253    ///
2254    /// The endpoint goes first and the stream is terminated only if it agrees,
2255    /// which is the order every request path here uses: a caller acts on a
2256    /// stream after the endpoint has accepted the step, never before. A refused
2257    /// cancel therefore leaves the stream exactly as it was, and
2258    /// [`RequestStream::cancel`] is still there for a caller that wants the
2259    /// stream reset regardless.
2260    ///
2261    /// Idempotent from both ends: a request that has already ended accepts the
2262    /// cancel and stays where it is, and a handle that has already been
2263    /// cancelled resets nothing a second time.
2264    ///
2265    /// # Errors
2266    ///
2267    /// [`ConnectionError::Endpoint`] if no request carries this stream's id or
2268    /// the request has not been written, and [`ConnectionError::Transport`] if
2269    /// `code` is outside the QUIC varint range — see
2270    /// [`RequestStream::cancel`], which is what sends it.
2271    pub fn cancel_request_stream(
2272        &mut self,
2273        stream: &mut RequestStream,
2274        code: u64,
2275    ) -> Result<(), ConnectionError> {
2276        let recorded = self.endpoint.cancel_request(stream.request_id);
2277        recorded.map_err(|e| self.close_if_session_fatal(e))?;
2278        stream.cancel(code)
2279    }
2280
2281    /// Wait for the peer to cancel this request, and record it if it does.
2282    ///
2283    /// [`RequestStream::peer_cancelled`] with the endpoint's record attached. A
2284    /// caller applying backpressure is deliberately not calling
2285    /// [`recv_on_request_stream`](Self::recv_on_request_stream), which is the
2286    /// other place a peer reset surfaces, so without this the request would end
2287    /// on the wire and stay open in the endpoint's record for as long as the
2288    /// backpressure lasts.
2289    ///
2290    /// Returns what the handle's own method returns; see it for the `Ok(None)`
2291    /// case and for what WebTransport can and cannot observe. Cancel-safe, and
2292    /// it grants no flow-control credit.
2293    pub async fn peer_cancelled_on_request_stream(
2294        &mut self,
2295        stream: &mut RequestStream,
2296    ) -> Result<Option<u64>, ConnectionError> {
2297        let code = stream.peer_cancelled().await?;
2298        if code.is_some() {
2299            // Discarded for the reason the read path discards it: the peer has
2300            // ended the request whatever the record said, and a state error
2301            // here would replace the answer the caller asked for.
2302            let _ = self.endpoint.cancel_request(stream.request_id);
2303        }
2304        Ok(code)
2305    }
2306
2307    // -- Accepting the peer's request streams -----------------------
2308
2309    /// Accept the next bidirectional stream the peer opened, read the request
2310    /// it begins with, and hand back that request and a handle to answer it
2311    /// on.
2312    ///
2313    /// This is the mirror of the request helpers. Where
2314    /// [`subscribe`](Self::subscribe) and its siblings open a stream and write
2315    /// a request, this takes one the peer opened and reads one. Draft-21
2316    /// Section 6.3 puts requests in both directions on bidirectional streams,
2317    /// so a client that only ever calls the helpers can never be published to
2318    /// or subscribed from.
2319    ///
2320    /// The returned [`RequestStream`] carries [`RequestOrigin::Peer`]. Answer
2321    /// it with [`respond_subscribe_ok`](Self::respond_subscribe_ok),
2322    /// [`respond_fetch_ok`](Self::respond_fetch_ok),
2323    /// [`respond_ok`](Self::respond_ok) or
2324    /// [`respond_error`](Self::respond_error), and **hold it for as long as
2325    /// the request lasts** — a subscription's PUBLISH_DONE is written on it,
2326    /// and dropping it resets the stream.
2327    ///
2328    /// # Two refusals, two codes
2329    ///
2330    /// Draft-21 Section 6.3, on a stream that begins with the wrong type:
2331    /// "Bidirectional streams MUST NOT begin with any other message type
2332    /// unless negotiated. If they do, the peer MUST close the Session with a
2333    /// PROTOCOL_VIOLATION." Section 6.4.2.1, on the Request ID: "If an endpoint
2334    /// receives a Request ID where the least significant bit is incorrect for
2335    /// the sender, or a duplicate Request ID, it MUST close the session with
2336    /// INVALID_REQUEST_ID." Both are closes of the session on the wire, with
2337    /// different codes, and both happen before this returns — the error handed
2338    /// back reports a session that is already gone, not one the caller must
2339    /// remember to close.
2340    ///
2341    /// # Cancelling this future loses nothing
2342    ///
2343    /// A stream taken off the transport but not yet read is put back on an
2344    /// internal queue, and the next call takes it before accepting anything
2345    /// new — including whatever bytes of the request had already arrived,
2346    /// which live in the stream's own reader. So this is safe to `select!`
2347    /// against a shutdown signal or a timer. See
2348    /// [`pending_inbound_count`](Self::pending_inbound_count).
2349    ///
2350    /// What it is **not** safe to do is run concurrently with another method
2351    /// on the same connection: this takes `&mut self` because registering the
2352    /// peer's request moves endpoint state, and no signature avoids that while
2353    /// the connection owns the endpoint. A caller blocked in
2354    /// [`recv_on_request_stream`](Self::recv_on_request_stream) waiting for
2355    /// its own response is not accepting, and the peer's request streams queue
2356    /// up in the transport behind it. One loop that never blocks indefinitely
2357    /// on a single read is the shape this supports.
2358    ///
2359    /// # Ordering
2360    ///
2361    /// The endpoint is told about the request last, after every step that can
2362    /// fail or be cancelled, and building the handle afterwards cannot fail.
2363    /// This is the inverse of the outbound path's reasoning — it opens the
2364    /// stream before allocating a Request ID for the same reason — and rests
2365    /// on the same fact: the endpoint has no way to abandon a request it has
2366    /// already registered. Registering earlier would let a cancelled accept
2367    /// leave a state machine keyed to a stream nobody holds, and the peer's
2368    /// next use of that Request ID would then be reported as a duplicate — a
2369    /// session close, over an id the peer used exactly once.
2370    ///
2371    /// # Errors
2372    ///
2373    /// - [`ConnectionError::NonRequestOnRequestStream`] — the session has been
2374    ///   closed with PROTOCOL_VIOLATION and the stream reset.
2375    /// - [`ConnectionError::Endpoint`] carrying `RequestId` or
2376    ///   `DuplicateRequestId` — the session has been closed with
2377    ///   INVALID_REQUEST_ID and the stream reset.
2378    /// - [`ConnectionError::Endpoint`] carrying `NotActive` or `Draining` —
2379    ///   the stream is reset, the session is left alone.
2380    /// - [`ConnectionError::Transport`] or [`ConnectionError::Codec`] — the
2381    ///   stream is reset, the session is left alone.
2382    pub async fn accept_request_stream(
2383        &mut self,
2384    ) -> Result<(ControlMessage, RequestStream), ConnectionError> {
2385        let pair = match self.take_pending_inbound() {
2386            Some(pair) => pair,
2387            None => {
2388                let (send, recv) = self.transport.accept_bi().await?;
2389                (FramedSendStream::new(send, self.draft), FramedRecvStream::new(recv, self.draft))
2390            }
2391        };
2392        let capture_raw = self.observer.is_some();
2393
2394        let (any, raw, mut send, mut recv) = {
2395            let mut pending = PendingInbound { pair: Some(pair), queue: &self.pending_inbound };
2396            let read = {
2397                let (_, recv) = pending.pair.as_mut().expect("set on construction");
2398                recv.read_control(capture_raw).await
2399            };
2400            // Taken out before anything can return, so the guard's Drop puts
2401            // the pair back for exactly one reason: this future was cancelled.
2402            let (mut send, mut recv) = pending.pair.take().expect("set on construction");
2403            match read {
2404                Ok((any, raw)) => (any, raw, send, recv),
2405                Err(e) => {
2406                    // A stream whose first message could not be read is not
2407                    // worth queueing: the next accept would fail on it the
2408                    // same way. Reset rather than FIN — nothing was served.
2409                    let _ = send.reset(REQUEST_UNANSWERED);
2410                    let _ = recv.stop(REQUEST_UNANSWERED);
2411                    return Err(e);
2412                }
2413            }
2414        };
2415
2416        // Reported once the request has actually arrived rather than when the
2417        // stream came off the transport, so a cancelled accept that is retried
2418        // does not report the same stream twice.
2419        let stream_id = send.stream_id();
2420        self.emit(ClientEvent::StreamOpened {
2421            direction: Direction::Receive,
2422            stream_kind: StreamKind::Request,
2423            stream_id,
2424        });
2425        if capture_raw {
2426            self.emit(ClientEvent::ControlMessage {
2427                direction: Direction::Receive,
2428                message: any.clone(),
2429                stream_id: Some(stream_id),
2430                raw,
2431            });
2432        }
2433
2434        let msg = match any {
2435            AnyControlMessage::Draft21(msg) => msg,
2436            // `AnyControlMessage` carries one variant per enabled draft feature. With draft 21 the
2437            // only one enabled the arm above is exhaustive and this rejection arm unreachable.
2438            // Compiled in every configuration with the lint allowed, rather than gated on a `cfg`
2439            // naming the other drafts: such a list has to be edited in every draft module
2440            // whenever a draft is added, and a copy that omits one leaves this match
2441            // non-exhaustive.
2442            #[allow(unreachable_patterns)]
2443            _ => {
2444                let _ = send.reset(REQUEST_UNANSWERED);
2445                let _ = recv.stop(REQUEST_UNANSWERED);
2446                return Err(ConnectionError::ControlMessageNarrowing);
2447            }
2448        };
2449
2450        let ty = msg.message_type();
2451        let Some(kind) = RequestKind::from_message_type(ty) else {
2452            let err = self.endpoint.refuse_non_request(ty);
2453            self.close_for(&err);
2454            let _ = send.reset(REQUEST_UNANSWERED);
2455            let _ = recv.stop(REQUEST_UNANSWERED);
2456            return Err(ConnectionError::NonRequestOnRequestStream(ty));
2457        };
2458
2459        let request_id = match self.endpoint.receive_request_on_stream(&msg) {
2460            Ok(request_id) => request_id,
2461            Err(e) => {
2462                let _ = send.reset(REQUEST_UNANSWERED);
2463                let _ = recv.stop(REQUEST_UNANSWERED);
2464                return Err(self.close_if_session_fatal(e));
2465            }
2466        };
2467
2468        Ok((
2469            msg,
2470            RequestStream {
2471                send,
2472                recv,
2473                request_id,
2474                kind,
2475                draft: self.draft,
2476                stream_id,
2477                cancelled: false,
2478                finished: false,
2479                origin: RequestOrigin::Peer,
2480                responded: false,
2481                fetch_data: None,
2482                // A peer's SUBSCRIBE does not establish a subscription until
2483                // it is accepted, so nothing is owed until
2484                // `respond_subscribe_ok` runs.
2485                owes_publish_done: false,
2486            },
2487        ))
2488    }
2489
2490    /// Take the oldest stream pair a cancelled
2491    /// [`accept_request_stream`](Self::accept_request_stream) put back, if any.
2492    ///
2493    /// Synchronous on purpose, like
2494    /// [`take_deferred_uni`](Self::take_deferred_uni): the guard is dropped
2495    /// before the caller awaits, so the lock is never held across a suspension
2496    /// point.
2497    fn take_pending_inbound(&self) -> Option<(FramedSendStream, FramedRecvStream)> {
2498        self.pending_inbound.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).pop_front()
2499    }
2500
2501    /// How many peer-opened request streams a cancelled
2502    /// [`accept_request_stream`](Self::accept_request_stream) put back and a
2503    /// later call has not yet taken.
2504    ///
2505    /// Zero unless an accept future was dropped mid-read.
2506    pub fn pending_inbound_count(&self) -> usize {
2507        self.pending_inbound.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).len()
2508    }
2509
2510    // -- Answering the peer's requests ------------------------------
2511
2512    /// Write `msg` on the request stream `stream` carries, driving the
2513    /// endpoint first and the wire second.
2514    ///
2515    /// The response goes on the request's own bidirectional stream and never
2516    /// on the control stream: draft-21 responses carry no Request ID, so the
2517    /// stream is the only thing that says what is being answered. Taking the
2518    /// id off the handle rather than from the caller makes that correlation
2519    /// unforgeable.
2520    ///
2521    /// `fin` is true only for REQUEST_ERROR. See
2522    /// [`respond_error`](Self::respond_error).
2523    async fn respond(
2524        &mut self,
2525        stream: &mut RequestStream,
2526        msg: ControlMessage,
2527        fin: bool,
2528    ) -> Result<(), ConnectionError> {
2529        // A request this endpoint made is answered by the peer, with one
2530        // exception the draft states outright: "A subscriber can also send
2531        // REQUEST_UPDATE to modify parameters of a subscription established
2532        // with PUBLISH", and the receiver of one "MUST respond with exactly one
2533        // REQUEST_OK or REQUEST_ERROR message indicating if the update was
2534        // successful". On a PUBLISH this endpoint sent, that receiver is this
2535        // endpoint, so the one response it may write on a stream of its own is
2536        // the answer to an update waiting there.
2537        let answers_an_update =
2538            matches!(msg, ControlMessage::RequestOk(_) | ControlMessage::RequestError(_))
2539                && self.endpoint.has_unanswered_update(stream.request_id);
2540        if stream.origin != RequestOrigin::Peer && !answers_an_update {
2541            return Err(ConnectionError::RespondedToOwnRequest(stream.request_id.into_inner()));
2542        }
2543        // The endpoint first, so a response that does not fit the request's
2544        // state is refused before any of it reaches the wire. What this cannot
2545        // undo is a write that fails afterwards, which leaves the state
2546        // machine one step ahead of the peer — the same asymmetry
2547        // `begin_request` carries on the outbound side.
2548        self.endpoint.send_response_on_stream(stream.request_id, &msg)?;
2549        self.send_on_request_stream(stream, &msg).await?;
2550        stream.responded = true;
2551        // A REQUEST_ERROR answering an update retires nothing: the
2552        // subscription is live and Section 9.5 now asks for a PUBLISH_DONE
2553        // carrying UPDATE_FAILED. So neither the flag nor the send half is
2554        // cleared, and the obligation this draft already models goes on
2555        // standing until that message is written.
2556        // Section 9.5.1: "When a REQUEST_UPDATE fails for a FETCH, the
2557        // publisher MUST reset the FETCH data stream." A REQUEST_ERROR on a
2558        // fetch that has already been answered can only be answering an
2559        // update, because the request's own answer was the FETCH_OK; one
2560        // before that refuses the fetch itself, and there is no data stream
2561        // open to reset.
2562        if fin && stream.kind == RequestKind::Fetch && stream.responded {
2563            stream.reset_fetch_data();
2564        }
2565        if fin && !self.endpoint.owes_update_failure(stream.request_id) {
2566            // A rejected request owes nothing further, so the guard in
2567            // `finish` cannot be standing: clear the flag rather than let a
2568            // REQUEST_ERROR trip over an obligation the error just retired.
2569            stream.owes_publish_done = false;
2570            stream.finish().await?;
2571        }
2572        Ok(())
2573    }
2574
2575    /// Answer a peer's PUBLISH, PUBLISH_NAMESPACE, SUBSCRIBE_NAMESPACE,
2576    /// SUBSCRIBE_TRACKS or TRACK_STATUS with REQUEST_OK.
2577    ///
2578    /// Draft-18 folded PUBLISH_OK into REQUEST_OK and draft-21 keeps the fold,
2579    /// so this is the one success message for five of the seven request kinds
2580    /// — there is no `respond_publish_ok` here, where draft-17 has one.
2581    ///
2582    /// The send half is left open. A SUBSCRIBE_NAMESPACE responder still owes
2583    /// the peer the namespaces it accepted, so finishing here would end the
2584    /// request before it had been served; a TRACK_STATUS responder owes
2585    /// nothing further and may call [`RequestStream::finish`] straight after.
2586    ///
2587    /// # Errors
2588    ///
2589    /// [`ConnectionError::RespondedToOwnRequest`] if `stream` is one this
2590    /// endpoint opened, and [`ConnectionError::Endpoint`] if no request of a
2591    /// kind REQUEST_OK answers is pending on it — including the Section 9.3
2592    /// case of Track Properties on anything but a TRACK_STATUS response.
2593    /// Nothing is written in any of them.
2594    pub async fn respond_ok(
2595        &mut self,
2596        stream: &mut RequestStream,
2597        response: RequestOk,
2598    ) -> Result<(), ConnectionError> {
2599        self.respond(stream, ControlMessage::RequestOk(response), false).await
2600    }
2601
2602    /// Answer a peer's SUBSCRIBE with SUBSCRIBE_OK.
2603    ///
2604    /// The send half is left open, and it must be: this endpoint is now the
2605    /// publisher of an established subscription and owes it a PUBLISH_DONE,
2606    /// which travels on this same stream —
2607    /// [`publish_done_on`](Self::publish_done_on). Until that has been sent,
2608    /// [`RequestStream::finish`] refuses, per draft-21 Section 6.4.2.2.
2609    pub async fn respond_subscribe_ok(
2610        &mut self,
2611        stream: &mut RequestStream,
2612        response: SubscribeOk,
2613    ) -> Result<(), ConnectionError> {
2614        self.respond(stream, ControlMessage::SubscribeOk(response), false).await?;
2615        stream.owes_publish_done = true;
2616        Ok(())
2617    }
2618
2619    /// Answer a peer's FETCH with FETCH_OK.
2620    ///
2621    /// The send half is left open. The fetched objects travel on separate
2622    /// unidirectional streams, so a fetch responder may call
2623    /// [`RequestStream::finish`] as soon as this returns; it is not done here
2624    /// because nothing about FETCH_OK says the responder has no more to write.
2625    pub async fn respond_fetch_ok(
2626        &mut self,
2627        stream: &mut RequestStream,
2628        response: FetchOk,
2629    ) -> Result<(), ConnectionError> {
2630        self.respond(stream, ControlMessage::FetchOk(response), false).await
2631    }
2632
2633    /// Reject a peer's request with REQUEST_ERROR, and finish the send half.
2634    ///
2635    /// The FIN is part of the act, not a convenience: draft-21 Section 6.4.2.3
2636    /// says "When an endpoint rejects a request without performing any
2637    /// application processing, it SHOULD send a REQUEST_ERROR and FIN the
2638    /// stream." It is also the one response that can be finished immediately,
2639    /// because a rejected request leaves nothing further to send — every
2640    /// success path owes the peer something more, which is what Section 6.4.2.2
2641    /// makes a MUST NOT for the rest of them.
2642    ///
2643    /// A finished handle does nothing further on [`Drop`], so the rejected
2644    /// stream is not then reset.
2645    pub async fn respond_error(
2646        &mut self,
2647        stream: &mut RequestStream,
2648        response: RequestError,
2649    ) -> Result<(), ConnectionError> {
2650        self.respond(stream, ControlMessage::RequestError(response), true).await
2651    }
2652
2653    /// End a subscription this endpoint accepted, on the stream the peer's
2654    /// SUBSCRIBE opened.
2655    ///
2656    /// The mirror of [`publish_done`](Self::publish_done), which ends a
2657    /// publication this endpoint offered with PUBLISH. Both write PUBLISH_DONE
2658    /// on a request stream and take the Request ID off the handle; they differ
2659    /// in which state machine moves, and therefore in which one refuses.
2660    ///
2661    /// The send half is finished once the message is out, for the reason
2662    /// [`publish_done`](Self::publish_done) gives: Section 6.4.2.2 names
2663    /// PUBLISH_DONE as the last required message on a publisher's direction and
2664    /// asks for the FIN promptly after it.
2665    pub async fn publish_done_on(
2666        &mut self,
2667        stream: &mut RequestStream,
2668        status_code: VarInt,
2669        stream_count: VarInt,
2670        reason_phrase: Vec<u8>,
2671    ) -> Result<(), ConnectionError> {
2672        let msg = ControlMessage::PublishDone(moqtap_codec::draft21::message::PublishDone {
2673            status_code,
2674            stream_count,
2675            reason_phrase,
2676        });
2677        self.respond(stream, msg, false).await?;
2678        stream.owes_publish_done = false;
2679        stream.finish().await
2680    }
2681
2682    /// Announce a namespace on a peer's SUBSCRIBE_NAMESPACE stream.
2683    ///
2684    /// Draft-21 Section 9.16 puts NAMESPACE "on the response stream of a
2685    /// SUBSCRIBE_NAMESPACE request", and Table 5 gives it the Stream value
2686    /// Request rather than Control — which is why this exists at all and why
2687    /// [`send_control`](Self::send_control) is the wrong route for it. Section
2688    /// 9.17 has the announcements follow the acceptance, so this refuses until
2689    /// [`respond_ok`](Self::respond_ok) has run on the same stream.
2690    pub async fn namespace_on(
2691        &mut self,
2692        stream: &mut RequestStream,
2693        response: Namespace,
2694    ) -> Result<(), ConnectionError> {
2695        self.respond(stream, ControlMessage::Namespace(response), false).await
2696    }
2697
2698    /// Withdraw a namespace on a peer's SUBSCRIBE_NAMESPACE stream.
2699    ///
2700    /// Section 9.15: "The publisher MUST NOT send NAMESPACE_DONE for a
2701    /// namespace suffix before the corresponding NAMESPACE." Which suffixes
2702    /// have been announced is the caller's bookkeeping, not this connection's,
2703    /// so what is enforced here is only that the request was accepted first.
2704    pub async fn namespace_done_on(
2705        &mut self,
2706        stream: &mut RequestStream,
2707        response: NamespaceDone,
2708    ) -> Result<(), ConnectionError> {
2709        self.respond(stream, ControlMessage::NamespaceDone(response), false).await
2710    }
2711
2712    /// Tell the peer a track matching its SUBSCRIBE_TRACKS will not be
2713    /// published, on that request's own stream.
2714    ///
2715    /// Section 9.19: "All PUBLISH_SKIPPED messages are in response to a
2716    /// SUBSCRIBE_TRACKS," which is why this refuses any other kind of stream —
2717    /// the endpoint looks the Request ID up among the SUBSCRIBE_TRACKS
2718    /// requests alone.
2719    pub async fn publish_skipped_on(
2720        &mut self,
2721        stream: &mut RequestStream,
2722        response: PublishSkipped,
2723    ) -> Result<(), ConnectionError> {
2724        self.respond(stream, ControlMessage::PublishSkipped(response), false).await
2725    }
2726
2727    // -- Subscribe flow ---------------------------------------------
2728
2729    /// Send a SUBSCRIBE on a bidirectional stream of its own.
2730    ///
2731    /// The returned [`RequestStream`] is where SUBSCRIBE_OK, REQUEST_ERROR
2732    /// and later PUBLISH_DONE arrive — read them with
2733    /// [`recv_on_request_stream`](Self::recv_on_request_stream). **Hold it for
2734    /// the subscription's life**: dropping it resets the stream, which
2735    /// cancels the subscription.
2736    pub async fn subscribe(
2737        &mut self,
2738        track_namespace: TrackNamespace,
2739        track_name: Vec<u8>,
2740        parameters: Vec<KeyValuePair>,
2741    ) -> Result<RequestStream, ConnectionError> {
2742        let mut halves = self.open_request_bi().await?;
2743        let (req_id, msg) = Self::or_abandon(
2744            &mut halves,
2745            self.endpoint.subscribe(track_namespace, track_name, parameters),
2746        )?;
2747        self.begin_request(halves, RequestKind::Subscribe, req_id, &msg).await
2748    }
2749
2750    // Draft-21 inherits draft-17's removal of UNSUBSCRIBE. Subscribers end a
2751    // subscription by resetting its request stream — `RequestStream::cancel`
2752    // — or wait for PublishDone.
2753
2754    // -- Fetch flow -------------------------------------------------
2755
2756    /// Send a FETCH on a bidirectional stream of its own.
2757    ///
2758    /// FETCH_OK or REQUEST_ERROR comes back on the returned
2759    /// [`RequestStream`]; the fetched objects arrive on separate
2760    /// unidirectional data streams. Dropping the handle cancels the fetch.
2761    ///
2762    /// # The range is a parameter now
2763    ///
2764    /// Draft-21 Section 9.11 is not draft-19's FETCH: there is no `Fetch Type`, no
2765    /// Standalone or Joining structure, and no inline `Start Location` /
2766    /// `End Location` pair. The range travels in the `LOCATION_FILTER`
2767    /// parameter, so this takes the same three arguments
2768    /// [`subscribe`](Self::subscribe) does. [`fetch_range`](Self::fetch_range)
2769    /// is the same call with the filter built for you; a FETCH with no filter
2770    /// covers `{0,0}` through Largest Object, inclusive.
2771    pub async fn fetch(
2772        &mut self,
2773        track_namespace: TrackNamespace,
2774        track_name: Vec<u8>,
2775        parameters: Vec<KeyValuePair>,
2776    ) -> Result<RequestStream, ConnectionError> {
2777        let mut halves = self.open_request_bi().await?;
2778        let (req_id, msg) = Self::or_abandon(
2779            &mut halves,
2780            self.endpoint.fetch(track_namespace, track_name, parameters),
2781        )?;
2782        self.begin_request(halves, RequestKind::Fetch, req_id, &msg).await
2783    }
2784
2785    /// Send a FETCH for one range, carried as a `LOCATION_FILTER` parameter.
2786    ///
2787    /// **The range is inclusive at both ends.** Draft-19's `End Location` was
2788    /// "the last Object, plus 1; or 0 to indicate the entire Group";
2789    /// draft-21 Section 3.3.1 and draft-21 Section 9.11 both call the filter's
2790    /// range inclusive and delete both conventions, and nothing here restores
2791    /// them. Port a draft-19 call by removing the `+ 1`.
2792    pub async fn fetch_range(
2793        &mut self,
2794        track_namespace: TrackNamespace,
2795        track_name: Vec<u8>,
2796        range: &LocationFilter,
2797        parameters: Vec<KeyValuePair>,
2798    ) -> Result<RequestStream, ConnectionError> {
2799        let mut halves = self.open_request_bi().await?;
2800        let (req_id, msg) = Self::or_abandon(
2801            &mut halves,
2802            self.endpoint.fetch_range(track_namespace, track_name, range, parameters),
2803        )?;
2804        self.begin_request(halves, RequestKind::Fetch, req_id, &msg).await
2805    }
2806
2807    // Draft-21 has no joining fetch. Section 9.11 has no Fetch Type field, no
2808    // variant structures and no joining mechanism (draft-20 removed them), and
2809    // Section 3.4's fill fetch stream replaces it: a subscriber asks for the
2810    // Objects behind the live edge by putting a `FILL_PARAMETERS` parameter on
2811    // its SUBSCRIBE (or on a later REQUEST_UPDATE) rather than by opening a
2812    // second request. See [`accept_fill_stream`](Self::accept_fill_stream) for
2813    // the stream that answers it, and `crate::draft21::fill` for the parameter.
2814
2815    // Draft-21 inherits draft-17's removal of FETCH_CANCEL. Fetchers abort
2816    // with `RequestStream::cancel`, which resets the request stream.
2817
2818    // -- Namespace flows --------------------------------------------
2819
2820    /// Send a SUBSCRIBE_NAMESPACE on a bidirectional stream of its own.
2821    ///
2822    /// Draft-18 split the draft-17 SUBSCRIBE_NAMESPACE into two messages and
2823    /// draft-21 keeps the split. This call sends the renumbered
2824    /// SUBSCRIBE_NAMESPACE (type 0x50), which subscribes to NAMESPACE /
2825    /// NAMESPACE_DONE announcements only. To receive PUBLISH messages for
2826    /// matching tracks, use [`Self::subscribe_tracks`] instead — a separate
2827    /// request on a request stream of its own.
2828    pub async fn subscribe_namespace(
2829        &mut self,
2830        namespace_prefix: TrackNamespace,
2831        parameters: Vec<KeyValuePair>,
2832    ) -> Result<RequestStream, ConnectionError> {
2833        let mut halves = self.open_request_bi().await?;
2834        let (req_id, msg) = Self::or_abandon(
2835            &mut halves,
2836            self.endpoint.subscribe_namespace(namespace_prefix, parameters),
2837        )?;
2838        self.begin_request(halves, RequestKind::SubscribeNamespace, req_id, &msg).await
2839    }
2840
2841    /// Send a SUBSCRIBE_TRACKS (type 0x51, new in draft-18) on a bidirectional
2842    /// stream of its own. Causes the relay to PUBLISH matching tracks back to
2843    /// us.
2844    ///
2845    /// Draft-17 has no such message: this is the seventh request type, and the
2846    /// one that makes draft-21's set differ from draft-17's.
2847    pub async fn subscribe_tracks(
2848        &mut self,
2849        namespace_prefix: TrackNamespace,
2850        parameters: Vec<KeyValuePair>,
2851    ) -> Result<RequestStream, ConnectionError> {
2852        let mut halves = self.open_request_bi().await?;
2853        let (req_id, msg) = Self::or_abandon(
2854            &mut halves,
2855            self.endpoint.subscribe_tracks(namespace_prefix, parameters),
2856        )?;
2857        self.begin_request(halves, RequestKind::SubscribeTracks, req_id, &msg).await
2858    }
2859
2860    /// Send a PUBLISH_NAMESPACE on a bidirectional stream of its own.
2861    pub async fn publish_namespace(
2862        &mut self,
2863        track_namespace: TrackNamespace,
2864        parameters: Vec<KeyValuePair>,
2865    ) -> Result<RequestStream, ConnectionError> {
2866        let mut halves = self.open_request_bi().await?;
2867        let (req_id, msg) = Self::or_abandon(
2868            &mut halves,
2869            self.endpoint.publish_namespace(track_namespace, parameters),
2870        )?;
2871        self.begin_request(halves, RequestKind::PublishNamespace, req_id, &msg).await
2872    }
2873
2874    // -- Track Status flow ------------------------------------------
2875
2876    /// Send a TRACK_STATUS on a bidirectional stream of its own.
2877    pub async fn track_status(
2878        &mut self,
2879        track_namespace: TrackNamespace,
2880        track_name: Vec<u8>,
2881        parameters: Vec<KeyValuePair>,
2882    ) -> Result<RequestStream, ConnectionError> {
2883        let mut halves = self.open_request_bi().await?;
2884        let (req_id, msg) = Self::or_abandon(
2885            &mut halves,
2886            self.endpoint.track_status(track_namespace, track_name, parameters),
2887        )?;
2888        self.begin_request(halves, RequestKind::TrackStatus, req_id, &msg).await
2889    }
2890
2891    // -- Publish flow (publisher side) ------------------------------
2892
2893    /// Send a PUBLISH on a bidirectional stream of its own.
2894    ///
2895    /// REQUEST_OK — which is what draft-21 answers a PUBLISH with, PUBLISH_OK
2896    /// having been folded into it — or REQUEST_ERROR comes back on the
2897    /// returned [`RequestStream`], and [`publish_done`](Self::publish_done) is
2898    /// written back on it when the publication ends, so the handle must be
2899    /// held for as long as the publication lasts.
2900    pub async fn publish(
2901        &mut self,
2902        track_namespace: TrackNamespace,
2903        track_name: Vec<u8>,
2904        track_alias: VarInt,
2905        parameters: Vec<KeyValuePair>,
2906        track_properties: Vec<KeyValuePair>,
2907    ) -> Result<RequestStream, ConnectionError> {
2908        let mut halves = self.open_request_bi().await?;
2909        let (req_id, msg) = Self::or_abandon(
2910            &mut halves,
2911            self.endpoint.publish(
2912                track_namespace,
2913                track_name,
2914                track_alias,
2915                parameters,
2916                track_properties,
2917            ),
2918        )?;
2919        self.begin_request(halves, RequestKind::Publish, req_id, &msg).await
2920    }
2921
2922    /// Send a PUBLISH_DONE on the request stream the PUBLISH opened.
2923    ///
2924    /// PUBLISH_DONE is a response and carries no request id on the wire, so
2925    /// the stream is the only thing that says which publication ended. The id
2926    /// the endpoint needs is taken off `stream`, which makes the correlation
2927    /// unforgeable — there is no way to name one request and write on
2928    /// another's stream.
2929    ///
2930    /// The send half is finished once the message is out. Draft-21 Section
2931    /// 6.4.2.2 names PUBLISH_DONE as the last required message on a publisher's
2932    /// direction — "the publisher of an Established subscription MUST send
2933    /// PUBLISH_DONE, before sending a FIN" — and asks for the FIN promptly
2934    /// afterwards, since nothing further is owed on that direction. Leaving it
2935    /// open instead would end the publication at [`Drop`], which resets the
2936    /// stream with REQUEST_CANCELLED and tells the peer the request was
2937    /// abandoned rather than completed.
2938    ///
2939    /// The receive half stays open. A FIN closes one direction, so the
2940    /// subscriber can still be heard from on its own.
2941    pub async fn publish_done(
2942        &mut self,
2943        stream: &mut RequestStream,
2944        status_code: VarInt,
2945        stream_count: VarInt,
2946        reason_phrase: Vec<u8>,
2947    ) -> Result<(), ConnectionError> {
2948        let request_id = stream.request_id();
2949        let msg = self.endpoint.send_publish_done(
2950            request_id,
2951            status_code,
2952            stream_count,
2953            reason_phrase,
2954        )?;
2955        self.send_on_request_stream(stream, &msg).await?;
2956        stream.owes_publish_done = false;
2957        stream.finish().await
2958    }
2959
2960    // -- Data streams -----------------------------------------------
2961
2962    /// Open a new unidirectional stream for sending subgroup data.
2963    pub async fn open_subgroup_stream(
2964        &self,
2965        header: &AnySubgroupHeader,
2966    ) -> Result<FramedSendStream, ConnectionError> {
2967        let send = self.transport.open_uni().await?;
2968        let mut framed = FramedSendStream::new(send, self.draft);
2969        let sid = framed.stream_id();
2970        framed.write_subgroup_header(header).await?;
2971        self.emit(ClientEvent::StreamOpened {
2972            direction: Direction::Send,
2973            stream_kind: StreamKind::Subgroup,
2974            stream_id: sid,
2975        });
2976        self.emit(ClientEvent::DataStreamHeader {
2977            stream_id: sid,
2978            direction: Direction::Send,
2979            header: header.clone(),
2980        });
2981        Ok(framed)
2982    }
2983
2984    /// Open a new unidirectional stream for sending a FETCH's objects.
2985    ///
2986    /// The objects answering a FETCH do not go on the request's own stream:
2987    /// they go on a unidirectional stream of their own, which opens with a
2988    /// FETCH_HEADER naming the request they belong to. This writes that header
2989    /// and hands back the stream, the same way
2990    /// [`open_subgroup_stream`](Self::open_subgroup_stream) does for a
2991    /// subgroup.
2992    ///
2993    /// The caller owns the stream that comes back. Nothing here remembers
2994    /// which request it belongs to, so an endpoint serving several fetches at
2995    /// once keeps its own map from Request ID to stream.
2996    pub async fn open_fetch_stream(
2997        &self,
2998        header: &AnyFetchHeader,
2999    ) -> Result<FramedSendStream, ConnectionError> {
3000        let send = self.transport.open_uni().await?;
3001        let mut framed = FramedSendStream::new(send, self.draft);
3002        let sid = framed.stream_id();
3003        framed.write_fetch_header(header).await?;
3004        self.emit(ClientEvent::StreamOpened {
3005            direction: Direction::Send,
3006            stream_kind: StreamKind::Fetch,
3007            stream_id: sid,
3008        });
3009        Ok(framed)
3010    }
3011
3012    /// Open the data stream for a FETCH this endpoint is answering, and keep
3013    /// the handle on the request.
3014    ///
3015    /// The same stream [`open_fetch_stream`](Self::open_fetch_stream) returns,
3016    /// parked on the request stream it belongs to. That is what lets a rule
3017    /// about the fetch reach the objects it is serving: a refused
3018    /// REQUEST_UPDATE has to reset this stream, and the connection cannot
3019    /// reset a handle the caller walked away with.
3020    ///
3021    /// Write objects through
3022    /// [`RequestStream::fetch_data`](RequestStream::fetch_data), or through
3023    /// the borrow this returns.
3024    pub async fn open_fetch_stream_on<'s>(
3025        &self,
3026        stream: &'s mut RequestStream,
3027        header: &AnyFetchHeader,
3028    ) -> Result<&'s mut FramedSendStream, ConnectionError> {
3029        let framed = self.open_fetch_stream(header).await?;
3030        stream.fetch_data = Some(framed);
3031        Ok(stream.fetch_data.as_mut().expect("just stored"))
3032    }
3033
3034    /// Accept an incoming unidirectional data stream and read its subgroup
3035    /// header.
3036    ///
3037    /// Streams the peer opened before its control stream are returned first,
3038    /// in arrival order, before any new one is accepted from the transport:
3039    /// [`connect`](Self::connect) had to look at them to find the control
3040    /// stream and set the rest aside rather than drop them. They are
3041    /// otherwise ordinary — the type varint `connect` read is still on the
3042    /// front of each one.
3043    ///
3044    /// A FETCH_HEADER stream, fetch or fill, is never read as a subgroup: it
3045    /// is set aside for [`accept_fetch_stream`](Self::accept_fetch_stream)
3046    /// and [`accept_fill_stream`](Self::accept_fill_stream), and this waits
3047    /// for the next stream.
3048    pub async fn accept_subgroup_stream(
3049        &self,
3050    ) -> Result<(AnySubgroupHeader, FramedRecvStream), ConnectionError> {
3051        let mut framed = self.next_non_fetch_uni().await?;
3052        let sid = framed.stream_id();
3053        let header = framed.read_subgroup_header().await?;
3054        self.emit(ClientEvent::StreamOpened {
3055            direction: Direction::Receive,
3056            stream_kind: StreamKind::Subgroup,
3057            stream_id: sid,
3058        });
3059        self.emit(ClientEvent::DataStreamHeader {
3060            stream_id: sid,
3061            direction: Direction::Receive,
3062            header: header.clone(),
3063        });
3064        // The track is resolved here and not inside the stream: it takes the
3065        // endpoint's alias table, which a stream handle has no way back to.
3066        // Handed over rather than offered, so measuring is not something a
3067        // caller has to remember to ask for.
3068        if let Some(objects) = self.endpoint.track_objects(header.track_alias()) {
3069            framed.measure_objects_against(objects, header.group_id());
3070        }
3071        Ok((header, framed))
3072    }
3073
3074    /// Accept the next unidirectional stream and read its fetch header.
3075    ///
3076    /// [`accept_subgroup_stream`](Self::accept_subgroup_stream)'s twin. The two
3077    /// are separate because the header decides how every object after it is
3078    /// framed, so a caller has to know which it is expecting before the first
3079    /// byte is read.
3080    ///
3081    /// Objects come off the returned stream with
3082    /// [`FramedRecvStream::read_fetch_object`].
3083    ///
3084    /// FETCH_HEADER streams another accept set aside come first, in arrival
3085    /// order. A stream of any other type that arrives while this waits is
3086    /// set aside for [`accept_subgroup_stream`](Self::accept_subgroup_stream).
3087    pub async fn accept_fetch_stream(
3088        &self,
3089    ) -> Result<(AnyFetchHeader, FramedRecvStream), ConnectionError> {
3090        let mut framed = self.next_fetch_uni().await?;
3091        let sid = framed.stream_id();
3092        let header = framed.read_fetch_header().await?;
3093        self.emit(ClientEvent::StreamOpened {
3094            direction: Direction::Receive,
3095            stream_kind: StreamKind::Fetch,
3096            stream_id: sid,
3097        });
3098        self.emit(ClientEvent::FetchStreamHeader {
3099            stream_id: sid,
3100            direction: Direction::Receive,
3101            header: header.clone(),
3102        });
3103        // A fetch header goes out as `FetchStreamHeader`; `DataStreamHeader`
3104        // carries an `AnySubgroupHeader` and cannot express one. What
3105        // `accept_subgroup_stream` does beyond this - the forwarding-preference
3106        // note, the object measurement - is about a subgroup and has no
3107        // counterpart on a fetch stream.
3108        Ok((header, framed))
3109    }
3110
3111    /// Accept the next unidirectional stream as a **fill fetch stream**, new in
3112    /// draft-20 (Section 3.4).
3113    ///
3114    /// A fill fetch stream is framed exactly as a fetch response — a
3115    /// FETCH_HEADER and the fetch object records after it, read with
3116    /// [`FramedRecvStream::read_fetch_object`] — and differs only in what its
3117    /// Request ID names: the SUBSCRIBE (or the REQUEST_UPDATE, which travels
3118    /// under the same Request ID) that asked for the fill, rather than a FETCH.
3119    /// So this is [`accept_fetch_stream`](Self::accept_fetch_stream) with the
3120    /// attribution done: the endpoint is asked whether that request asked for a
3121    /// fill, the stream is counted against the subscription, and the event goes
3122    /// out under [`StreamKind::Fill`].
3123    ///
3124    /// # The object reader is already started
3125    ///
3126    /// Unlike [`accept_fetch_stream`](Self::accept_fetch_stream), the returned
3127    /// stream needs no
3128    /// [`begin_fetch_objects`](FramedRecvStream::begin_fetch_objects) call:
3129    /// objects can be read straight off it. A fetch stream cannot be started
3130    /// here because the Group Order lives on the FETCH the caller sent and
3131    /// nothing on this side holds it; a **fill** stream can, because the
3132    /// endpoint kept the order when the subscription asked for the fill — see
3133    /// [`Endpoint::fill_group_order`](crate::draft21::endpoint::Endpoint::fill_group_order)
3134    /// and [`fill::group_order`](crate::draft21::fill::group_order) for the
3135    /// three-step resolution Section 3.4 and Section 9.20.9 define.
3136    ///
3137    /// Doing it here rather than leaving it to the caller is the difference
3138    /// between an error and a wrong answer: a reader started in the wrong
3139    /// direction still parses every frame, and reports Group IDs that walk the
3140    /// wrong way. A caller that has since learned better restarts it by calling
3141    /// `begin_fetch_objects` itself before reading the first object.
3142    ///
3143    /// # What ends it, and what that does not do
3144    ///
3145    /// Section 3.4.1: a FIN means the whole fill range was delivered, and a
3146    /// reset means the fill failed — "Because there is no REQUEST_ERROR
3147    /// associated with a fill fetch stream, the publisher signals a fill
3148    /// failure by resetting the stream". Neither touches the subscription:
3149    /// "Resetting or cancelling a fill fetch stream, by either endpoint, does
3150    /// not affect the subscription, which continues to deliver objects using
3151    /// subscribe subgroups and datagrams." Tell the endpoint which happened
3152    /// with [`Endpoint::on_fill_stream_ended`](crate::draft21::endpoint::Endpoint::on_fill_stream_ended);
3153    /// a subscriber that wants to stop one early sends `STOP_SENDING` with
3154    /// [`FramedRecvStream::stop`], which Section 3.4.1 gives it outright.
3155    ///
3156    /// # Errors
3157    ///
3158    /// [`ConnectionError::Endpoint`] carrying
3159    /// [`EndpointError::UnrequestedFillStream`] when the header names a request
3160    /// that asked for no fill. Not fatal to the session — draft-21 states no
3161    /// rule for the case, and the stream is the only thing wrong.
3162    ///
3163    /// # Which stream it takes
3164    ///
3165    /// The same one [`accept_fetch_stream`](Self::accept_fetch_stream)
3166    /// would: a FETCH_HEADER stream another accept set aside, else the next
3167    /// one to arrive. Streams of any other type are set aside for
3168    /// [`accept_subgroup_stream`](Self::accept_subgroup_stream).
3169    pub async fn accept_fill_stream(
3170        &mut self,
3171    ) -> Result<(AnyFetchHeader, FramedRecvStream), ConnectionError> {
3172        let mut framed = self.next_fetch_uni().await?;
3173        let sid = framed.stream_id();
3174        let header = framed.read_fetch_header().await?;
3175        let request_id = VarInt::from_u64(header.request_id())
3176            .map_err(|e| ConnectionError::Codec(CodecError::VarInt(e)))?;
3177        self.endpoint.on_fill_stream_opened(request_id)?;
3178        // `on_fill_stream_opened` returned Ok, so the request asked for a fill
3179        // and the entry that answers this exists; the fallback is what a future
3180        // caller that split the two lookups would get, and it is the same
3181        // Section 9.20.9 default `fill::group_order` applies.
3182        let group_order =
3183            self.endpoint.fill_group_order(request_id).unwrap_or(GroupOrder::Ascending);
3184        framed.begin_fetch_objects(group_order);
3185        self.emit(ClientEvent::StreamOpened {
3186            direction: Direction::Receive,
3187            stream_kind: StreamKind::Fill,
3188            stream_id: sid,
3189        });
3190        self.emit(ClientEvent::FetchStreamHeader {
3191            stream_id: sid,
3192            direction: Direction::Receive,
3193            header: header.clone(),
3194        });
3195        Ok((header, framed))
3196    }
3197
3198    /// Take the oldest stream [`connect`](Self::connect) set aside, if any.
3199    ///
3200    /// Synchronous on purpose: the guard is dropped before the caller awaits,
3201    /// so the lock is never held across a suspension point. A poisoned lock
3202    /// is recovered rather than propagated — nothing here can leave the queue
3203    /// in a state a later reader could be misled by, since the only mutations
3204    /// are a `push_back` and a `pop_front`.
3205    fn take_deferred_uni(&self) -> Option<FramedRecvStream> {
3206        self.deferred_uni.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).pop_front()
3207    }
3208
3209    /// Take the oldest FETCH_HEADER stream set aside, if any. Synchronous for
3210    /// the reason [`take_deferred_uni`](Self::take_deferred_uni) is.
3211    fn take_deferred_fetch(&self) -> Option<FramedRecvStream> {
3212        self.deferred_fetch.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).pop_front()
3213    }
3214
3215    fn set_aside(queue: &Mutex<VecDeque<FramedRecvStream>>, framed: FramedRecvStream) {
3216        queue.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push_back(framed);
3217    }
3218
3219    /// The next stream that is not a FETCH_HEADER stream: a set-aside one
3220    /// first, then the transport's. FETCH_HEADER streams met on the way are
3221    /// set aside. A stream whose type cannot be read is returned, so that the
3222    /// header read reports why.
3223    async fn next_non_fetch_uni(&self) -> Result<FramedRecvStream, ConnectionError> {
3224        loop {
3225            let mut framed = match self.take_deferred_uni() {
3226                Some(framed) => framed,
3227                None => FramedRecvStream::new(self.transport.accept_uni().await?, self.draft),
3228            };
3229            match framed.peek_stream_type().await {
3230                Ok(FETCH_STREAM_TYPE) => Self::set_aside(&self.deferred_fetch, framed),
3231                _ => return Ok(framed),
3232            }
3233        }
3234    }
3235
3236    /// The next FETCH_HEADER stream: a set-aside one first, then the
3237    /// transport's. Streams of other types met on the way are set aside. A
3238    /// stream whose type cannot be read is returned, so that the header read
3239    /// reports why.
3240    async fn next_fetch_uni(&self) -> Result<FramedRecvStream, ConnectionError> {
3241        if let Some(framed) = self.take_deferred_fetch() {
3242            return Ok(framed);
3243        }
3244        loop {
3245            let mut framed = FramedRecvStream::new(self.transport.accept_uni().await?, self.draft);
3246            match framed.peek_stream_type().await {
3247                Ok(stream_type) if stream_type != FETCH_STREAM_TYPE => {
3248                    Self::set_aside(&self.deferred_uni, framed)
3249                }
3250                _ => return Ok(framed),
3251            }
3252        }
3253    }
3254
3255    /// How many unidirectional streams have been set aside and not yet handed
3256    /// back: those [`connect`](Self::connect) met before the control stream,
3257    /// and those an accept met that were for another accept.
3258    ///
3259    /// Zero for a peer that opened its control stream first and a caller
3260    /// that accepted each stream as the kind it is, which is the ordinary
3261    /// case.
3262    pub fn deferred_stream_count(&self) -> usize {
3263        self.deferred_uni.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).len()
3264            + self.deferred_fetch.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).len()
3265    }
3266
3267    /// Send an object via datagram.
3268    ///
3269    /// A header whose object status the framing cannot carry is refused rather
3270    /// than sent. A datagram writes a status field only when its type byte sets
3271    /// the STATUS bit, so a header carrying End of Group under a type byte
3272    /// without that bit would go out as an ordinary payload object with the
3273    /// marker missing — a datagram the peer cannot tell from one that never had
3274    /// a status. `AnyDatagramHeader::encode` answers that with
3275    /// `CodecError::InvalidField` and writes nothing, on every draft.
3276    pub fn send_datagram(
3277        &self,
3278        header: &AnyDatagramHeader,
3279        payload: &[u8],
3280    ) -> Result<(), ConnectionError> {
3281        let mut buf = Vec::new();
3282        header.encode(&mut buf)?;
3283        buf.extend_from_slice(payload);
3284        self.emit(ClientEvent::DatagramReceived {
3285            direction: Direction::Send,
3286            header: header.clone(),
3287            payload_len: payload.len(),
3288        });
3289        self.transport.send_datagram(bytes::Bytes::from(buf))?;
3290        Ok(())
3291    }
3292
3293    /// Receive a datagram and decode it whole.
3294    ///
3295    /// Errors with [`ConnectionError::EmptyDatagramProperties`] on a datagram
3296    /// with the PROPERTIES bit set and a Properties Length of 0, which
3297    /// [`Connection::close_for_data_stream`] closes the session over.
3298    ///
3299    /// Errors with [`ConnectionError::PropertiesOnNonNormalStatus`] on a
3300    /// draft-21 datagram carrying properties on a status other than Normal.
3301    /// Draft-21 Section 11.2.1 builds the datagram's Properties field out of
3302    /// the structure defined in Section 11.1.3, and that section answers the
3303    /// combination with a session close — the same rule the subgroup form
3304    /// obeys, on the same receive side.
3305    ///
3306    /// A payload after a status is returned as
3307    /// [`ConnectionError::PayloadOnStatusDatagram`], and the session stays open.
3308    /// The codec's `DatagramHeader::decode_object` then reads the whole
3309    /// datagram. A Prior Group ID Gap or Prior Object ID Gap fault, and a
3310    /// property block that does not parse, are returned as
3311    /// [`ConnectionError::MalformedTrackDatagram`], for
3312    /// [`Connection::requests_to_cancel`]; its other refusals as
3313    /// [`ConnectionError::Codec`].
3314    ///
3315    /// The event is emitted before the checks, so an observer of the client's
3316    /// event stream still sees the datagram that caused the error.
3317    pub async fn recv_datagram(&self) -> Result<(AnyDatagramHeader, Bytes), ConnectionError> {
3318        let data = self.transport.recv_datagram().await?;
3319        let mut cursor = &data[..];
3320        let header = AnyDatagramHeader::decode(self.draft, &mut cursor)?;
3321        let consumed = data.len() - cursor.len();
3322        let payload = data.slice(consumed..);
3323        self.emit(ClientEvent::DatagramReceived {
3324            direction: Direction::Receive,
3325            header: header.clone(),
3326            payload_len: payload.len(),
3327        });
3328        // Refutable only in a build with more than one draft enabled;
3329        // in a single-draft build `AnyDatagramHeader` has one variant.
3330        #[allow(irrefutable_let_patterns)]
3331        if let AnyDatagramHeader::Draft21(h) = &header {
3332            // draft-21 Section 11.2.1: "If an endpoint receives a datagram with the
3333            // PROPERTIES bit set and an Properties Length of 0, it MUST close
3334            // the session with a PROTOCOL_VIOLATION."
3335            if !h.properties_block_well_formed() {
3336                return Err(ConnectionError::EmptyDatagramProperties {
3337                    object_id: h.object_id.into_inner(),
3338                });
3339            }
3340            // draft-21 Section 11.2.1: "If an Object Datagram includes both the
3341            // STATUS bit and PROPERTIES bit, and the Object Status is not Normal
3342            // (0x0), the endpoint MUST close the session with a PROTOCOL_VIOLATION, because
3343            // only Normal Objects can have Properties."
3344            if !h.properties_permitted() {
3345                return Err(ConnectionError::PropertiesOnNonNormalStatus {
3346                    object_id: h.object_id.into_inner(),
3347                    properties_len: h.properties.len(),
3348                    status: h.status(),
3349                });
3350            }
3351            if !h.permits_payload() && !payload.is_empty() {
3352                return Err(ConnectionError::PayloadOnStatusDatagram {
3353                    object_id: h.object_id.into_inner(),
3354                    payload_len: payload.len(),
3355                    status: h.object_status,
3356                });
3357            }
3358            // The codec's whole-datagram read, for the rules a header alone
3359            // does not show. A gap fault is returned with the datagram's alias,
3360            // for `requests_to_cancel`.
3361            let whole =
3362                moqtap_codec::draft21::data_stream::DatagramHeader::decode_object(&mut &data[..]);
3363            match whole {
3364                Ok(_) => {}
3365                Err(
3366                    error @ (CodecError::MalformedTrack { .. }
3367                    | CodecError::MalformedObjectProperties { .. }),
3368                ) => {
3369                    return Err(ConnectionError::MalformedTrackDatagram {
3370                        track_alias: h.track_alias.into_inner(),
3371                        error,
3372                    });
3373                }
3374                Err(error) => return Err(ConnectionError::Codec(error)),
3375            }
3376        }
3377        // A datagram is a whole object, so the connection can measure it
3378        // without help from the caller. It cannot *answer* the condition,
3379        // though: the answer is a reset of a request stream the caller holds,
3380        // so both data paths report and neither withdraws - see
3381        // `Connection::requests_to_cancel`.
3382        let meta = header.meta();
3383        self.endpoint.note_received_object(
3384            meta.track_alias,
3385            ObjectLocation { group: meta.group_id, object: meta.object_id },
3386            object_role(meta.status),
3387        )?;
3388        Ok((header, payload))
3389    }
3390
3391    // -- Accessors --------------------------------------------------
3392
3393    /// Access the underlying endpoint state machine.
3394    pub fn endpoint(&self) -> &Endpoint {
3395        &self.endpoint
3396    }
3397
3398    /// Mutable access to the endpoint state machine.
3399    pub fn endpoint_mut(&mut self) -> &mut Endpoint {
3400        &mut self.endpoint
3401    }
3402
3403    /// The SETUP message the server answered the handshake with.
3404    ///
3405    /// `SERVER_SETUP` through draft-16, the server's half of the unified
3406    /// `SETUP` from draft-17. [`AnyControlMessage::fields`] renders it under
3407    /// this draft's own parameter names, in the order they arrived.
3408    pub fn server_setup(&self) -> &AnyControlMessage {
3409        &self.server_setup
3410    }
3411
3412    /// The framed wire bytes of [`Self::server_setup`], as they arrived.
3413    ///
3414    /// Kept beside the decoded form because the encoding is evidence the
3415    /// decoding discards: two relays sending the same parameter can still
3416    /// disagree on how wide a varint they wrote it in.
3417    pub fn server_setup_raw(&self) -> Option<&[u8]> {
3418        self.server_setup_raw.as_deref()
3419    }
3420
3421    /// Returns the draft version this connection is using.
3422    pub fn draft(&self) -> DraftVersion {
3423        self.draft
3424    }
3425
3426    /// Close the session on the wire when the endpoint says a violation is
3427    /// fatal to it, and hand the error back unchanged.
3428    ///
3429    /// [`EndpointError::session_error_code`] answers `Some` for exactly the
3430    /// errors draft-21 tells the receiver to close the session over, and the
3431    /// endpoint has already moved its own state machine to Closed by the time
3432    /// this runs. Without this step that move is purely internal: the local
3433    /// endpoint refuses to start anything new while the peer, which is the one
3434    /// that broke the rule, sees a session that is still open and goes on
3435    /// sending. "MUST close the session with a PROTOCOL_VIOLATION" is a
3436    /// statement about the wire, so it takes a CONNECTION_CLOSE to satisfy it.
3437    ///
3438    /// The reason phrase is the error's own `Display` text, which names the
3439    /// message and the rule rather than repeating the numeric code the close
3440    /// already carries.
3441    ///
3442    /// Errors that answer `None` are recoverable and nothing is sent.
3443    fn close_for(&self, err: &EndpointError) {
3444        if let Some(code) = err.session_error_code() {
3445            // QUIC application error codes are 62-bit; every code in this
3446            // registry is far below `u32::MAX`, and saturating rather than
3447            // truncating means a future code that is not could never be
3448            // reported as a different, assigned one.
3449            let wire_code = u32::try_from(code.as_u64()).unwrap_or(u32::MAX);
3450            self.close(wire_code, err.to_string().as_bytes());
3451        }
3452    }
3453
3454    /// [`close_for`](Self::close_for), then the error unchanged, for the
3455    /// common case where the endpoint's error is also what the caller returns.
3456    fn close_if_session_fatal(&self, err: EndpointError) -> ConnectionError {
3457        self.close_for(&err);
3458        ConnectionError::Endpoint(err)
3459    }
3460
3461    /// Which of this draft's *own* `ConnectionError` variants this error is,
3462    /// and which kind of thing it says.
3463    ///
3464    /// The ten every draft carries answer `None` here: [`AnyConnectionError`]
3465    /// classifies those itself, once, and never asks a draft about them. What
3466    /// is left splits two ways, and the split is the reason this function
3467    /// exists — before it, both halves reached a caller as a sentence and read
3468    /// exactly alike. A [`LocalRefusal`] is this endpoint declining to write
3469    /// something, so nothing reached the wire and no relay is implicated; a
3470    /// [`PeerViolation`] is a peer having done something draft-21 forbids, and
3471    /// carries the session error code draft-21's own text answers it with.
3472    ///
3473    /// Matched exhaustively, with no wildcard arm and deliberately so: a
3474    /// variant added to this draft's error type has to arrive here as a compile
3475    /// error, beside the doc comment quoting the sentence it enforces, rather
3476    /// than as a silent [`ErrorCause::Unclassified`] in the facade.
3477    ///
3478    /// [`AnyConnectionError`]: crate::dispatch::AnyConnectionError
3479    /// [`ErrorCause::Unclassified`]: crate::dispatch::ErrorCause::Unclassified
3480    /// [`LocalRefusal`]: crate::above_codec_rules::DraftSpecificCause::LocalRefusal
3481    /// [`PeerViolation`]: crate::above_codec_rules::DraftSpecificCause::PeerViolation
3482    pub fn draft_specific_cause(
3483        err: &ConnectionError,
3484    ) -> Option<crate::above_codec_rules::DraftSpecificCause> {
3485        use crate::above_codec_rules::{AboveCodecRule, DraftSpecificCause};
3486        use moqtap_codec::draft21::error_codes::SessionErrorCode;
3487
3488        match err {
3489            ConnectionError::Endpoint(_)
3490            | ConnectionError::Codec(_)
3491            | ConnectionError::Transport(_)
3492            | ConnectionError::VarInt(_)
3493            | ConnectionError::NoControlStream
3494            | ConnectionError::UnexpectedEnd
3495            | ConnectionError::StreamFinished
3496            | ConnectionError::InvalidAddress(_)
3497            | ConnectionError::TlsConfig(_)
3498            | ConnectionError::DataStreamState(_) => None,
3499            // This build decoding a message and then failing to narrow it to
3500            // its own draft. Nothing reached the wire and no peer is
3501            // implicated, which is the whole reason it is not
3502            // `ConnectionError::Codec`: under that name it would carry
3503            // `Some(PROTOCOL_VIOLATION)` out of `codec_session_error_code` and
3504            // publish a relay for this build's defect. See the variant's own
3505            // doc.
3506            ConnectionError::ControlMessageNarrowing => {
3507                Some(crate::above_codec_rules::DraftSpecificCause::LocalRefusal)
3508            }
3509            // Section 11.1.3 states the rule and names the code in the same
3510            // sentence. The codec refuses such an Object only as a bare
3511            // `InvalidField`, so this layer is the one that names the rule,
3512            // and `close_for_data_stream` performs the close by
3513            // reading this same answer.
3514            ConnectionError::PropertiesOnNonNormalStatus { .. } => {
3515                Some(DraftSpecificCause::PeerViolation {
3516                    rule: AboveCodecRule::PropertiesOnNonNormalStatus,
3517                    close: Some(SessionErrorCode::ProtocolViolation.as_u64()),
3518                })
3519            }
3520            // draft-21 Section 11.2.1 answers it with a close, which this variant
3521            // names. See the variant's own doc.
3522            ConnectionError::EmptyDatagramProperties { .. } => Some(DraftSpecificCause::Codec {
3523                error: CodecError::InvalidField,
3524                close: Some(SessionErrorCode::ProtocolViolation.as_u64()),
3525            }),
3526            // The codec's refusal, carried with the alias its error does
3527            // not name. draft-21 Section 12.1 answers a Malformed Track by
3528            // cancelling requests, and `codec_session_error_code` names no
3529            // close for it.
3530            ConnectionError::MalformedTrackDatagram { error, .. } => {
3531                Some(DraftSpecificCause::Codec {
3532                    close: Self::codec_session_error_code(error).map(|code| code.as_u64()),
3533                    error: error.clone(),
3534                })
3535            }
3536            // Section 11.1.2 states this one as a property of a conforming
3537            // Object rather than as one of the cases a draft answers with a
3538            // close. That phrase carries no quotation marks and must not: it
3539            // is this crate naming a shape of drafting, and the marks would
3540            // file the words on the section named right beside them — which is
3541            // the one section here that pointedly does not carry them. The
3542            // datagram is refused and the session is left running. `None` is
3543            // that reading, and it is what keeps a relay from being published
3544            // for a rule its draft attaches no consequence to.
3545            ConnectionError::PayloadOnStatusDatagram { .. } => {
3546                Some(DraftSpecificCause::PeerViolation {
3547                    rule: AboveCodecRule::PayloadOnStatusDatagram,
3548                    close: None,
3549                })
3550            }
3551            // Section 6.3: "Bidirectional streams MUST NOT begin with any
3552            // other message type unless negotiated. If they do, the peer MUST
3553            // close the Session with a PROTOCOL_VIOLATION." The session has
3554            // already been closed on the wire by the time this is returned, so
3555            // the code is carried here for a caller to read which rule was
3556            // answered, not for it to answer one again.
3557            ConnectionError::NonRequestOnRequestStream(_) => {
3558                Some(DraftSpecificCause::PeerViolation {
3559                    rule: AboveCodecRule::BidiStreamOpener,
3560                    close: Some(SessionErrorCode::ProtocolViolation.as_u64()),
3561                })
3562            }
3563            // Three ways of handing this endpoint a message it will not write,
3564            // and one answer: nothing reached the wire, so nothing here is
3565            // evidence about a peer. Two are messages put on the control stream
3566            // that belong on a request stream of their own; the third is a
3567            // `respond_*` helper pointed at a request this endpoint opened,
3568            // which only the endpoint a request was opened *toward* may answer.
3569            ConnectionError::RequestOnControlStream(_)
3570            | ConnectionError::RequestStreamMessageOnControlStream(_)
3571            | ConnectionError::RespondedToOwnRequest(_) => Some(DraftSpecificCause::LocalRefusal),
3572            // Section 6.4.2.2 forbids a FIN before the response a request type
3573            // requires, and before PUBLISH_DONE on an established
3574            // subscription. Both are raised when *this* endpoint asks for the
3575            // FIN, so both are refusals rather than findings: the draft's rule
3576            // is being kept, not broken.
3577            ConnectionError::FinBeforeResponse(_) | ConnectionError::FinBeforePublishDone(_) => {
3578                Some(DraftSpecificCause::LocalRefusal)
3579            }
3580        }
3581    }
3582
3583    /// The code to close the session with when a control message could not be
3584    /// decoded because the peer broke a rule draft-21 answers with a close.
3585    ///
3586    /// Every variant listed here comes from a sentence in the draft that names
3587    /// the consequence: the reason phrase and GOAWAY URI maxima (Section 8.5
3588    /// and Section 9.2), the KVP value maximum and the delta-encoded
3589    /// type overflow (Section 8.3), the duplicate-parameter rule (Section
3590    /// 9.20), the Track Namespace field, count and length rules
3591    /// (Section 8.7), and the Object ID delta wrap (Section 11.3.1). Each of
3592    /// those reads "MUST close the session with a PROTOCOL_VIOLATION".
3593    ///
3594    /// The Object ID wrap is the one that arrives here from a data stream
3595    /// rather than a control message, and it is drafts 18, 19 and 20 only:
3596    /// "The Object ID Delta + 1 is added to the previous Object ID in the
3597    /// Subgroup stream if there was one... If the resulting Object ID would be
3598    /// greater than 2^64 - 1, the endpoint MUST close the session with a
3599    /// PROTOCOL_VIOLATION." Draft-17 describes the same arithmetic and states
3600    /// no consequence for overflowing it, so its connection deliberately leaves
3601    /// the wrap off this list and treats it as a decode failure alone.
3602    ///
3603    /// One more rule reaches this table without naming a code: "An endpoint
3604    /// that receives an unknown message type MUST close the session", stated in
3605    /// those words by all the drafts. Protocol Violation is what carries
3606    /// it, as it does on every draft below this one.
3607    ///
3608    /// `None` for everything else, including [`CodecError::InvalidField`]. That
3609    /// variant is shared by a dozen unrelated malformations, only some of which
3610    /// the draft answers with a close, so treating it as fatal would close
3611    /// sessions the draft does not ask to be closed. Splitting it is the way to
3612    /// bring the rest of those rules under this function; widening the match is
3613    /// not — the Object ID wrap is answerable here because it has a variant of
3614    /// its own rather than being one more reading of `InvalidField`.
3615    pub fn codec_session_error_code(
3616        err: &CodecError,
3617    ) -> Option<moqtap_codec::draft21::error_codes::SessionErrorCode> {
3618        use moqtap_codec::draft21::error_codes::SessionErrorCode;
3619        use moqtap_codec::kvp::KvpError;
3620        match err {
3621            // The declared Length disagreeing with the fields, which every
3622            // draft answers with a close. Drafts 07 through 10 name no code for
3623            // it, so it takes the one their other unnamed rules take.
3624            // **Draft-21 has no Filter Type.** Drafts 15 through 19 state that
3625            // rule in a Section 5.1.2 that defines a Filter Type field;
3626            // draft-21's Section 9.20.10 defines the LOCATION_FILTER parameter
3627            // instead, which finds its optional fields by length and has no
3628            // type discriminator at all. The only occurrence of the words in
3629            // the whole draft is prose in Section 3.3.3 about combining
3630            // filters.
3631            //
3632            // So this arm cannot fire: draft-21's message reader raises the
3633            // error nowhere and has nothing to raise it from. It stays because
3634            // `CodecError` is shared across every draft and is not
3635            // `#[non_exhaustive]`, which is the same reason the Fetch Type arm
3636            // below stays.
3637            //
3638            // `CodecRule::InvalidFilterType` stops its runs at draft-19 for
3639            // this reason, so a consumer that did somehow reach this close
3640            // would find no sentence to publish and would name nobody.
3641            CodecError::InvalidFilterType(_) => Some(SessionErrorCode::ProtocolViolation),
3642            // An AbsoluteRange filter whose End Group Delta carries the range
3643            // past the end of the number space, Section 9.20.10: "If StartGroup +
3644            // EndGroupDelta exceeds 2^64 - 1, the endpoint MUST close the
3645            // session with a PROTOCOL_VIOLATION."
3646            //
3647            // Draft-21's own wording. Drafts 18 and 19 state the rule as two
3648            // sentences, where the consequence follows a clause supplying the
3649            // antecedent for *the resulting Group ID*; draft-21 states it as
3650            // the one self-contained sentence above, naming its operands.
3651            // Drafts 18 and 19 put it in their Section 5.1.2 and draft-21 in
3652            // Section 9.20.10, and all three name
3653            // PROTOCOL_VIOLATION, so a sentence borrowed from a neighbour is
3654            // the shape a reader cannot tell from a transcription — which is
3655            // why `CodecRule` keeps the two wordings as separate runs, so that
3656            // neither draft is published with the other's words.
3657            //
3658            // New in draft-18; draft-17, which introduced the delta, states no
3659            // such sentence.
3660            CodecError::FilterEndGroupOverflow { .. } => {
3661                Some(SessionErrorCode::ProtocolViolation)
3662            }
3663            // Draft-21 has no Fetch Type: Section 9.11 has no such field, no
3664            // variant structures and no registry for it, so this draft's
3665            // FETCH decoder cannot produce this error. The arm stays because
3666            // `CodecError` is shared across every draft and is not
3667            // `#[non_exhaustive]`, and because the answer would not change if
3668            // it could: a discriminator a reader cannot name is a message it
3669            // cannot find the end of, which is the PROTOCOL_VIOLATION the arms
3670            // around it carry.
3671            CodecError::InvalidFetchType(_) => Some(SessionErrorCode::ProtocolViolation),
3672            CodecError::ControlMessageLengthMismatch { .. } => {
3673                Some(SessionErrorCode::ProtocolViolation)
3674            }
3675            CodecError::KeyDeltaOverflow(..)
3676            | CodecError::DuplicateParameter(_)
3677            | CodecError::TrackNameTooLong
3678            | CodecError::InvalidNamespaceTupleSize(_)
3679            | CodecError::ReasonPhraseTooLong
3680            | CodecError::GoAwayUriTooLong
3681            | CodecError::UnknownMessageType(_)
3682            | CodecError::Kvp(KvpError::ValueTooLong(_))
3683            | CodecError::EmptyNamespaceField
3684            | CodecError::ObjectIdOverflow(..) => Some(SessionErrorCode::ProtocolViolation),
3685            // An unknown data-plane type. Drafts 17 and later split the sentence
3686            // in two: Section 6.4.1 for streams, Section 11 for datagrams, both
3687            // ending "MUST close the session" and neither naming a code, so both
3688            // take the one this draft's other unnamed rules take.
3689            // A Message Parameter whose value is outside the range its type
3690            // allows: FORWARD in Section 9.20.19 and GROUP_ORDER in Section 9.20.9.
3691            // Each states that a receiver "MUST close the session with
3692            // PROTOCOL_VIOLATION".
3693            CodecError::ParameterValueOutOfRange { .. } => {
3694                Some(SessionErrorCode::ProtocolViolation)
3695            }
3696            // A Track Extension or Track Property whose value is outside the
3697            // range its type allows: DEFAULT_PUBLISHER_GROUP_ORDER in Section 10.5
3698            // and DYNAMIC_GROUPS in Section 10.6.
3699            // Each states that a receiver "MUST close the session with
3700            // PROTOCOL_VIOLATION".
3701            //
3702            // A separate arm from the parameter rule above because the two
3703            // registries are separate: 0x22 is GROUP_ORDER as a parameter and
3704            // DEFAULT_PUBLISHER_GROUP_ORDER as a Track Property, and a log that
3705            // named only the number would not say which.
3706            CodecError::TrackPropertyValueOutOfRange { .. } => {
3707                Some(SessionErrorCode::ProtocolViolation)
3708            }
3709            CodecError::UnknownStreamType(_) | CodecError::UnknownDatagramType(_) => {
3710                Some(SessionErrorCode::ProtocolViolation)
3711            }
3712            // A Type inside a form this draft defines but on a list it names as
3713            // invalid: Section 11.3.1 for a subgroup header whose SUBGROUP_ID_MODE
3714            // is the reserved 0b11, Section 11.2.1 for a datagram asking to be both
3715            // an object status and an end-of-group marker. Unlike the rule above,
3716            // these two name their code outright.
3717            CodecError::InvalidStreamTypeValue { .. }
3718            | CodecError::InvalidDatagramTypeValue { .. } => {
3719                Some(SessionErrorCode::ProtocolViolation)
3720            }
3721            // A key-value pair whose value is not the serialization its own
3722            // Type defines, Section 8.3: "If a receiver understands a Type,
3723            // and the following Value or Length/Value does not match the
3724            // serialization defined by that Type, the receiver MUST close the
3725            // session with error code KEY_VALUE_FORMATTING_ERROR."
3726            //
3727            // Section 8.9 states the same answer for the one structure this
3728            // draft spells out: "If the Token structure cannot be decoded, the
3729            // receiver MUST close the Session with KEY_VALUE_FORMATTING_ERROR."
3730            //
3731            // The one rule in this table that names a code other than Protocol
3732            // Violation.
3733            CodecError::KeyValueFormatting { .. }
3734            // A filter parameter whose value is not a filter reaches the same
3735            // sentence. Drafts 15 and 16 answered it with PROTOCOL_VIOLATION
3736            // instead, on the strength of a sentence of the parameter's own that
3737            // this draft dropped; what remains is the general rule above, so the
3738            // code changed with it.
3739            | CodecError::SubscriptionFilterMalformed { .. } => {
3740                Some(SessionErrorCode::KeyValueFormattingError)
3741            }
3742            // A Message Parameter whose type this draft does not define, Section
3743            // 9.20: "All Message Parameters MUST be defined in the negotiated
3744            // version of MOQT or negotiated via Setup Options. An endpoint that
3745            // receives an unknown Message Parameter MUST close the session with
3746            // PROTOCOL_VIOLATION."
3747            //
3748            // One namespace only. This draft also says a receiver ignores an
3749            // unrecognised Setup Option, so an unknown type in a SETUP is carried and
3750            // the codec never raises this for one.
3751            CodecError::UnknownMessageParameter(_) => Some(SessionErrorCode::ProtocolViolation),
3752            // A Message Parameter in a message type its own definition does not
3753            // name, Section 9.20.1: "Each Message Parameter definition indicates
3754            // the message types in which it can appear. If it appears in some
3755            // other type of message, the receiving endpoint MUST close the
3756            // connection with a PROTOCOL_VIOLATION."
3757            //
3758            // Draft-16 and every draft before it end that same sentence "it MUST
3759            // be ignored", so this is a rule whose answer reverses rather than
3760            // one that arrives.
3761            CodecError::ParameterOutOfScope { .. } => Some(SessionErrorCode::ProtocolViolation),
3762            // Everything this draft does not answer, named rather than swept up
3763            // by a wildcard. The arm is exhaustive deliberately: a new
3764            // `CodecError` variant will not compile until it has been placed on
3765            // one side or the other, on this draft, which is the decision a `_`
3766            // arm makes silently and invisibly on every draft at once.
3767            //
3768            // Adding one variant to `CodecError` produces one `E0004` per
3769            // draft, each naming the variant that has nowhere to go. That is
3770            // the whole mechanism.
3771            //
3772            // The nesting stops at `VarInt`, whose variants report how the bytes
3773            // ran out rather than a rule an endpoint states, so there is nothing
3774            // in it for a draft to answer. `Kvp` is spelled out because it does
3775            // carry one.
3776            // Neither field exists from draft-15 on. Forwarding became the
3777            // FORWARD parameter, which carries the same rule in a different
3778            // shape and is answered above under its own variant; Content Exists
3779            // became the presence or absence of a LARGEST_OBJECT parameter.
3780            CodecError::InvalidForward(_)
3781            | CodecError::InvalidContentExists(_)
3782            | CodecError::UnexpectedEnd
3783            | CodecError::MessageTooLong(_)
3784            | CodecError::VarInt(_)
3785            | CodecError::InvalidField
3786            | CodecError::InvalidRange(..)
3787            | CodecError::ParameterLengthMismatch(_)
3788            | CodecError::EndOfTrackObjectId(_)
3789            | CodecError::ParametersOutOfOrder(..)
3790            | CodecError::ExtensionsOnNonExistentObject(_)
3791            | CodecError::InvalidRequiredRequestIdDelta(..)
3792            // The object payload rule, Section 11.1.2, which draft-21 states
3793            // against a registry rather than against zero: "An Object MUST have
3794            // an empty payload unless its Object Status value is registered as
3795            // permitting a payload in the Object Status registry (Section 16.9).
3796            // Of the values defined in this document, only Normal (0x0) permits
3797            // a payload." Still a MUST on the sender with no receiver action
3798            // named, so the answer is the one every draft before it gets.
3799            | CodecError::PayloadNotPermitted { .. }
3800            // A property block that does not parse makes the Track malformed,
3801            // Section 10.7.
3802            | CodecError::MalformedObjectProperties { .. }
3803            // A Malformed Track (Section 12.1) costs the track and not the
3804            // session.
3805            | CodecError::MalformedTrack { .. }
3806            // Raised only by the draft-23 codec.
3807            | CodecError::ControlMessageExceedsLimit { .. }
3808            | CodecError::MissingErrorDetail { .. }
3809            | CodecError::MalformedErrorDetail { .. }
3810            | CodecError::TokenAliasInSetup { .. }
3811            | CodecError::EmptyTrackName
3812            | CodecError::MalformedAuthToken { .. }
3813            | CodecError::TrackPropertiesNotPermitted
3814            | CodecError::DeltaDecodingOverflow { .. }
3815            | CodecError::MalformedObject { .. }
3816            | CodecError::UnknownObjectStatus(_)
3817            | CodecError::UnsupportedDraft(_)
3818            | CodecError::Kvp(
3819                KvpError::MissingLength | KvpError::UnexpectedEnd | KvpError::VarInt(_),
3820            ) => None,
3821        }
3822    }
3823
3824    /// Close the session on the wire when a decode failure is one draft-21
3825    /// answers with a close, and hand the error back unchanged.
3826    ///
3827    /// The codec's counterpart to
3828    /// [`close_if_session_fatal`](Self::close_if_session_fatal). Without it
3829    /// every bound the decoder enforces would stop at *this endpoint refused the
3830    /// frame* while the peer, which is the one that broke the rule, saw a
3831    /// session that was still open and went on sending. "MUST close the session
3832    /// with a PROTOCOL_VIOLATION" is a statement about the wire.
3833    fn close_for_codec(&self, err: ConnectionError) -> ConnectionError {
3834        if let ConnectionError::Codec(inner) = &err {
3835            if let Some(code) = Self::codec_session_error_code(inner) {
3836                // QUIC application error codes are 62-bit; every code in this
3837                // registry is far below `u32::MAX`, and saturating rather than
3838                // truncating means a future code that is not could never be
3839                // reported as a different, assigned one.
3840                let wire_code = u32::try_from(code.as_u64()).unwrap_or(u32::MAX);
3841                self.close(wire_code, inner.to_string().as_bytes());
3842            }
3843        }
3844        err
3845    }
3846
3847    /// Name every request whose stream the caller must reset, for a track a
3848    /// data path has just found malformed.
3849    ///
3850    /// Section 12.1 answers its whole list of conditions at once: "it MUST
3851    /// cancel any corresponding subscription or fetches for that Track from
3852    /// that publisher". On this draft cancelling a request is a transport
3853    /// operation rather than a message — Section 6.4.2.3: "Implementations cancel a request by
3854    /// abruptly terminating any directions of the stream that are still open,
3855    /// using RESET_STREAM for a direction they are sending and STOP_SENDING for
3856    /// a direction they are receiving."
3857    ///
3858    /// **No RFC 2119 keyword on this draft.** Drafts 17 and 18 say
3859    /// implementations SHOULD cancel this way; draft-21 states it as what
3860    /// cancelling *is*, and adds the case of an endpoint that has already sent
3861    /// a FIN and sends STOP_SENDING alone.
3862    ///
3863    /// # Why this returns ids instead of doing it
3864    ///
3865    /// Because the streams are the caller's. Every request on this draft lives
3866    /// at the front of a bidirectional stream of its own, and
3867    /// [`Connection::recv_on_request_stream`] hands that stream back as a
3868    /// [`RequestStream`]. There is no handle here to reset. So the connection
3869    /// does the half it can — note the track, and work out which requests
3870    /// receive it — and the caller passes each id to
3871    /// [`Connection::cancel_request_stream`], which resets the stream *and*
3872    /// moves the endpoint's record.
3873    ///
3874    /// **This is the one place in this crate where the two halves of an answer
3875    /// are split across the API boundary**, and it is the draft that splits
3876    /// them: drafts 12 through 16 answer with a control message, which the
3877    /// connection owns, so `withdraw_for_data_stream` there does the whole
3878    /// thing.
3879    ///
3880    /// # Both data paths come here
3881    ///
3882    /// Unlike the drafts that answer with a message, where a datagram is read
3883    /// through the connection and answers itself. Here neither path can, for
3884    /// the same reason, so there is one entry point rather than two. Pass it
3885    /// whatever error a read returned; anything that is not this condition
3886    /// gives back an empty list.
3887    ///
3888    /// Empty is not "the track was fine" — it is also what an alias no live
3889    /// binding names gives, and what a track this endpoint only publishes
3890    /// gives.
3891    pub fn requests_to_cancel(&self, err: &ConnectionError) -> Vec<VarInt> {
3892        match err {
3893            ConnectionError::Endpoint(EndpointError::ObjectPastFinalObject { alias, .. }) => {
3894                self.endpoint.requests_for_malformed_track(
3895                    *alias,
3896                    MalformedTrackCondition::ObjectPastFinalObject,
3897                )
3898            }
3899            ConnectionError::MalformedTrackDatagram { track_alias, error } => {
3900                malformed_track_condition(error).map_or_else(Vec::new, |condition| {
3901                    self.endpoint.requests_for_malformed_track(*track_alias, condition)
3902                })
3903            }
3904            _ => Vec::new(),
3905        }
3906    }
3907
3908    /// [`Connection::requests_to_cancel`] for an error read from the subgroup
3909    /// stream `header` opened, which also names the requests to cancel over
3910    /// the [`CodecError::MalformedTrack`] that
3911    /// [`FramedRecvStream::read_subgroup_object`] returns for a Prior Group ID
3912    /// Gap or Prior Object ID Gap fault (draft-21 Section 10.8,
3913    /// draft-21 Section 10.9), and over the
3914    /// [`CodecError::MalformedObjectProperties`] it returns for a property block
3915    /// that does not parse (draft-21 Section 10.7). Those errors name no track, so
3916    /// the header supplies its alias.
3917    ///
3918    /// draft-21 Section 12.1: "When a subscriber detects a Malformed Track, it
3919    /// MUST cancel any corresponding subscription or fetches for that Track
3920    /// from that publisher (see Section 6.4.2.3)". The session stays open.
3921    pub fn requests_to_cancel_for_subgroup_stream(
3922        &self,
3923        header: &AnySubgroupHeader,
3924        err: &ConnectionError,
3925    ) -> Vec<VarInt> {
3926        if let ConnectionError::Codec(codec) = err {
3927            if let Some(condition) = malformed_track_condition(codec) {
3928                return self.endpoint.requests_for_malformed_track(header.track_alias(), condition);
3929            }
3930        }
3931        self.requests_to_cancel(err)
3932    }
3933
3934    /// [`Connection::requests_to_cancel`] for an error read from the fetch stream
3935    /// `header` opened, which also names the requests to cancel over the
3936    /// [`CodecError::MalformedTrack`] that
3937    /// [`FramedRecvStream::read_fetch_object`] returns for a Prior Group ID
3938    /// Gap or Prior Object ID Gap fault (draft-21 Section 10.8,
3939    /// draft-21 Section 10.9), and over the
3940    /// [`CodecError::MalformedObjectProperties`] it returns for a property block
3941    /// that does not parse (draft-21 Section 10.7). Those errors name no track, so
3942    /// the track the FETCH under the header's Request ID asked for is the one.
3943    ///
3944    /// draft-21 Section 12.1: "When a subscriber detects a Malformed Track, it
3945    /// MUST cancel any corresponding subscription or fetches for that Track
3946    /// from that publisher (see Section 6.4.2.3)". The session stays open.
3947    pub fn requests_to_cancel_for_fetch_stream(
3948        &self,
3949        header: &AnyFetchHeader,
3950        err: &ConnectionError,
3951    ) -> Vec<VarInt> {
3952        if let ConnectionError::Codec(codec) = err {
3953            if let Some(condition) = malformed_track_condition(codec) {
3954                return self
3955                    .endpoint
3956                    .requests_for_malformed_fetch_track(header.request_id(), condition);
3957            }
3958        }
3959        self.requests_to_cancel(err)
3960    }
3961
3962    /// Close the session when a failure raised while reading a *data* stream is
3963    /// one draft-21 answers with a close. Reports whether it closed.
3964    ///
3965    /// [`recv_control`](Self::recv_control) does this for itself, because it
3966    /// owns both the stream and the connection. A data stream does not:
3967    /// [`accept_subgroup_stream`](Self::accept_subgroup_stream) hands the caller
3968    /// a [`FramedRecvStream`], which holds no connection and so cannot close
3969    /// one, and the reads that raise these failures happen there. The caller is
3970    /// the only party holding both halves, which is what this is for:
3971    ///
3972    /// ```no_run
3973    /// # async fn f(conn: &moqtap_client::draft21::connection::Connection,
3974    /// #            framed: &mut moqtap_client::draft21::connection::FramedRecvStream)
3975    /// # -> Result<(), Box<dyn std::error::Error>> {
3976    /// if let Err(err) = framed.read_subgroup_object().await {
3977    ///     conn.close_for_data_stream(&err);
3978    ///     return Err(err.into());
3979    /// }
3980    /// # Ok(()) }
3981    /// ```
3982    ///
3983    /// Splitting it this way rather than closing inside the reader keeps a
3984    /// caller that is deliberately permissive — a tool reproducing a capture,
3985    /// say — able to read a violating stream and report it without tearing the
3986    /// session down. The rule is stated at endpoints, and this is where an
3987    /// endpoint decides it is one.
3988    ///
3989    /// Only [`ConnectionError::Codec`] failures are matched, against the same
3990    /// `codec_session_error_code` table the
3991    /// control path uses, so a rule is answered with one code whichever stream
3992    /// carried it. The Object ID delta wrap of Section 11.3.1 is the entry that
3993    /// can only arrive this way.
3994    pub fn close_for_data_stream(&self, err: &ConnectionError) -> bool {
3995        use crate::above_codec_rules::DraftSpecificCause;
3996
3997        match err {
3998            ConnectionError::Codec(inner) => {
3999                let Some(code) = Self::codec_session_error_code(inner) else { return false };
4000                let wire_code = u32::try_from(code.as_u64()).unwrap_or(u32::MAX);
4001                self.close(wire_code, inner.to_string().as_bytes());
4002                true
4003            }
4004            // Not a `Codec` failure: the codec refuses such an Object as a bare
4005            // `InvalidField`, which `read_subgroup_object` narrows to this
4006            // crate's own variant, so the mapping table above never sees it.
4007            //
4008            // The code comes from `draft_specific_cause` rather than from a
4009            // constant here, so this draft's reading of its own sentence is
4010            // written down once and a caller who reads the error as a value
4011            // sees the same code the peer was sent.
4012            ConnectionError::PropertiesOnNonNormalStatus { .. } => {
4013                let Some(DraftSpecificCause::PeerViolation { close: Some(code), .. }) =
4014                    Self::draft_specific_cause(err)
4015                else {
4016                    return false;
4017                };
4018                // Saturate rather than truncate, so a future code above
4019                // `u32::MAX` is never reported as a different assigned one.
4020                self.close(u32::try_from(code).unwrap_or(u32::MAX), err.to_string().as_bytes());
4021                true
4022            }
4023            // Not a `Codec` failure: the codec refuses the datagram as a bare
4024            // `InvalidField`, which `recv_datagram` names, so the code comes
4025            // from `draft_specific_cause`.
4026            ConnectionError::EmptyDatagramProperties { .. } => {
4027                let Some(DraftSpecificCause::Codec { close: Some(code), .. }) =
4028                    Self::draft_specific_cause(err)
4029                else {
4030                    return false;
4031                };
4032                self.close(u32::try_from(code).unwrap_or(u32::MAX), err.to_string().as_bytes());
4033                true
4034            }
4035            _ => false,
4036        }
4037    }
4038
4039    /// Close the connection.
4040    pub fn close(&self, code: u32, reason: &[u8]) {
4041        self.emit(ClientEvent::Closed { code, reason: reason.to_vec() });
4042        self.transport.close(code, reason);
4043    }
4044}
4045
4046/// The Malformed Track condition a codec refusal on a data path is, on this
4047/// draft, or `None` for a refusal that is not one.
4048fn malformed_track_condition(err: &CodecError) -> Option<MalformedTrackCondition> {
4049    match err {
4050        CodecError::MalformedTrack { .. } => Some(MalformedTrackCondition::PriorGap),
4051        // draft-21 Section 10.7: "A Key-Value-Pair cannot be parsed."
4052        CodecError::MalformedObjectProperties { .. } => {
4053            Some(MalformedTrackCondition::MalformedPropertyBlock)
4054        }
4055        _ => None,
4056    }
4057}
4058
4059#[cfg(test)]
4060mod tests {
4061    use super::*;
4062
4063    /// This build failing to narrow a message it decoded is never a finding
4064    /// about the peer.
4065    ///
4066    /// The arm that raises `ControlMessageNarrowing` is unreachable — this
4067    /// draft's decoder can only hand back this draft's variant — and nothing
4068    /// pins that. What is pinned here is the half that matters.
4069    /// `CodecError::UnknownMessageType(0)` is what the arm must not raise:
4070    /// `codec_session_error_code` answers it `Some(PROTOCOL_VIOLATION)` on
4071    /// every draft in range, so the day the narrowing failed a conformance
4072    /// probe would publish a relay for sending a control message type this
4073    /// draft does not assign — with `0x00` attached as the codepoint that
4074    /// proved it, which is an accusation better evidenced than any real one
4075    /// this build makes. The section stating that rule is numbered differently
4076    /// on every draft, and the point does not turn on the number.
4077    #[test]
4078    fn a_message_this_build_could_not_narrow_names_nobody() {
4079        use crate::dispatch::{AnyConnectionError, ErrorCause};
4080
4081        let err: AnyConnectionError = ConnectionError::ControlMessageNarrowing.into();
4082        assert!(err.is_local(), "a narrowing this build could not do is this build's");
4083        assert_eq!(
4084            err.cause(),
4085            &ErrorCause::Facade,
4086            "nothing reached the wire, so there is no rule and no close code to read"
4087        );
4088    }
4089
4090    /// Draft-21 uses MoQT's variable-length integer, whose length is the
4091    /// number of leading 1 bits in the first byte, not RFC 9000's two-bit
4092    /// prefix. Control framing measures the type field with it before any
4093    /// bytes past the first have arrived.
4094    #[test]
4095    fn varint_len_follows_the_moqt_encoding() {
4096        let draft = DraftVersion::Draft21;
4097        assert_eq!(draft.varint_len(0x00), 1);
4098        assert_eq!(draft.varint_len(0x7F), 1);
4099        assert_eq!(draft.varint_len(0x80), 2);
4100        assert_eq!(draft.varint_len(0xBF), 2);
4101        assert_eq!(draft.varint_len(0xC0), 3);
4102        assert_eq!(draft.varint_len(0xFF), 9);
4103        // SETUP's type id, 0x2F00, is two bytes here and four under RFC 9000.
4104        assert_eq!(draft.varint_len(0xAF), 2);
4105    }
4106
4107    #[test]
4108    fn client_config_alpn_quic_draft21() {
4109        let config = ClientConfig {
4110            draft: DraftVersion::Draft21,
4111            transport: TransportType::Quic,
4112            skip_cert_verification: false,
4113            ca_certs: Vec::new(),
4114            setup_parameters: Vec::new(),
4115        };
4116        assert_eq!(config.alpn(), vec![b"moqt-21".to_vec()]);
4117    }
4118
4119    #[test]
4120    fn client_config_alpn_webtransport() {
4121        let config = ClientConfig {
4122            draft: DraftVersion::Draft21,
4123            transport: TransportType::WebTransport { url: "https://example.com".to_string() },
4124            skip_cert_verification: false,
4125            ca_certs: Vec::new(),
4126            setup_parameters: Vec::new(),
4127        };
4128        assert_eq!(config.alpn(), vec![b"h3".to_vec()]);
4129    }
4130
4131    /// `MOQT_ALPN` is the ALPN a client configured for this draft offers.
4132    #[test]
4133    fn moqt_alpn_is_the_one_a_client_offers() {
4134        // A literal on its own is what let this constant keep `moq-00` for
4135        // five drafts after draft-15 stopped using it, so the value is
4136        // checked against what a client configured for this draft actually
4137        // puts on the wire, and only then against the literal.
4138        let config = ClientConfig {
4139            draft: DraftVersion::Draft21,
4140            transport: TransportType::Quic,
4141            skip_cert_verification: false,
4142            ca_certs: Vec::new(),
4143            setup_parameters: Vec::new(),
4144        };
4145        assert_eq!(
4146            config.alpn(),
4147            vec![MOQT_ALPN.to_vec()],
4148            "MOQT_ALPN is {:?}; a draft-{} client offers {:?}",
4149            String::from_utf8_lossy(MOQT_ALPN),
4150            21,
4151            config
4152                .alpn()
4153                .iter()
4154                .map(|a| String::from_utf8_lossy(a).into_owned())
4155                .collect::<Vec<_>>(),
4156        );
4157        assert_eq!(MOQT_ALPN, b"moqt-21");
4158    }
4159
4160    /// Draft-21 Section 6.3 names seven message types a bidirectional stream
4161    /// may begin with, and no others. The set is checked against the raw
4162    /// numbers this draft's registry assigns rather than against the names,
4163    /// so a variant that is renumbered — SUBSCRIBE_NAMESPACE moved from 0x11
4164    /// to 0x50 between draft-17 and draft-18 — is caught even though the
4165    /// spelling did not change, and so is a port that carries draft-17's six
4166    /// over and leaves SUBSCRIBE_TRACKS (0x51) out.
4167    #[test]
4168    fn only_seven_message_types_open_a_request_stream() {
4169        // TRACK_STATUS, SUBSCRIBE, PUBLISH, FETCH, PUBLISH_NAMESPACE,
4170        // SUBSCRIBE_NAMESPACE and SUBSCRIBE_TRACKS, written as the numbers
4171        // draft-21 assigns them.
4172        let mut expected = vec![0x0D, 0x03, 0x1D, 0x16, 0x06, 0x50, 0x51];
4173        expected.sort_unstable();
4174
4175        let mut opens = Vec::new();
4176        for id in 0..=CONTROL_STREAM_TYPE {
4177            if let Some(ty) = MessageType::from_id(id) {
4178                if starts_a_request_stream(ty) {
4179                    opens.push(id);
4180                }
4181            }
4182        }
4183        opens.sort_unstable();
4184
4185        assert_eq!(
4186            opens, expected,
4187            "the types that open a request stream are {opens:?}; \
4188             draft-21 Section 6.3 names {expected:?}"
4189        );
4190    }
4191
4192    /// The kind a request helper labels its stream with must name the message
4193    /// that helper actually writes, and the check is made against the type
4194    /// varint the encoded message leads with — the byte a peer reads to
4195    /// decide whether the bidirectional stream is legal.
4196    ///
4197    /// This is the mislabelling a port from another draft is most likely to
4198    /// introduce, because the numbers move between drafts while the names do
4199    /// not. SUBSCRIBE_TRACKS is here for the opposite reason: it has no
4200    /// draft-17 counterpart at all, so a port that forgot it would leave
4201    /// `subscribe_tracks` on the control stream and nothing below would
4202    /// notice.
4203    #[test]
4204    fn each_request_kind_labels_the_message_its_helper_writes() {
4205        use crate::draft21::endpoint::Endpoint;
4206        use moqtap_codec::draft21::message::Setup;
4207
4208        let v = |n: u64| VarInt::from_u64(n).unwrap();
4209        let ns = TrackNamespace(vec![b"ns".to_vec()]);
4210
4211        let mut ep = Endpoint::new(Role::Client);
4212        ep.connect().unwrap();
4213        let _ = ep.send_setup(vec![]).unwrap();
4214        ep.receive_setup(&Setup { options: vec![] }).unwrap();
4215
4216        let (_, subscribe) = ep.subscribe(ns.clone(), b"t".to_vec(), vec![]).unwrap();
4217        let built = vec![
4218            (RequestKind::Subscribe, subscribe),
4219            // One FETCH, not two: draft-21 Section 9.11 has no Fetch Type field
4220            // and no joining fetch (draft-20 removed both), so there is no second shape
4221            // for this to label.
4222            (RequestKind::Fetch, ep.fetch(ns.clone(), b"t".to_vec(), vec![]).unwrap().1),
4223            (
4224                RequestKind::SubscribeNamespace,
4225                ep.subscribe_namespace(ns.clone(), vec![]).unwrap().1,
4226            ),
4227            (RequestKind::SubscribeTracks, ep.subscribe_tracks(ns.clone(), vec![]).unwrap().1),
4228            (RequestKind::PublishNamespace, ep.publish_namespace(ns.clone(), vec![]).unwrap().1),
4229            (
4230                RequestKind::TrackStatus,
4231                ep.track_status(ns.clone(), b"t".to_vec(), vec![]).unwrap().1,
4232            ),
4233            (
4234                RequestKind::Publish,
4235                ep.publish(ns.clone(), b"t".to_vec(), v(7), vec![], vec![]).unwrap().1,
4236            ),
4237        ];
4238
4239        for (kind, msg) in built {
4240            let mut wire = Vec::new();
4241            msg.encode(&mut wire).unwrap();
4242            let mut cursor = &wire[..];
4243            let on_the_wire =
4244                DraftVersion::Draft21.decode_varint(&mut cursor).unwrap().into_inner();
4245            assert_eq!(
4246                kind.message_type().id(),
4247                on_the_wire,
4248                "{kind:?} is labelled {} but its message leads with {on_the_wire}",
4249                kind.message_type().id(),
4250            );
4251            assert!(
4252                starts_a_request_stream(kind.message_type()),
4253                "{kind:?} labels a message type that may not begin a bidirectional stream",
4254            );
4255        }
4256    }
4257
4258    /// The classifier the accept path runs and the one
4259    /// [`Connection::send_control`] runs must answer alike for every message
4260    /// type this draft assigns, or a message could be refused on the control
4261    /// stream and refused again as the opening of a request stream — leaving
4262    /// no legal place for it.
4263    ///
4264    /// SUBSCRIBE_TRACKS is the one a port from draft-17 would drop, because
4265    /// draft-17 has no such message to copy.
4266    #[test]
4267    fn the_two_request_stream_classifiers_agree() {
4268        let mut classified = 0;
4269        for id in 0..=CONTROL_STREAM_TYPE {
4270            let Some(ty) = MessageType::from_id(id) else { continue };
4271            classified += 1;
4272            let kind = RequestKind::from_message_type(ty);
4273            assert_eq!(
4274                kind.is_some(),
4275                starts_a_request_stream(ty),
4276                "type {id} {} a request stream but from_message_type calls it {kind:?}",
4277                if starts_a_request_stream(ty) { "opens" } else { "does not open" },
4278            );
4279            if let Some(kind) = kind {
4280                assert_eq!(
4281                    kind.message_type(),
4282                    ty,
4283                    "from_message_type sent type {id} to {kind:?}, which names a different message",
4284                );
4285            }
4286        }
4287        assert!(classified > 7, "the loop found only {classified} assigned message types");
4288    }
4289
4290    /// A stream this endpoint opened is cancelled when its handle is dropped;
4291    /// one the peer opened is reset as unserved. Both codes are on the wire,
4292    /// so they may not be the same number.
4293    #[test]
4294    fn the_two_abandonment_codes_are_distinct() {
4295        assert_eq!(REQUEST_CANCELLED, 0x1);
4296        assert_eq!(REQUEST_UNANSWERED, 0x0);
4297        assert_ne!(
4298            REQUEST_CANCELLED, REQUEST_UNANSWERED,
4299            "a peer cannot tell a rejected request from a dropped one if both reset with the same code",
4300        );
4301    }
4302
4303    #[test]
4304    fn transport_type_debug() {
4305        let quic = TransportType::Quic;
4306        assert!(format!("{quic:?}").contains("Quic"));
4307
4308        let wt = TransportType::WebTransport { url: "https://example.com".to_string() };
4309        assert!(format!("{wt:?}").contains("WebTransport"));
4310    }
4311}
4312
4313#[cfg(test)]
4314mod accept_on_the_wire {
4315    //! The accept path against a real QUIC peer.
4316    //!
4317    //! Everything the responder side does that a peer can see — which stream a
4318    //! response goes out on, which code an abandoned request stream is reset
4319    //! with, whether a FIN arrives before the messages that direction still
4320    //! owes, and which session error code a violation closes with — is
4321    //! observable only from the other end of a connection. A test holding an
4322    //! endpoint alone is satisfied by state that never reached the wire, so
4323    //! these hold the other end.
4324    //!
4325    //! The peer is raw `quinn` for everything the accept path decides. It does
4326    //! use [`FramedRecvStream`] to decode what comes back, because control
4327    //! framing is shared by both directions and gated elsewhere; the
4328    //! classification, registration, routing and stream-closing under test here
4329    //! are not part of it.
4330
4331    use super::*;
4332    use std::sync::Arc;
4333
4334    use std::net::SocketAddr;
4335    use std::time::Duration;
4336
4337    use moqtap_codec::draft21::message::{
4338        GoAway, Publish, PublishDone, Setup, Subscribe, SubscribeNamespace,
4339    };
4340
4341    /// Session termination codes, draft-21 Section 16.11.1.
4342    const PROTOCOL_VIOLATION: u64 = 0x3;
4343    const INVALID_REQUEST_ID: u64 = 0x4;
4344
4345    /// Long enough that a loaded machine cannot fail a test that would
4346    /// otherwise pass, short enough that a hang is reported rather than run to
4347    /// the harness timeout.
4348    const PATIENCE: Duration = Duration::from_secs(10);
4349
4350    /// How long to wait before concluding that nothing more is coming. Used
4351    /// only where the absence of a message is the assertion, so it is a floor
4352    /// on the test's run time and is kept small.
4353    const QUIET: Duration = Duration::from_millis(300);
4354
4355    fn v(n: u64) -> VarInt {
4356        VarInt::from_u64(n).unwrap()
4357    }
4358
4359    fn ns() -> TrackNamespace {
4360        TrackNamespace(vec![b"live".to_vec()])
4361    }
4362
4363    fn encode(msg: ControlMessage) -> Vec<u8> {
4364        let mut buf = Vec::new();
4365        AnyControlMessage::Draft21(msg).encode(&mut buf).expect("encode");
4366        buf
4367    }
4368
4369    /// A SUBSCRIBE carrying `id`. Odd ids are the ones a server allocates,
4370    /// which is what a client's peer must use.
4371    fn subscribe(id: u64) -> ControlMessage {
4372        ControlMessage::Subscribe(Subscribe {
4373            request_id: v(id),
4374            track_namespace: ns(),
4375            track_name: b"video".to_vec(),
4376            parameters: vec![],
4377        })
4378    }
4379
4380    fn request_update(id: u64) -> ControlMessage {
4381        ControlMessage::RequestUpdate(moqtap_codec::draft21::message::RequestUpdate {
4382            request_id: v(id),
4383            parameters: vec![],
4384        })
4385    }
4386
4387    fn peer_fetch(id: u64) -> ControlMessage {
4388        ControlMessage::Fetch(moqtap_codec::draft21::message::Fetch {
4389            request_id: v(id),
4390            track_namespace: ns(),
4391            track_name: b"video".to_vec(),
4392            parameters: vec![],
4393        })
4394    }
4395
4396    fn fetch_ok() -> FetchOk {
4397        FetchOk {
4398            end_of_track: 0,
4399            end_group: v(1),
4400            end_object: v(0),
4401            parameters: vec![],
4402            track_properties: vec![],
4403        }
4404    }
4405
4406    fn subscribe_ok() -> SubscribeOk {
4407        SubscribeOk { track_alias: v(7), parameters: vec![], track_properties: vec![] }
4408    }
4409
4410    fn request_error() -> RequestError {
4411        RequestError {
4412            error_code: v(0x1),
4413            retry_interval: v(0),
4414            reason_phrase: b"no".to_vec(),
4415            redirect: None,
4416        }
4417    }
4418
4419    fn init_crypto() {
4420        let _ = rustls::crypto::ring::default_provider().install_default();
4421    }
4422
4423    /// A quinn server on a loopback port, offering this draft's ALPN.
4424    fn server_endpoint() -> (quinn::Endpoint, SocketAddr) {
4425        use rcgen::{CertificateParams, KeyPair, PKCS_ECDSA_P256_SHA256};
4426        use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
4427
4428        let key_pair = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).expect("keypair");
4429        let params = CertificateParams::new(vec!["localhost".into()]).expect("params");
4430        let cert = params.self_signed(&key_pair).expect("self-sign");
4431        let cert_der = CertificateDer::from(cert.der().to_vec());
4432        let key_der = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key_pair.serialize_der()));
4433
4434        let mut server_crypto = rustls::ServerConfig::builder()
4435            .with_no_client_auth()
4436            .with_single_cert(vec![cert_der], key_der)
4437            .expect("server cert");
4438        server_crypto.alpn_protocols = vec![DraftVersion::Draft21.quic_alpn().to_vec()];
4439        let server_crypto =
4440            quinn::crypto::rustls::QuicServerConfig::try_from(server_crypto).expect("quic crypto");
4441        let server_config = quinn::ServerConfig::with_crypto(Arc::new(server_crypto));
4442        let endpoint = quinn::Endpoint::server(server_config, "127.0.0.1:0".parse().unwrap())
4443            .expect("bind server");
4444        let addr = endpoint.local_addr().expect("local_addr");
4445        (endpoint, addr)
4446    }
4447
4448    async fn connect_client(addr: SocketAddr) -> Result<Connection, ConnectionError> {
4449        Connection::connect(
4450            &addr.to_string(),
4451            ClientConfig {
4452                draft: DraftVersion::Draft21,
4453                transport: TransportType::Quic,
4454                skip_cert_verification: true,
4455                ca_certs: Vec::new(),
4456                setup_parameters: Vec::new(),
4457            },
4458        )
4459        .await
4460    }
4461
4462    /// The peer's half of the setup exchange: read the client's SETUP off its
4463    /// unidirectional control stream, answer with one of our own.
4464    ///
4465    /// Both control streams are handed back so they stay open for the
4466    /// connection's life. Dropping a quinn receive stream sends STOP_SENDING
4467    /// and dropping a send stream resets it, either of which would look to the
4468    /// client like the control plane failing.
4469    async fn peer_handshake(
4470        endpoint: &quinn::Endpoint,
4471    ) -> (quinn::Connection, quinn::SendStream, quinn::RecvStream) {
4472        let conn = endpoint.accept().await.expect("accept").await.expect("tls handshake");
4473        let mut client_control = conn.accept_uni().await.expect("accept_uni");
4474        let mut seen = Vec::new();
4475        let mut chunk = [0u8; 1024];
4476        while seen.len() < 3 {
4477            match client_control.read(&mut chunk).await.expect("read SETUP") {
4478                Some(n) => seen.extend_from_slice(&chunk[..n]),
4479                None => break,
4480            }
4481        }
4482        assert!(!seen.is_empty(), "the client sent no SETUP");
4483        let mut ours = conn.open_uni().await.expect("open_uni");
4484        ours.write_all(&encode(ControlMessage::Setup(Setup { options: Vec::new() })))
4485            .await
4486            .expect("write SETUP");
4487        (conn, ours, client_control)
4488    }
4489
4490    /// A connected client and the peer holding the other end.
4491    struct Loopback {
4492        conn: Connection,
4493        peer: quinn::Connection,
4494        _endpoint: quinn::Endpoint,
4495        _control_send: quinn::SendStream,
4496        _control_recv: quinn::RecvStream,
4497    }
4498
4499    async fn loopback() -> Loopback {
4500        init_crypto();
4501        let (endpoint, addr) = server_endpoint();
4502        let (client, peer) = tokio::join!(connect_client(addr), peer_handshake(&endpoint));
4503        let (peer, control_send, control_recv) = peer;
4504        Loopback {
4505            conn: client.expect("client connect"),
4506            peer,
4507            _endpoint: endpoint,
4508            _control_send: control_send,
4509            _control_recv: control_recv,
4510        }
4511    }
4512
4513    fn framed(recv: quinn::RecvStream) -> FramedRecvStream {
4514        FramedRecvStream::new(RecvStream::Quic(recv), DraftVersion::Draft21)
4515    }
4516
4517    /// Read one control message the client wrote, failing rather than hanging.
4518    async fn next_control(recv: &mut FramedRecvStream) -> ControlMessage {
4519        let (any, _) = tokio::time::timeout(PATIENCE, recv.read_control(false))
4520            .await
4521            .expect("the client wrote nothing")
4522            .expect("read control");
4523        match any {
4524            AnyControlMessage::Draft21(msg) => msg,
4525            #[allow(unreachable_patterns)]
4526            other => panic!("expected a draft-21 message, got {other:?}"),
4527        }
4528    }
4529
4530    async fn assert_closed_with(peer: &quinn::Connection, code: u64, phrase: &str) {
4531        let reason = tokio::time::timeout(PATIENCE, peer.closed())
4532            .await
4533            .expect("the client reported the violation but never closed the connection");
4534        match reason {
4535            quinn::ConnectionError::ApplicationClosed(frame) => {
4536                assert_eq!(u64::from(frame.error_code), code, "the close carried the wrong code");
4537                let text = String::from_utf8_lossy(&frame.reason).to_string();
4538                assert!(
4539                    text.contains(phrase),
4540                    "the close reason should name the rule that was broken; got {text:?}",
4541                );
4542            }
4543            other => panic!("expected an application close, got {other:?}"),
4544        }
4545    }
4546
4547    /// A peer's SUBSCRIBE is accepted, answered on the stream it arrived on,
4548    /// and cannot be finished until each message draft-21 Section 6.4.2.2
4549    /// requires has been sent.
4550    #[tokio::test]
4551    async fn a_peers_subscribe_is_answered_on_the_stream_it_arrived_on() {
4552        let mut lb = loopback().await;
4553
4554        let (mut ps, pr) = lb.peer.open_bi().await.expect("open_bi");
4555        ps.write_all(&encode(subscribe(1))).await.expect("write SUBSCRIBE");
4556        let mut pr = framed(pr);
4557
4558        let (msg, mut stream) = tokio::time::timeout(PATIENCE, lb.conn.accept_request_stream())
4559            .await
4560            .expect("accept hung")
4561            .expect("accept");
4562        assert!(matches!(msg, ControlMessage::Subscribe(_)), "{msg:?}");
4563        assert_eq!(stream.origin(), RequestOrigin::Peer);
4564        assert_eq!(stream.kind(), RequestKind::Subscribe);
4565        assert_eq!(stream.request_id().into_inner(), 1);
4566        assert_eq!(lb.conn.endpoint().peer_request_count(), 1);
4567
4568        // Section 6.4.2.2: "an endpoint sending a response to a request MUST send
4569        // the corresponding response message ... before sending a FIN."
4570        let err = stream.finish().await.err();
4571        assert!(
4572            matches!(err, Some(ConnectionError::FinBeforeResponse(1))),
4573            "a FIN before the response must be refused: {err:?}",
4574        );
4575
4576        lb.conn.respond_subscribe_ok(&mut stream, subscribe_ok()).await.expect("respond");
4577        assert!(stream.responded());
4578        // On the request's own stream, not the control stream: this reader is
4579        // the peer's half of the bidirectional stream it opened.
4580        assert!(matches!(next_control(&mut pr).await, ControlMessage::SubscribeOk(_)));
4581
4582        // The rest of the same sentence: "the publisher of an Established
4583        // subscription MUST send PUBLISH_DONE, before sending a FIN."
4584        assert!(stream.owes_publish_done());
4585        let err = stream.finish().await.err();
4586        assert!(
4587            matches!(err, Some(ConnectionError::FinBeforePublishDone(1))),
4588            "a FIN before PUBLISH_DONE must be refused: {err:?}",
4589        );
4590
4591        lb.conn
4592            .publish_done_on(&mut stream, v(0), v(0), Vec::new())
4593            .await
4594            .expect("publish_done_on");
4595        assert!(matches!(next_control(&mut pr).await, ControlMessage::PublishDone(_)));
4596
4597        // And now the FIN, which is a clean end rather than a reset.
4598        let end = pr.read_control(false).await.expect_err("the stream should have ended");
4599        assert!(
4600            matches!(end, ConnectionError::UnexpectedEnd),
4601            "the completed request stream should end with a FIN, not {end}",
4602        );
4603    }
4604
4605    /// A refused update leaves the stream open for the termination it owes.
4606    ///
4607    /// Section 9.5.1: "When a REQUEST_UPDATE is unsuccessful, the publisher
4608    /// MUST also terminate the subscription by sending a PUBLISH_DONE with
4609    /// error code UPDATE_FAILED." That message has to go on the request's own
4610    /// stream, so a REQUEST_ERROR answering an update cannot finish the send
4611    /// half the way one answering the request does.
4612    #[tokio::test]
4613    async fn a_refused_update_leaves_the_stream_open_for_its_termination() {
4614        let mut lb = loopback().await;
4615
4616        let (mut ps, pr) = lb.peer.open_bi().await.expect("open_bi");
4617        ps.write_all(&encode(subscribe(1))).await.expect("write SUBSCRIBE");
4618        let mut pr = framed(pr);
4619
4620        let (_, mut stream) = tokio::time::timeout(PATIENCE, lb.conn.accept_request_stream())
4621            .await
4622            .expect("accept hung")
4623            .expect("accept");
4624        lb.conn.respond_subscribe_ok(&mut stream, subscribe_ok()).await.expect("respond");
4625        assert!(matches!(next_control(&mut pr).await, ControlMessage::SubscribeOk(_)));
4626        assert!(stream.owes_publish_done());
4627
4628        // The peer updates the subscription and this endpoint refuses it.
4629        // The read is what puts the update on the endpoint's books; refusing
4630        // one it has not seen is a different error entirely.
4631        ps.write_all(&encode(request_update(1))).await.expect("write REQUEST_UPDATE");
4632        let update = tokio::time::timeout(PATIENCE, lb.conn.recv_on_request_stream(&mut stream))
4633            .await
4634            .expect("the update never arrived")
4635            .expect("read the update");
4636        assert!(matches!(update, ControlMessage::RequestUpdate(_)), "{update:?}");
4637        lb.conn.respond_error(&mut stream, request_error()).await.expect("refuse the update");
4638        assert!(matches!(next_control(&mut pr).await, ControlMessage::RequestError(_)));
4639
4640        // The subscription is still live and still owes its ending, so the
4641        // stream is neither finished nor relieved of the obligation.
4642        assert!(
4643            stream.owes_publish_done(),
4644            "a refused update retires nothing: the subscription still owes a PUBLISH_DONE",
4645        );
4646
4647        lb.conn
4648            .publish_done_on(&mut stream, v(0x8), v(0), Vec::new())
4649            .await
4650            .expect("the termination the refusal owes");
4651        assert!(matches!(next_control(&mut pr).await, ControlMessage::PublishDone(_)));
4652    }
4653
4654    /// A refused namespace update closes the stream rather than owing a message.
4655    ///
4656    /// Section 9.5.1 sorts a refused REQUEST_UPDATE by what was being
4657    /// updated, and a namespace subscription falls in the clause that ends
4658    /// with the transport rather than with a message: "When a REQUEST_UPDATE
4659    /// fails for a SUBSCRIBE_NAMESPACE, SUBSCRIBE_TRACKS or PUBLISH_NAMESPACE,
4660    /// the responder MUST close the bidi stream (see Section 6.4.2.2)." There is
4661    /// no subscription to terminate here and no PUBLISH_DONE that could go
4662    /// out, so a send half held open for one would stay open for good.
4663    #[tokio::test]
4664    async fn a_refused_namespace_update_closes_the_stream() {
4665        let mut lb = loopback().await;
4666
4667        let (mut ps, pr) = lb.peer.open_bi().await.expect("open_bi");
4668        ps.write_all(&encode(ControlMessage::SubscribeNamespace(SubscribeNamespace {
4669            request_id: v(1),
4670            namespace_prefix: ns(),
4671            parameters: vec![],
4672        })))
4673        .await
4674        .expect("write SUBSCRIBE_NAMESPACE");
4675        let mut pr = framed(pr);
4676
4677        let (_, mut stream) = tokio::time::timeout(PATIENCE, lb.conn.accept_request_stream())
4678            .await
4679            .expect("accept hung")
4680            .expect("accept");
4681        lb.conn
4682            .respond_ok(&mut stream, RequestOk { parameters: vec![], track_properties: vec![] })
4683            .await
4684            .expect("respond_ok");
4685        assert!(matches!(next_control(&mut pr).await, ControlMessage::RequestOk(_)));
4686
4687        // The peer asks to move the prefix and this endpoint refuses.
4688        ps.write_all(&encode(request_update(1))).await.expect("write REQUEST_UPDATE");
4689        let update = tokio::time::timeout(PATIENCE, lb.conn.recv_on_request_stream(&mut stream))
4690            .await
4691            .expect("read hung")
4692            .expect("read REQUEST_UPDATE");
4693        assert!(matches!(update, ControlMessage::RequestUpdate(_)));
4694        lb.conn.respond_error(&mut stream, request_error()).await.expect("refuse the update");
4695        assert!(matches!(next_control(&mut pr).await, ControlMessage::RequestError(_)));
4696
4697        // The refusal ends this request stream, so the peer's next read finds
4698        // the send half closed rather than waiting on a message a namespace
4699        // subscription has no way to send.
4700        let ended = tokio::time::timeout(PATIENCE, pr.read_control(false))
4701            .await
4702            .expect("the peer is still reading: the refusal never closed the send half")
4703            .expect_err("a refused namespace update left the stream open");
4704        assert!(
4705            matches!(ended, ConnectionError::UnexpectedEnd),
4706            "the peer should have seen the FIN, got {ended:?}",
4707        );
4708    }
4709
4710    /// Draft-21 Section 6.4.2.3: "When an endpoint rejects a request without
4711    /// performing any application processing, it SHOULD send a REQUEST_ERROR
4712    /// and FIN the stream." The FIN is what tells the peer the request is over;
4713    /// without it the handle's [`Drop`] would reset the stream instead.
4714    #[tokio::test]
4715    async fn a_rejected_request_is_finished_rather_than_reset() {
4716        let mut lb = loopback().await;
4717
4718        let (mut ps, pr) = lb.peer.open_bi().await.expect("open_bi");
4719        ps.write_all(&encode(subscribe(1))).await.expect("write SUBSCRIBE");
4720        let mut pr = framed(pr);
4721
4722        let (_, mut stream) = tokio::time::timeout(PATIENCE, lb.conn.accept_request_stream())
4723            .await
4724            .expect("accept hung")
4725            .expect("accept");
4726        lb.conn.respond_error(&mut stream, request_error()).await.expect("respond_error");
4727        assert!(matches!(next_control(&mut pr).await, ControlMessage::RequestError(_)));
4728
4729        // Dropping the handle after the FIN must not turn a rejection into a
4730        // reset, so the end of stream is read after the handle is gone.
4731        drop(stream);
4732        let end = pr.read_control(false).await.expect_err("the stream should have ended");
4733        assert!(
4734            matches!(end, ConnectionError::UnexpectedEnd),
4735            "a rejected request stream should be finished, not {end}",
4736        );
4737    }
4738
4739    /// Draft-21 Section 6.3: a bidirectional stream that begins with a message
4740    /// type that opens no request "MUST close the Session with a
4741    /// PROTOCOL_VIOLATION" — on the wire, not only in the local state machine.
4742    /// The code is not draft-21 Section 6.4.2.1's INVALID_REQUEST_ID.
4743    #[tokio::test]
4744    async fn a_stream_that_opens_no_request_closes_the_session() {
4745        let mut lb = loopback().await;
4746
4747        let (mut ps, _pr) = lb.peer.open_bi().await.expect("open_bi");
4748        ps.write_all(&encode(ControlMessage::GoAway(GoAway {
4749            new_session_uri: Vec::new(),
4750            timeout: v(0),
4751        })))
4752        .await
4753        .expect("write GOAWAY");
4754
4755        // `RequestStream` is not `Debug` — it owns two live stream halves — so
4756        // the accepted case is named rather than unwrapped.
4757        let err = match tokio::time::timeout(PATIENCE, lb.conn.accept_request_stream())
4758            .await
4759            .expect("accept hung")
4760        {
4761            Err(e) => e,
4762            Ok((msg, _)) => panic!("a GOAWAY opens no request stream, but {msg:?} was accepted"),
4763        };
4764        assert!(
4765            matches!(err, ConnectionError::NonRequestOnRequestStream(MessageType::GoAway)),
4766            "{err}",
4767        );
4768
4769        assert_closed_with(&lb.peer, PROTOCOL_VIOLATION, "GoAway").await;
4770    }
4771
4772    /// Draft-21 Section 6.4.2.1: "If an endpoint receives a Request ID where the
4773    /// least significant bit is incorrect for the sender ... it MUST close the
4774    /// session with INVALID_REQUEST_ID." A different rule from the one above,
4775    /// and a different code, so a peer can tell them apart.
4776    #[tokio::test]
4777    async fn a_peer_id_with_the_wrong_parity_closes_the_session() {
4778        let mut lb = loopback().await;
4779
4780        let (mut ps, _pr) = lb.peer.open_bi().await.expect("open_bi");
4781        // 2 is even, so it is an id this client allocates for itself.
4782        ps.write_all(&encode(subscribe(2))).await.expect("write SUBSCRIBE");
4783
4784        let err = match tokio::time::timeout(PATIENCE, lb.conn.accept_request_stream())
4785            .await
4786            .expect("accept hung")
4787        {
4788            Err(e) => e,
4789            Ok((msg, _)) => {
4790                panic!("an even Request ID from a server peer must be refused, not {msg:?}")
4791            }
4792        };
4793        assert!(matches!(err, ConnectionError::Endpoint(EndpointError::RequestId(_))), "{err}");
4794
4795        assert_closed_with(&lb.peer, INVALID_REQUEST_ID, "parity").await;
4796    }
4797
4798    /// Dropping a request stream is one act with two meanings, and the peer
4799    /// can only tell them apart if the codes differ: a request this endpoint
4800    /// made was cancelled, a request made of it was never served.
4801    #[tokio::test]
4802    async fn an_unserved_request_and_a_cancelled_one_reset_with_different_codes() {
4803        let mut lb = loopback().await;
4804
4805        // Inbound: the peer asked, and the handle was dropped unanswered.
4806        let (mut ps, pr) = lb.peer.open_bi().await.expect("open_bi");
4807        ps.write_all(&encode(subscribe(1))).await.expect("write SUBSCRIBE");
4808        let mut pr = framed(pr);
4809        let (_, stream) = tokio::time::timeout(PATIENCE, lb.conn.accept_request_stream())
4810            .await
4811            .expect("accept hung")
4812            .expect("accept");
4813        drop(stream);
4814        let err = tokio::time::timeout(PATIENCE, pr.read_control(false))
4815            .await
4816            .expect("the inbound stream was neither reset nor answered")
4817            .expect_err("the dropped handle should have reset the stream");
4818        assert!(
4819            matches!(
4820                err,
4821                ConnectionError::Transport(TransportError::StreamReset(c))
4822                    if c == REQUEST_UNANSWERED
4823            ),
4824            "an unserved inbound request should reset with INTERNAL_ERROR (0x0): {err}",
4825        );
4826
4827        // Outbound: this endpoint asked, and walked away.
4828        let outbound = lb.conn.subscribe(ns(), b"audio".to_vec(), vec![]).await.expect("subscribe");
4829        let (_, their_recv) = tokio::time::timeout(PATIENCE, lb.peer.accept_bi())
4830            .await
4831            .expect("the client opened no request stream")
4832            .expect("accept_bi");
4833        let mut their_recv = framed(their_recv);
4834        assert!(matches!(next_control(&mut their_recv).await, ControlMessage::Subscribe(_)));
4835        drop(outbound);
4836        let err = tokio::time::timeout(PATIENCE, their_recv.read_control(false))
4837            .await
4838            .expect("the outbound stream was never reset")
4839            .expect_err("the dropped handle should have reset the stream");
4840        assert!(
4841            matches!(
4842                err,
4843                ConnectionError::Transport(TransportError::StreamReset(c))
4844                    if c == REQUEST_CANCELLED
4845            ),
4846            "an abandoned outbound request should reset with CANCELLED (0x1): {err}",
4847        );
4848    }
4849
4850    /// A dropped accept future loses neither the stream nor the bytes of the
4851    /// request that had already arrived, which is what makes
4852    /// [`Connection::accept_request_stream`] safe to `select!` against anything
4853    /// else.
4854    #[tokio::test]
4855    async fn a_cancelled_accept_keeps_the_stream_and_what_had_arrived() {
4856        let mut lb = loopback().await;
4857
4858        let (mut ps, _pr) = lb.peer.open_bi().await.expect("open_bi");
4859        let bytes = encode(subscribe(1));
4860        // One byte: enough to open the stream and to be read as the start of a
4861        // message, not enough to complete one.
4862        ps.write_all(&bytes[..1]).await.expect("write the first byte");
4863
4864        assert!(
4865            tokio::time::timeout(QUIET, lb.conn.accept_request_stream()).await.is_err(),
4866            "a partial request must not complete an accept",
4867        );
4868        assert_eq!(
4869            lb.conn.pending_inbound_count(),
4870            1,
4871            "the cancelled accept dropped the peer's stream",
4872        );
4873
4874        ps.write_all(&bytes[1..]).await.expect("write the rest");
4875        let (msg, stream) = tokio::time::timeout(PATIENCE, lb.conn.accept_request_stream())
4876            .await
4877            .expect("the retried accept hung")
4878            .expect("accept");
4879        // The Request ID could not be read at all if the first byte had gone
4880        // with the cancelled future: the message would not decode.
4881        assert_eq!(stream.request_id().into_inner(), 1);
4882        assert!(matches!(msg, ControlMessage::Subscribe(_)), "{msg:?}");
4883        assert_eq!(lb.conn.pending_inbound_count(), 0);
4884    }
4885
4886    /// The `respond_*` helpers answer requests the peer made, and refuse the
4887    /// ones this endpoint made. The consequence is that nothing is written:
4888    /// the peer sees the request and then silence, not a response to itself.
4889    #[tokio::test]
4890    async fn a_respond_helper_writes_nothing_on_a_stream_this_endpoint_opened() {
4891        let mut lb = loopback().await;
4892
4893        let mut outbound =
4894            lb.conn.subscribe(ns(), b"video".to_vec(), vec![]).await.expect("subscribe");
4895        let (_, their_recv) = tokio::time::timeout(PATIENCE, lb.peer.accept_bi())
4896            .await
4897            .expect("the client opened no request stream")
4898            .expect("accept_bi");
4899        let mut their_recv = framed(their_recv);
4900        assert!(matches!(next_control(&mut their_recv).await, ControlMessage::Subscribe(_)));
4901
4902        let err = lb
4903            .conn
4904            .respond_error(&mut outbound, request_error())
4905            .await
4906            .expect_err("a request this endpoint made is not ours to answer");
4907        assert!(matches!(err, ConnectionError::RespondedToOwnRequest(0)), "{err}");
4908
4909        assert!(
4910            tokio::time::timeout(QUIET, their_recv.read_control(false)).await.is_err(),
4911            "the refused response reached the wire anyway",
4912        );
4913    }
4914
4915    /// A refused fetch update resets the stream the objects were going out on.
4916    ///
4917    /// Section 9.5.1: "When a REQUEST_UPDATE fails for a FETCH, the publisher
4918    /// MUST reset the FETCH data stream." The objects are not on the request
4919    /// stream, so refusing the update on that stream is only half of it; the
4920    /// data stream has to go too, and the connection can only reset a handle
4921    /// it still holds.
4922    #[tokio::test]
4923    async fn a_refused_fetch_update_resets_the_fetch_data_stream() {
4924        let mut lb = loopback().await;
4925
4926        let (mut ps, pr) = lb.peer.open_bi().await.expect("open_bi");
4927        ps.write_all(&encode(peer_fetch(1))).await.expect("write FETCH");
4928        let mut pr = framed(pr);
4929
4930        let (_, mut stream) = tokio::time::timeout(PATIENCE, lb.conn.accept_request_stream())
4931            .await
4932            .expect("accept hung")
4933            .expect("accept");
4934        assert_eq!(stream.kind(), RequestKind::Fetch);
4935        lb.conn.respond_fetch_ok(&mut stream, fetch_ok()).await.expect("respond_fetch_ok");
4936        assert!(matches!(next_control(&mut pr).await, ControlMessage::FetchOk(_)));
4937
4938        // The objects go out on a stream of their own, which the request now
4939        // holds.
4940        lb.conn
4941            .open_fetch_stream_on(
4942                &mut stream,
4943                &AnyFetchHeader::Draft21(FetchHeader { request_id: v(1) }),
4944            )
4945            .await
4946            .expect("open the fetch data stream");
4947        let data = tokio::time::timeout(PATIENCE, lb.peer.accept_uni())
4948            .await
4949            .expect("no data stream arrived")
4950            .expect("accept_uni");
4951        let mut data = framed(data);
4952        tokio::time::timeout(PATIENCE, data.read_fetch_header())
4953            .await
4954            .expect("the header never arrived")
4955            .expect("the data stream opens with a FETCH_HEADER");
4956
4957        // The peer updates the fetch and this endpoint refuses it.
4958        ps.write_all(&encode(request_update(1))).await.expect("write REQUEST_UPDATE");
4959        tokio::time::timeout(PATIENCE, lb.conn.recv_on_request_stream(&mut stream))
4960            .await
4961            .expect("read hung")
4962            .expect("read REQUEST_UPDATE");
4963        lb.conn.respond_error(&mut stream, request_error()).await.expect("refuse the update");
4964        assert!(matches!(next_control(&mut pr).await, ControlMessage::RequestError(_)));
4965
4966        // The data stream went with it: the peer's next read on it fails
4967        // rather than waiting for objects that are not coming.
4968        let err = tokio::time::timeout(PATIENCE, data.read_control(false))
4969            .await
4970            .expect("the peer is still waiting on a stream that should have been reset")
4971            .expect_err("the data stream should have been reset");
4972        assert!(
4973            format!("{err}").to_lowercase().contains("reset"),
4974            "the peer should see a reset, got {err}",
4975        );
4976    }
4977
4978    /// A publisher can open the stream a FETCH's objects go on, and owns it.
4979    ///
4980    /// The objects answering a FETCH go on a unidirectional stream of their
4981    /// own that opens with a FETCH_HEADER.
4982    #[tokio::test]
4983    async fn a_fetch_data_stream_can_be_opened_through_the_connection() {
4984        let lb = loopback().await;
4985
4986        let mut send = lb
4987            .conn
4988            .open_fetch_stream(&AnyFetchHeader::Draft21(FetchHeader { request_id: v(4) }))
4989            .await
4990            .expect("open a fetch data stream");
4991
4992        let recv = tokio::time::timeout(PATIENCE, lb.peer.accept_uni())
4993            .await
4994            .expect("the client opened no data stream")
4995            .expect("accept_uni");
4996        let mut recv = framed(recv);
4997        let header = tokio::time::timeout(PATIENCE, recv.read_fetch_header())
4998            .await
4999            .expect("the header never arrived")
5000            .expect("the stream opens with a FETCH_HEADER");
5001        assert!(
5002            matches!(&header, AnyFetchHeader::Draft21(h) if h.request_id.into_inner() == 4),
5003            "the header names the request it answers: {header:?}",
5004        );
5005
5006        // The caller holds the stream, which is what lets a request that fails
5007        // later reset the objects it was serving.
5008        send.reset(0).expect("reset the fetch data stream");
5009    }
5010
5011    /// Draft-21 Table 5 gives NAMESPACE the Stream value "Request", and
5012    /// Section 9.16 puts it "on the response stream of a SUBSCRIBE_NAMESPACE
5013    /// request". Draft-17 has no Stream column and treats NAMESPACE as a
5014    /// control-stream announcement, so this is the placement a port from
5015    /// draft-17 would get wrong — and it is checked by reading the peer's own
5016    /// half of the request stream, which a control-stream write could not
5017    /// reach.
5018    #[tokio::test]
5019    async fn a_namespace_is_announced_on_the_request_stream_that_asked_for_it() {
5020        let mut lb = loopback().await;
5021
5022        let (mut ps, pr) = lb.peer.open_bi().await.expect("open_bi");
5023        ps.write_all(&encode(ControlMessage::SubscribeNamespace(SubscribeNamespace {
5024            request_id: v(1),
5025            namespace_prefix: ns(),
5026            parameters: vec![],
5027        })))
5028        .await
5029        .expect("write SUBSCRIBE_NAMESPACE");
5030        let mut pr = framed(pr);
5031
5032        let (_, mut stream) = tokio::time::timeout(PATIENCE, lb.conn.accept_request_stream())
5033            .await
5034            .expect("accept hung")
5035            .expect("accept");
5036        assert_eq!(stream.kind(), RequestKind::SubscribeNamespace);
5037
5038        lb.conn
5039            .respond_ok(&mut stream, RequestOk { parameters: vec![], track_properties: vec![] })
5040            .await
5041            .expect("respond_ok");
5042        assert!(matches!(next_control(&mut pr).await, ControlMessage::RequestOk(_)));
5043
5044        lb.conn
5045            .namespace_on(&mut stream, Namespace { namespace_suffix: ns() })
5046            .await
5047            .expect("namespace_on");
5048        assert!(matches!(next_control(&mut pr).await, ControlMessage::Namespace(_)));
5049
5050        lb.conn
5051            .namespace_done_on(&mut stream, NamespaceDone { namespace_suffix: ns() })
5052            .await
5053            .expect("namespace_done_on");
5054        assert!(matches!(next_control(&mut pr).await, ControlMessage::NamespaceDone(_)));
5055
5056        // Nothing further is owed on this direction, so the responder may
5057        // finish it — Section 6.4.2.2's guard covers the response and a
5058        // publisher's PUBLISH_DONE, not announcements that may never come.
5059        stream.finish().await.expect("finish an answered namespace subscription");
5060    }
5061
5062    /// An update on a PUBLISH this endpoint sent is answered here.
5063    ///
5064    /// Section 9.5 names the one case where a requester answers rather than
5065    /// asks: "A subscriber can also send REQUEST_UPDATE to modify parameters
5066    /// of a subscription established with PUBLISH." The receiver of that
5067    /// update "MUST respond with exactly one REQUEST_OK or REQUEST_ERROR
5068    /// message indicating if the update was successful", and on a PUBLISH this
5069    /// endpoint sent, the receiver is this endpoint.
5070    #[tokio::test]
5071    async fn an_update_on_a_publish_we_sent_is_answered_here() {
5072        let mut lb = loopback().await;
5073
5074        let mut outbound =
5075            lb.conn.publish(ns(), b"video".to_vec(), v(7), vec![], vec![]).await.expect("publish");
5076        let (mut their_send, their_recv) = tokio::time::timeout(PATIENCE, lb.peer.accept_bi())
5077            .await
5078            .expect("the client opened no request stream")
5079            .expect("accept_bi");
5080        let mut their_recv = framed(their_recv);
5081        assert!(matches!(next_control(&mut their_recv).await, ControlMessage::Publish(_)));
5082
5083        // The subscriber accepts the publication, then updates it.
5084        their_send
5085            .write_all(&encode(ControlMessage::RequestOk(RequestOk {
5086                parameters: vec![],
5087                track_properties: vec![],
5088            })))
5089            .await
5090            .expect("write REQUEST_OK");
5091        let msg = tokio::time::timeout(PATIENCE, lb.conn.recv_on_request_stream(&mut outbound))
5092            .await
5093            .expect("no REQUEST_OK arrived")
5094            .expect("read REQUEST_OK");
5095        assert!(matches!(msg, ControlMessage::RequestOk(_)), "{msg:?}");
5096
5097        their_send.write_all(&encode(request_update(0))).await.expect("write REQUEST_UPDATE");
5098        let msg = tokio::time::timeout(PATIENCE, lb.conn.recv_on_request_stream(&mut outbound))
5099            .await
5100            .expect("no REQUEST_UPDATE arrived")
5101            .expect("read REQUEST_UPDATE");
5102        assert!(matches!(msg, ControlMessage::RequestUpdate(_)), "{msg:?}");
5103
5104        lb.conn
5105            .respond_ok(&mut outbound, RequestOk { parameters: vec![], track_properties: vec![] })
5106            .await
5107            .expect("the subscriber's update is this endpoint's to answer");
5108        assert!(matches!(next_control(&mut their_recv).await, ControlMessage::RequestOk(_)));
5109
5110        // The publication is untouched by the update and still owes its ending.
5111        assert!(outbound.owes_publish_done());
5112        lb.conn
5113            .publish_done(&mut outbound, v(0), v(0), Vec::new())
5114            .await
5115            .expect("an accepted update leaves the ending free");
5116    }
5117
5118    /// Refusing that update owes the same ending as refusing any other.
5119    ///
5120    /// Section 9.5.1: "When a REQUEST_UPDATE is unsuccessful, the publisher
5121    /// MUST also terminate the subscription by sending a PUBLISH_DONE with
5122    /// error code UPDATE_FAILED." The publisher of a subscription established
5123    /// with PUBLISH is the endpoint that sent it, and the ending goes on the
5124    /// stream that endpoint opened rather than on one the peer opened.
5125    #[tokio::test]
5126    async fn a_refused_update_on_a_publish_we_sent_owes_its_ending() {
5127        let mut lb = loopback().await;
5128
5129        let mut outbound =
5130            lb.conn.publish(ns(), b"video".to_vec(), v(7), vec![], vec![]).await.expect("publish");
5131        let (mut their_send, their_recv) = tokio::time::timeout(PATIENCE, lb.peer.accept_bi())
5132            .await
5133            .expect("the client opened no request stream")
5134            .expect("accept_bi");
5135        let mut their_recv = framed(their_recv);
5136        assert!(matches!(next_control(&mut their_recv).await, ControlMessage::Publish(_)));
5137
5138        their_send
5139            .write_all(&encode(ControlMessage::RequestOk(RequestOk {
5140                parameters: vec![],
5141                track_properties: vec![],
5142            })))
5143            .await
5144            .expect("write REQUEST_OK");
5145        tokio::time::timeout(PATIENCE, lb.conn.recv_on_request_stream(&mut outbound))
5146            .await
5147            .expect("no REQUEST_OK arrived")
5148            .expect("read REQUEST_OK");
5149
5150        their_send.write_all(&encode(request_update(0))).await.expect("write REQUEST_UPDATE");
5151        tokio::time::timeout(PATIENCE, lb.conn.recv_on_request_stream(&mut outbound))
5152            .await
5153            .expect("no REQUEST_UPDATE arrived")
5154            .expect("read REQUEST_UPDATE");
5155
5156        lb.conn
5157            .respond_error(&mut outbound, request_error())
5158            .await
5159            .expect("refuse the subscriber's update");
5160        assert!(matches!(next_control(&mut their_recv).await, ControlMessage::RequestError(_)));
5161        assert!(
5162            outbound.owes_publish_done(),
5163            "a refused update retires nothing: the subscription still owes a PUBLISH_DONE",
5164        );
5165
5166        // The ending is owed under one status, and asking for another leaves
5167        // the publication exactly where it was rather than half ended.
5168        let err = lb
5169            .conn
5170            .publish_done(&mut outbound, v(0), v(0), Vec::new())
5171            .await
5172            .expect_err("a refused update fixes the status of the ending");
5173        assert!(
5174            matches!(
5175                err,
5176                ConnectionError::Endpoint(EndpointError::WrongUpdateFailureStatus {
5177                    request: 0,
5178                    required: 0x8,
5179                })
5180            ),
5181            "{err}",
5182        );
5183        lb.conn
5184            .publish_done(&mut outbound, v(0x8), v(0), Vec::new())
5185            .await
5186            .expect("the termination the refusal owes");
5187        assert!(matches!(next_control(&mut their_recv).await, ControlMessage::PublishDone(_)));
5188    }
5189
5190    /// Draft-21 Section 6.4.2.2 excludes the sender of a PUBLISH from the
5191    /// requesters that "MAY FIN immediately after sending a message", because
5192    /// an accepted PUBLISH makes it the publisher of an Established
5193    /// subscription. A **rejected** one establishes nothing, so the obligation
5194    /// has to end with the REQUEST_ERROR — otherwise the only way to close a
5195    /// refused publication would be to reset the stream, telling the peer the
5196    /// request was abandoned rather than answered.
5197    #[tokio::test]
5198    async fn a_refused_publish_can_still_be_finished_cleanly() {
5199        let mut lb = loopback().await;
5200
5201        let mut outbound =
5202            lb.conn.publish(ns(), b"video".to_vec(), v(7), vec![], vec![]).await.expect("publish");
5203        assert!(outbound.owes_publish_done(), "a PUBLISH sender owes a PUBLISH_DONE");
5204        let err = outbound.finish().await.err();
5205        assert!(
5206            matches!(err, Some(ConnectionError::FinBeforePublishDone(0))),
5207            "a PUBLISH may not be finished while its subscription could still be established: \
5208             {err:?}",
5209        );
5210
5211        let (mut their_send, their_recv) = tokio::time::timeout(PATIENCE, lb.peer.accept_bi())
5212            .await
5213            .expect("the client opened no request stream")
5214            .expect("accept_bi");
5215        let mut their_recv = framed(their_recv);
5216        assert!(matches!(next_control(&mut their_recv).await, ControlMessage::Publish(_)));
5217
5218        their_send
5219            .write_all(&encode(ControlMessage::RequestError(request_error())))
5220            .await
5221            .expect("write REQUEST_ERROR");
5222        let msg = tokio::time::timeout(PATIENCE, lb.conn.recv_on_request_stream(&mut outbound))
5223            .await
5224            .expect("no REQUEST_ERROR arrived")
5225            .expect("a refused PUBLISH is an ordinary response");
5226        assert!(matches!(msg, ControlMessage::RequestError(_)), "{msg:?}");
5227        assert!(!outbound.owes_publish_done());
5228
5229        outbound.finish().await.expect("a refused publication owes nothing further");
5230        drop(outbound);
5231        let end = their_recv.read_control(false).await.expect_err("the stream should have ended");
5232        assert!(
5233            matches!(end, ConnectionError::UnexpectedEnd),
5234            "a refused publication should end with a FIN, not {end}",
5235        );
5236    }
5237
5238    /// A peer that PUBLISHes to us is the publisher, so PUBLISH_DONE arrives
5239    /// on the stream it opened rather than being sent on it. Routing a
5240    /// peer-opened stream's reads through the response dispatcher would look
5241    /// up a request this endpoint never made.
5242    #[tokio::test]
5243    async fn a_peers_publish_is_ended_by_the_peer_on_its_own_stream() {
5244        let mut lb = loopback().await;
5245
5246        let (mut ps, pr) = lb.peer.open_bi().await.expect("open_bi");
5247        ps.write_all(&encode(ControlMessage::Publish(Publish {
5248            request_id: v(1),
5249            track_namespace: ns(),
5250            track_name: b"video".to_vec(),
5251            track_alias: v(7),
5252            parameters: vec![],
5253            track_properties: vec![],
5254        })))
5255        .await
5256        .expect("write PUBLISH");
5257        let mut pr = framed(pr);
5258
5259        let (_, mut stream) = tokio::time::timeout(PATIENCE, lb.conn.accept_request_stream())
5260            .await
5261            .expect("accept hung")
5262            .expect("accept");
5263        assert_eq!(stream.kind(), RequestKind::Publish);
5264
5265        lb.conn
5266            .respond_ok(&mut stream, RequestOk { parameters: vec![], track_properties: vec![] })
5267            .await
5268            .expect("respond_ok");
5269        assert!(matches!(next_control(&mut pr).await, ControlMessage::RequestOk(_)));
5270
5271        ps.write_all(&encode(ControlMessage::PublishDone(PublishDone {
5272            status_code: v(0),
5273            stream_count: v(0),
5274            reason_phrase: Vec::new(),
5275        })))
5276        .await
5277        .expect("write PUBLISH_DONE");
5278
5279        let msg = tokio::time::timeout(PATIENCE, lb.conn.recv_on_request_stream(&mut stream))
5280            .await
5281            .expect("no PUBLISH_DONE arrived")
5282            .expect("the publishing peer may end its own publication");
5283        assert!(matches!(msg, ControlMessage::PublishDone(_)), "{msg:?}");
5284    }
5285}