Skip to main content

moqtap_codec/draft20/
message.rs

1//! Draft-20 control message encoding and decoding.
2//!
3//! Key differences from draft-19:
4//! - **FETCH (0x16) is a different message.** The `Fetch Type` field is gone,
5//!   and with it the Standalone Fetch and Joining Fetch structures and the
6//!   Fetch Type registry. Track Namespace and Track Name are inline fields of
7//!   FETCH, and the range travels in the `LOCATION_FILTER` parameter
8//!   (Section 10.13, Figure 16).
9//! - **PUBLISH_STATE_NOTIFY (0x22) is new** and carries no Request ID
10//!   (Section 10.10, Figure 13).
11//! - **`LOCATION_FILTER` (0x21) has a new value shape.** The Filter Type enum
12//!   is gone; the shape comes from how many `vi64` fields the value holds
13//!   (Section 5.1.2).
14//! - **`FILL_PARAMETERS` (0x23) is new**: a length-prefixed parameter carrying
15//!   a nested parameter block in its own scope (Section 10.2.15).
16//! - **`INCLUDE_PROPERTIES` (0x35) is new**: a uint8 restricted to 0 and 1
17//!   (Section 10.2.21).
18//! - **Parameter applicability moved off `PUBLISH_OK`.** Six definitions
19//!   dropped it and several gained `PUBLISH`; only `EXPIRES` still names it.
20//! - `PUBLISH_DONE`'s `SUBSCRIPTION_ENDED` status (0x3) and `REQUEST_ERROR`'s
21//!   `INVALID_JOINING_REQUEST_ID` (0x32) are unassigned here.
22//! - Section numbering shifted from Section 10.10 on; every reference in this
23//!   module is draft-20's own.
24
25use crate::auth_token::{AuthorizationToken, AUTH_TOKEN_PARAMETER};
26use crate::error::MAX_FULL_TRACK_NAME_LENGTH;
27pub use crate::error::{
28    CodecError, MAX_GOAWAY_URI_LENGTH, MAX_MESSAGE_LENGTH, MAX_NAMESPACE_TUPLE_SIZE,
29    MAX_REASON_PHRASE_LENGTH,
30};
31use crate::kvp::{KeyValuePair, KvpError, KvpValue, MAX_KVP_VALUE_LEN};
32use crate::types::*;
33use crate::varint::{Moqt18 as Wire, VarInt};
34use bytes::{Buf, BufMut};
35
36// ============================================================
37// Parameter encoding helpers for draft-20
38// ============================================================
39
40/// How a parameter value is encoded on the wire.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42enum ParamEncoding {
43    /// Bare varint.
44    Varint,
45    /// Single byte (uint8).
46    Uint8,
47    /// Two consecutive varints (group, object).
48    Location,
49    /// Length-prefixed bytes.
50    LengthPrefixed,
51    /// A Track Namespace as defined in draft-20 Section 2.4.1: a varint field
52    /// count followed by that many length-prefixed fields.
53    ///
54    /// Not one of the four value encodings draft-20 Section 10.2 lists. A
55    /// parameter definition is free to name an encoding from elsewhere in the
56    /// document, and TRACK_NAMESPACE_PREFIX does exactly that; the field count
57    /// is the only length the wire carries.
58    TrackNamespaceValue,
59}
60
61fn param_encoding(key: u64) -> Option<ParamEncoding> {
62    match key {
63        // 0x02 = OBJECT_DELIVERY_TIMEOUT (Section 10.2.4)
64        // 0x04 = RENDEZVOUS_TIMEOUT (Section 10.2.6). Not MAX_CACHE_DURATION:
65        //        that is Property Type 0x04 in the separate Properties
66        //        registry (Section 15.8), a different namespace that happens
67        //        to reuse the number.
68        // 0x06 = SUBGROUP_DELIVERY_TIMEOUT (Section 10.2.3)
69        // 0x08 = EXPIRES (Section 10.2.16, draft-19's 10.2.15)
70        // 0x0A = FILL_TIMEOUT (Section 10.2.5)
71        // 0x32 = NEW_GROUP_REQUEST (Section 10.2.19, draft-19's 10.2.18)
72        0x02 | 0x04 | 0x06 | 0x08 | 0x0A | 0x32 => Some(ParamEncoding::Varint),
73        // 0x10 = FORWARD (Section 10.2.18), 0x20 = SUBSCRIBER_PRIORITY,
74        // 0x22 = GROUP_ORDER, and 0x35 = INCLUDE_PROPERTIES, new in draft-20.
75        // Section 10.2.21: "The INCLUDE_PROPERTIES parameter (Parameter Type
76        // 0x35) is a uint8."
77        0x10 | 0x20 | 0x22 | 0x35 => Some(ParamEncoding::Uint8),
78        // 0x09 = LARGEST_OBJECT. Draft-20 Section 10.2.17: "The LARGEST_OBJECT
79        //        parameter (Parameter Type 0x9) is a Location." A Location is
80        //        two consecutive varints (Section 10.2), with no length ahead
81        //        of them. The type is odd, which on a Key-Value-Pair would mean
82        //        length-prefixed; Message Parameters are not Key-Value-Pairs
83        //        and the odd/even rule does not reach them.
84        0x09 => Some(ParamEncoding::Location),
85        // 0x34 = TRACK_NAMESPACE_PREFIX. Section 10.2.20: it "uses the Track
86        //        Namespace encoding described in Section 2.4.1".
87        0x34 => Some(ParamEncoding::TrackNamespaceValue),
88        // 0x03 = AUTHORIZATION_TOKEN
89        // 0x21 = LOCATION_FILTER, whose value draft-20 rebuilt (Section 5.1.2)
90        // 0x23 = FILL_PARAMETERS, new in draft-20. Section 10.2.15: it "uses
91        //        length-prefixed encoding", and the value is a nested
92        //        parameter block rather than opaque bytes
93        // 0x25 = SUBGROUP_FILTER, 0x26 = OBJECTID_FILTER, 0x27 = PRIORITY_FILTER,
94        // 0x28 = OBJECT_PROPERTY_FILTER, 0x29 = TRACK_PROPERTY_FILTER
95        //        (Range Filters, Section 5.1.4 — draft-19's Section 5.1.3)
96        0x03 | 0x21 | 0x23 | 0x25 | 0x26 | 0x27 | 0x28 | 0x29 => {
97            Some(ParamEncoding::LengthPrefixed)
98        }
99        _ => None,
100    }
101}
102
103/// Whether `value` is inside the range draft-20 allows for a uint8-valued
104/// parameter.
105///
106/// Three of the four uint8 parameters restrict their range and say the receiver
107/// MUST close the session with PROTOCOL_VIOLATION on anything outside it:
108/// GROUP_ORDER allows only Ascending (0x1) and Descending (0x2) (Section
109/// 10.2.8), FORWARD allows only 0 and 1 (Section 10.2.18), and
110/// INCLUDE_PROPERTIES — new in draft-20 — allows only 0 and 1 (Section
111/// 10.2.21). SUBSCRIBER_PRIORITY (Section 10.2.7) uses the whole 0-255 range,
112/// so it has no entry here.
113///
114/// Range-checking on decode is what makes the values usable: an application
115/// that tests `group_order == 2` for descending would otherwise treat 7 as
116/// neither ascending nor descending and carry on.
117fn uint8_value_in_range(key: u64, value: u8) -> bool {
118    match key {
119        // FORWARD (0x10)
120        0x10 => value <= 1,
121        // GROUP_ORDER (0x22)
122        0x22 => value == 1 || value == 2,
123        // INCLUDE_PROPERTIES (0x35), Section 10.2.21: "The allowed values are
124        // 0 (do not send Properties) or 1 (send Properties), and the default
125        // is 1. If an endpoint receives a value outside this range, it MUST
126        // close the session with PROTOCOL_VIOLATION."
127        0x35 => value <= 1,
128        _ => true,
129    }
130}
131
132/// AUTHORIZATION TOKEN, Parameter Type 0x03.
133const AUTHORIZATION_TOKEN: u64 = 0x03;
134
135/// Whether draft-20 lets a message carry parameter type `key` more than once.
136///
137/// Section 10.2 states the default: "Senders MUST NOT repeat the same Parameter
138/// Type in a message unless the parameter definition explicitly allows multiple
139/// instances of that type to be sent in a single message." Two definitions do.
140///
141/// * `AUTHORIZATION_TOKEN` (0x03), Section 10.2.2: "The AUTHORIZATION TOKEN
142///   parameter MAY be repeated within a message as long as the combination of
143///   Token Type and Token Value are unique after resolving any aliases."
144/// * The five Range Filters (0x25 through 0x29), Section 5.1.4 — draft-19's
145///   5.1.3: "The Track Property filter parameter MAY appear multiple times in a
146///   SUBSCRIBE_TRACKS message or REQUEST_UPDATE for it. All other filter
147///   parameters MAY appear multiple times in a FETCH, SUBSCRIBE,
148///   SUBSCRIBE_TRACKS, or REQUEST_UPDATE (on a subscription, from the subscriber
149///   only) message."
150///
151/// # A zero `Type Delta` is "the same type again", not an error
152///
153/// The two rules interact, and **the draft does not say how**. Section 10.2 also
154/// requires that "Parameters MUST be serialized in ascending order by Type", so
155/// a second instance of a repeatable type produces a `Type Delta` of 0 — well
156/// formed only if the decoder reads a zero delta as a repeat rather than as a
157/// malformation. That reading is the one taken here; the alternative makes
158/// Section 5.1.4's permission unusable, because there is no other encoding for
159/// a second filter of the same type.
160///
161/// What the filters may **not** do is repeat the same (Parameter Type, SetID,
162/// Property Type) triple, and Section 5.1.4 answers that with a REQUEST_ERROR
163/// carrying INVALID_FILTER rather than with a session close. A reply an endpoint
164/// sends is not a frame a decoder refuses, so nothing here enforces it — see
165/// [`crate::range_filter`] for the reader an endpoint uses to decide.
166fn parameter_may_repeat(key: u64) -> bool {
167    matches!(key, AUTHORIZATION_TOKEN | 0x25..=0x29)
168}
169
170/// Add a delta to the previous delta-encoded key.
171///
172/// Draft-20 Section 1.4.3: "The previous Type value plus the Delta Type MUST NOT
173/// be greater than 2^64 - 1. If a Delta Type is received that would be too
174/// large, the Session MUST be closed with a PROTOCOL_VIOLATION." MoQT varints
175/// span the whole 64-bit range, so a peer can drive the sum past the end: an
176/// unchecked addition panics in a debug build, and in a release build wraps the
177/// key and reports the parameter under a type its sender never wrote.
178fn add_delta(prev_key: u64, delta: u64) -> Result<u64, CodecError> {
179    prev_key.checked_add(delta).ok_or(CodecError::KeyDeltaOverflow(prev_key, delta))
180}
181
182/// Hold a namespace-plus-name pair to the Full Track Name cap.
183///
184/// Draft-20 Section 2.4.1: "The maximum total length of a Full Track Name is
185/// 4,096 bytes. The length of a Full Track Name is computed as the sum of the
186/// Track Namespace Field Length fields and the Track Name Length field... If an
187/// endpoint receives a Track Namespace or a Full Track Name exceeding 4,096
188/// bytes, it MUST close the session with a PROTOCOL_VIOLATION."
189///
190/// The namespace half of that sentence is enforced inside the namespace decoder,
191/// which is the only place that sees a namespace with no name beside it. This is
192/// the other half, and it has to live where the two are decoded together: a
193/// namespace at 4,000 bytes and a name at 500 are each legal alone.
194fn check_full_track_name(namespace: &TrackNamespace, track_name: &[u8]) -> Result<(), CodecError> {
195    let total = namespace.field_bytes_len().saturating_add(track_name.len());
196    if total > MAX_FULL_TRACK_NAME_LENGTH {
197        return Err(CodecError::TrackNameTooLong);
198    }
199    Ok(())
200}
201
202/// Hold every AUTHORIZATION TOKEN parameter to the Token structure it names.
203///
204/// Section 10.2.2: "If the Token structure cannot be decoded, the receiver
205/// MUST close the Session with KEY_VALUE_FORMATTING_ERROR." That is the answer
206/// Section 1.4.3 gives for any Type whose value does not match the
207/// serialization that Type defines; the Token is the one structure this draft
208/// spells out, and the only parameter value in it that is more than opaque
209/// bytes.
210///
211/// Both namespaces carry the type on this draft, and both reach here.
212///
213/// A type this draft cannot name is left alone. The rule is conditional on the
214/// receiver understanding the Type, and an extension's parameter carries bytes
215/// no rule here describes.
216fn check_authorization_tokens(parameters: &[KeyValuePair]) -> Result<(), CodecError> {
217    for parameter in parameters {
218        let key = parameter.key.into_inner();
219        if key != AUTH_TOKEN_PARAMETER {
220            continue;
221        }
222        match &parameter.value {
223            KvpValue::Bytes(value) => {
224                AuthorizationToken::decode_moqt::<Wire>(key, value)?;
225            }
226            // Unreachable from the decoder, which picks the shape from the
227            // type and finds this one length-prefixed. A caller that built the
228            // pair in memory can still get here, and it is the same rule: the
229            // value is not the serialization the type defines.
230            KvpValue::Varint(_) => {
231                return Err(CodecError::KeyValueFormatting {
232                    key,
233                    detail: "its value is a bare varint where the type defines a Token structure",
234                });
235            }
236        }
237    }
238    Ok(())
239}
240
241/// The LOCATION_FILTER parameter type, draft-20 Section 10.2.9.
242pub const LOCATION_FILTER: u64 = 0x21;
243
244/// The FILL_PARAMETERS parameter type, draft-20 Section 10.2.15. New in
245/// draft-20.
246pub const FILL_PARAMETERS: u64 = 0x23;
247
248/// The most `vi64` fields a `LOCATION_FILTER` value can hold: `StartGroup`,
249/// `StartObject`, `EndGroupDelta`, `EndObject` (draft-20 Section 5.1.2).
250const LOCATION_FILTER_MAX_FIELDS: usize = 4;
251
252/// The parameter types draft-20 Section 10.2.15, Table 6 permits inside a
253/// `FILL_PARAMETERS` value, in ascending order.
254///
255/// `TRACK_PROPERTY_FILTER` (0x29) is deliberately absent: a fill applies to one
256/// already-selected track, so a filter that selects tracks has nothing to do
257/// there. The draft does not say that in as many words, but it does say what
258/// happens to one that arrives anyway — "An endpoint that receives a parameter
259/// inside FILL_PARAMETERS that is not listed above MUST close the session with
260/// PROTOCOL_VIOLATION" — which is what makes the omission load-bearing rather
261/// than editorial. A relay forwarding a downstream `FILL_PARAMETERS` upstream
262/// has to strip it rather than pass it on.
263const FILL_PARAMETERS_ALLOWED: &[u64] = &[0x0A, 0x20, 0x21, 0x22, 0x25, 0x26, 0x27, 0x28];
264
265/// Decode the `vi64` fields of a draft-20 `LOCATION_FILTER` value.
266///
267/// Returns between zero and four values, in the wire order `StartGroup`,
268/// `StartObject`, `EndGroupDelta`, `EndObject`. Which of the five shapes the
269/// filter is comes from how many came back; draft-20 Section 5.1.2 gives the
270/// table.
271///
272/// # The field count comes from parsing, never from the byte length
273///
274/// The draft says "Length (in bytes) determines how many optional vi64 fields
275/// are present", and that is not implementable as written. MoQT varints are one
276/// to nine bytes wide and Section 1.4.1 permits non-minimal encodings, so a
277/// `Length` of 2 is equally consistent with two one-byte fields and one two-byte
278/// field. **This codec decodes `vi64` values until exactly `Length` bytes have
279/// been consumed and then switches on the count.** That is the only rule that
280/// round-trips, and it is a decision this codec makes: the draft states the
281/// byte-length reading and no other.
282///
283/// Two corollaries follow that the draft also does not state, and both are
284/// chosen here:
285///
286/// * a field that would run past `Length` makes the parameter malformed, rather
287///   than being truncated or read from the bytes after the parameter;
288/// * more than four decoded values makes it malformed, because Section 5.1.2
289///   defines shapes for zero through four and nothing beyond.
290///
291/// A decoder that switched on the byte length would notice neither.
292pub fn decode_location_filter(value: &[u8]) -> Result<Vec<u64>, CodecError> {
293    let mut fields: Vec<u64> = Vec::with_capacity(LOCATION_FILTER_MAX_FIELDS);
294    let mut cursor = value;
295    while cursor.has_remaining() {
296        if fields.len() == LOCATION_FILTER_MAX_FIELDS {
297            return Err(CodecError::SubscriptionFilterMalformed {
298                detail: "it holds more than the four vi64 fields Section 5.1.2 defines",
299            });
300        }
301        // The slice is already bounded by the parameter's Length, so a varint
302        // that wants more bytes than remain is one that would have run past it.
303        let field = VarInt::decode_moqt::<Wire>(&mut cursor).map_err(|_| {
304            CodecError::SubscriptionFilterMalformed {
305                detail: "a field runs past the end of the parameter's Length",
306            }
307        })?;
308        fields.push(field.into_inner());
309    }
310    Ok(fields)
311}
312
313/// Hold a decoded `LOCATION_FILTER` to the one arithmetic rule draft-20 states
314/// about it.
315///
316/// Section 5.1.2: "EndGroupDelta is delta encoded from StartGroup, but both the
317/// start and end groups are absolute, not relative to Largest Object. If
318/// StartGroup + EndGroupDelta exceeds 2^64 - 1, the endpoint MUST close the
319/// session with a PROTOCOL_VIOLATION." The sum only exists once three or four
320/// fields are present, so the shorter shapes have nothing to check.
321///
322/// There is deliberately no check that the end is at or after the start.
323/// `EndGroupDelta` is unsigned and added to `StartGroup`, so the end group can
324/// never precede the start group; and within one group draft-20 states no rule
325/// about `EndObject` being below `StartObject`. Section 5.1.2 says the opposite
326/// for subscriptions — "A Location Filter on a subscription is always valid,
327/// even if it specifies a range entirely before Largest Object" — so refusing
328/// one would close sessions over a sentence that is not there.
329fn check_location_filter_fields(fields: &[u64]) -> Result<(), CodecError> {
330    if fields.len() < 3 {
331        return Ok(());
332    }
333    let start_group = fields[0];
334    let delta = fields[2];
335    if start_group.checked_add(delta).is_none() {
336        return Err(CodecError::FilterEndGroupOverflow { start_group, delta });
337    }
338    Ok(())
339}
340
341/// Decode the nested parameter block a `FILL_PARAMETERS` value carries.
342///
343/// # The value begins with a `Number of Parameters` count
344///
345/// Section 10.2.15 says the value is "a sequence of Parameters that apply to
346/// the fill fetch stream" and is "encoded as if they were Parameters for a
347/// separate message", and stops there. **This codec reads that as the
348/// full block, count included.** The draft does not state it either way, and the
349/// wrong choice desynchronises the whole outer parameter list rather than
350/// producing a recognisable error, so it is worth naming: Section 10.2 defines a
351/// parameter block as count-bounded — "Because unknown parameters cannot be
352/// skipped, the block is bounded by a parameter count rather than a length" —
353/// and the phrase *Parameters for a message* denotes that block everywhere else
354/// in Section 10. The outer length prefix is the generic length-prefixed value
355/// encoding every such parameter gets and says nothing about the value's
356/// internal structure.
357///
358/// So an empty `FILL_PARAMETERS` — the common case, a fill with every setting
359/// inherited from the subscription — is `Length = 1` carrying the single byte
360/// `0x00`, and **not** `Length = 0`.
361///
362/// # The `Type Delta` chain restarts here, and the outer chain is unaffected
363///
364/// Section 10.2.15: "The value of FILL_PARAMETERS is a separate parameter
365/// scope. Parameters inside it are not considered to appear in the enclosing
366/// message for the purposes of Section 10.2, so a Parameter Type MAY appear
367/// both in the message and inside FILL_PARAMETERS." Section 10.2 defines
368/// `Type Delta` as the difference from "the previous Parameter Type in the
369/// message", and a separate scope is not the message — so the inner chain
370/// starts from 0, and the outer parameter after `FILL_PARAMETERS` deltas from
371/// `0x23` rather than from the last inner type. **The draft states neither
372/// half explicitly**; both are decided here.
373///
374/// # What it refuses
375///
376/// A type outside Table 6 is [`CodecError::ParameterOutOfScope`], reported
377/// against `FILL_PARAMETERS` itself because the nested scope is the "message"
378/// the parameter appeared in. A type draft-20 does not define at all is
379/// [`CodecError::UnknownMessageParameter`], checked first so an unknown type is
380/// not reported as a known one in the wrong place.
381pub fn decode_fill_parameters(value: &[u8]) -> Result<Vec<KeyValuePair>, CodecError> {
382    let mut cursor = value;
383    let count = VarInt::decode_moqt::<Wire>(&mut cursor)?.into_inner() as usize;
384    let mut params = crate::types::reserve_bounded(count, &cursor);
385    // A separate scope, so the chain starts from 0 exactly as a message's does.
386    let mut prev_key: u64 = 0;
387
388    for i in 0..count {
389        let delta = VarInt::decode_moqt::<Wire>(&mut cursor)?.into_inner();
390        let abs_key = add_delta(prev_key, delta)?;
391        if i > 0 && delta == 0 && !parameter_may_repeat(abs_key) {
392            return Err(CodecError::DuplicateParameter(abs_key));
393        }
394        prev_key = abs_key;
395
396        let encoding =
397            param_encoding(abs_key).ok_or(CodecError::UnknownMessageParameter(abs_key))?;
398        if !FILL_PARAMETERS_ALLOWED.contains(&abs_key) {
399            return Err(CodecError::ParameterOutOfScope {
400                key: abs_key,
401                message_type: FILL_PARAMETERS,
402            });
403        }
404
405        let value = decode_parameter_value(encoding, abs_key, &mut cursor)?;
406        params.push(KeyValuePair { key: VarInt::from_u64_moqt(abs_key), value });
407    }
408
409    // The block is count-bounded and the parameter is length-bounded, and the
410    // two have to agree. Bytes left over mean the count was short of what the
411    // sender wrote, which is the same disagreement a control message's Length
412    // field can have with its body.
413    if cursor.has_remaining() {
414        return Err(CodecError::SubscriptionFilterMalformed {
415            detail: "its parameter count leaves bytes unread inside FILL_PARAMETERS",
416        });
417    }
418    check_location_filters(&params)?;
419    Ok(params)
420}
421
422/// Hold every LOCATION_FILTER and FILL_PARAMETERS parameter to the structure
423/// its own type names.
424///
425/// Applied on both sides. A value the decoder refuses is one the peer must
426/// close the session over, so writing it is a way to end a session rather than
427/// a way to ask for anything.
428///
429/// The two are checked together because `FILL_PARAMETERS` can carry a
430/// `LOCATION_FILTER` of its own, and a filter that is malformed one level down
431/// is exactly as malformed. [`decode_fill_parameters`] recurses back into this
432/// function for that reason; the nesting bottoms out because Table 6 does not
433/// list `FILL_PARAMETERS` inside itself.
434///
435/// The values are otherwise decoded and discarded. What is kept is the refusal
436/// — each stays on its parameter as the bytes that arrived, so a caller reads
437/// one through [`decode_location_filter`] or [`decode_fill_parameters`] when it
438/// wants the structure rather than the frame.
439fn check_location_filters(parameters: &[KeyValuePair]) -> Result<(), CodecError> {
440    for parameter in parameters {
441        let key = parameter.key.into_inner();
442        if key != LOCATION_FILTER && key != FILL_PARAMETERS {
443            continue;
444        }
445        match &parameter.value {
446            KvpValue::Bytes(value) if key == LOCATION_FILTER => {
447                check_location_filter_fields(&decode_location_filter(value)?)?;
448            }
449            KvpValue::Bytes(value) => {
450                decode_fill_parameters(value)?;
451            }
452            // Unreachable from the decoder, which picks the shape from the type
453            // and finds both of these length-prefixed. A caller that built the
454            // pair in memory can still get here, and it is the same rule.
455            KvpValue::Varint(_) => {
456                return Err(CodecError::SubscriptionFilterMalformed {
457                    detail: "its value is a bare varint where the type defines a structure",
458                });
459            }
460        }
461    }
462    Ok(())
463}
464
465/// Read one parameter's value in the shape its type names.
466///
467/// Shared by the message's own parameter block and by the nested block inside
468/// `FILL_PARAMETERS`, so a type cannot be read one way in a message and another
469/// way in a fill.
470fn decode_parameter_value(
471    encoding: ParamEncoding,
472    abs_key: u64,
473    buf: &mut impl Buf,
474) -> Result<KvpValue, CodecError> {
475    Ok(match encoding {
476        ParamEncoding::Varint => KvpValue::Varint(VarInt::decode_moqt::<Wire>(buf)?),
477        ParamEncoding::Uint8 => {
478            if buf.remaining() < 1 {
479                return Err(CodecError::UnexpectedEnd);
480            }
481            let byte = buf.get_u8();
482            if !uint8_value_in_range(abs_key, byte) {
483                return Err(CodecError::ParameterValueOutOfRange {
484                    key: abs_key,
485                    value: byte as u64,
486                });
487            }
488            KvpValue::Varint(VarInt::from_u64_moqt(byte as u64))
489        }
490        ParamEncoding::Location => {
491            let group = VarInt::decode_moqt::<Wire>(buf)?;
492            let object = VarInt::decode_moqt::<Wire>(buf)?;
493            let mut encoded = Vec::new();
494            group.encode_moqt::<Wire>(&mut encoded);
495            object.encode_moqt::<Wire>(&mut encoded);
496            KvpValue::Bytes(encoded)
497        }
498        ParamEncoding::LengthPrefixed => {
499            let len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
500            KvpValue::Bytes(read_bytes(buf, len)?)
501        }
502        ParamEncoding::TrackNamespaceValue => {
503            // A prefix of zero fields is legal: Section 2.4.1 puts a Track
504            // Namespace at "between 0 and 32 Track Namespace Fields", and
505            // an empty prefix matches every namespace.
506            let ns = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
507            let mut encoded = Vec::new();
508            ns.encode_moqt::<Wire>(&mut encoded);
509            KvpValue::Bytes(encoded)
510        }
511    })
512}
513
514/// Decode a count-prefixed list of parameters with delta-encoded types.
515fn decode_parameters(buf: &mut impl Buf) -> Result<Vec<KeyValuePair>, CodecError> {
516    let count = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
517    let mut params = crate::types::reserve_bounded(count, buf);
518    let mut prev_key: u64 = 0;
519
520    for i in 0..count {
521        let delta = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
522        let abs_key = add_delta(prev_key, delta)?;
523        // Types ascend, so a repeat is always a zero delta against the
524        // parameter before it. Draft-20 Section 10.2: "Receivers SHOULD check
525        // that there are no unexpected duplicate parameters and close the
526        // session with PROTOCOL_VIOLATION if found." Downstream code that scans
527        // the list for a key takes whichever copy it meets first, so two
528        // implementations reading one frame can pick opposite values.
529        //
530        // "Unexpected" is what `parameter_may_repeat` reads: a zero delta on a
531        // type whose own definition permits repeats is the second instance,
532        // which is the only encoding such an instance has.
533        if i > 0 && delta == 0 && !parameter_may_repeat(abs_key) {
534            return Err(CodecError::DuplicateParameter(abs_key));
535        }
536        prev_key = abs_key;
537
538        // Section 10.2: "All Message Parameters MUST be defined in the
539        // negotiated version of MOQT or negotiated via Setup Options. An
540        // endpoint that receives an unknown Message Parameter MUST close the
541        // session with PROTOCOL_VIOLATION. Because the receiver has to
542        // understand every Message Parameter, there is no need for a mechanism
543        // to skip unknown parameters." Because unknown parameters
544        // cannot be skipped, the block is bounded by a parameter count rather
545        // than a length.
546        //
547        // The table this consults is the registry's, so a type it cannot name
548        // is one this draft does not define. Reporting it as an ordinary
549        // malformation would leave the rule enforced against the frame and
550        // invisible to the session.
551        let encoding =
552            param_encoding(abs_key).ok_or(CodecError::UnknownMessageParameter(abs_key))?;
553
554        let value = decode_parameter_value(encoding, abs_key, buf)?;
555
556        params.push(KeyValuePair { key: VarInt::from_u64_moqt(abs_key), value });
557    }
558    check_authorization_tokens(&params)?;
559    check_location_filters(&params)?;
560    Ok(params)
561}
562
563/// Whether `bytes` is exactly the wire form of a Location — two consecutive
564/// varints and nothing after them.
565///
566/// `decode_parameters` builds this value by reading two varints and
567/// re-serialising them, so every value it produces satisfies this. A value
568/// built in memory need not, and the encode arm writes these bytes verbatim
569/// because a Location carries no length of its own. Without this check a
570/// caller could hand over one varint, or three, and the codec would put a
571/// frame on the wire that its own decoder answers with an error.
572fn is_location_value(bytes: &[u8]) -> bool {
573    let mut buf = bytes;
574    VarInt::decode_moqt::<Wire>(&mut buf).is_ok()
575        && VarInt::decode_moqt::<Wire>(&mut buf).is_ok()
576        && !buf.has_remaining()
577}
578
579/// Whether `bytes` is exactly the wire form of a Track Namespace, with
580/// nothing after it. The same reasoning as [`is_location_value`]: the value
581/// goes out verbatim, so it has to be something this draft can read back.
582fn is_track_namespace_value(bytes: &[u8]) -> bool {
583    let mut buf = bytes;
584    TrackNamespace::decode_allow_empty_moqt::<Wire>(&mut buf).is_ok() && !buf.has_remaining()
585}
586
587/// Encode a count-prefixed list of parameters with delta-encoded types.
588///
589/// Errors with [`CodecError::InvalidField`] on a uint8-valued parameter whose
590/// value [`decode_parameters`] would refuse, so the two directions accept the
591/// same set of frames.
592///
593/// The check is not a mirror added for tidiness. A uint8 parameter's value is
594/// written as one octet, and a value that does not fit one is otherwise
595/// truncated to its low byte: GROUP_ORDER 258 becomes the byte 0x02, which is
596/// Descending — a well-formed frame carrying a value the caller never asked
597/// for, and one no receiver could tell from a genuine Descending. Refusing is
598/// the only outcome that does not silently rewrite the message.
599///
600/// The two structure rules are here for a plainer reason. A value under a type
601/// that defines a structure and is not that structure — a Token, a filter — is
602/// one the receiver must close the session over, so writing it is not a way to
603/// send it; the sender's first sign of trouble would be the session going.
604fn encode_parameters(params: &[KeyValuePair], buf: &mut impl BufMut) -> Result<(), CodecError> {
605    check_authorization_tokens(params)?;
606    check_location_filters(params)?;
607    VarInt::from_usize(params.len()).encode_moqt::<Wire>(buf);
608    let mut prev_key: u64 = 0;
609
610    for (i, p) in params.iter().enumerate() {
611        let abs_key = p.key.into_inner();
612        // The delta is a difference, so a descending pair wraps the subtraction
613        // into a nine-byte delta the peer resolves to an unrelated key, and a
614        // repeated type is a frame `decode_parameters` refuses. Both are
615        // refused here so the two directions accept the same set of frames.
616        let delta = abs_key
617            .checked_sub(prev_key)
618            .ok_or(CodecError::ParametersOutOfOrder(prev_key, abs_key))?;
619        if i > 0 && delta == 0 && !parameter_may_repeat(abs_key) {
620            return Err(CodecError::DuplicateParameter(abs_key));
621        }
622        prev_key = abs_key;
623        VarInt::from_u64_moqt(delta).encode_moqt::<Wire>(buf);
624
625        // The same maximum the decoder below applies, and the same one this
626        // draft's Setup Option encoder has always applied: "The maximum length
627        // of a value is 2^16-1 bytes. If an endpoint receives a length larger
628        // than the maximum, it MUST close the session with a PROTOCOL_VIOLATION."
629        // A value past it is one the peer must end the session over, so writing
630        // it is not a way to send it.
631        //
632        // Hoisted above the shape table rather than repeated inside it: a
633        // Location is bytes as well, and one past the maximum is not a Location.
634        if let KvpValue::Bytes(b) = &p.value {
635            if b.len() > MAX_KVP_VALUE_LEN {
636                return Err(KvpError::ValueTooLong(b.len()).into());
637            }
638        }
639
640        let encoding = param_encoding(abs_key);
641        match (&p.value, encoding) {
642            (KvpValue::Varint(v), Some(ParamEncoding::Varint)) => {
643                v.encode_moqt::<Wire>(buf);
644            }
645            (KvpValue::Varint(v), Some(ParamEncoding::Uint8)) => {
646                let raw = v.into_inner();
647                let byte = u8::try_from(raw).map_err(|_| CodecError::InvalidField)?;
648                if !uint8_value_in_range(abs_key, byte) {
649                    return Err(CodecError::ParameterValueOutOfRange {
650                        key: abs_key,
651                        value: byte as u64,
652                    });
653                }
654                buf.put_u8(byte);
655            }
656            // Both values are already stored in their own wire form — two
657            // varints for a Location, a field count and its fields for a Track
658            // Namespace — so they go out as they are. Adding a length here is
659            // the bug these arms exist to avoid.
660            (KvpValue::Bytes(b), Some(ParamEncoding::Location)) => {
661                if !is_location_value(b) {
662                    return Err(CodecError::InvalidField);
663                }
664                buf.put_slice(b);
665            }
666            (KvpValue::Bytes(b), Some(ParamEncoding::TrackNamespaceValue)) => {
667                if !is_track_namespace_value(b) {
668                    return Err(CodecError::InvalidField);
669                }
670                buf.put_slice(b);
671            }
672            (KvpValue::Bytes(b), Some(ParamEncoding::LengthPrefixed)) => {
673                VarInt::from_usize(b.len()).encode_moqt::<Wire>(buf);
674                buf.put_slice(b);
675            }
676            _ => {
677                // Fallback: encode as KVP even/odd
678                match &p.value {
679                    KvpValue::Varint(v) => v.encode_moqt::<Wire>(buf),
680                    KvpValue::Bytes(b) => {
681                        VarInt::from_usize(b.len()).encode_moqt::<Wire>(buf);
682                        buf.put_slice(b);
683                    }
684                }
685            }
686        }
687    }
688    Ok(())
689}
690
691/// Decode delta-encoded KVPs with even/odd convention (for setup options
692/// and track properties). Read until buffer is exhausted.
693fn decode_kvp_delta(buf: &mut impl Buf) -> Result<Vec<KeyValuePair>, CodecError> {
694    let mut pairs = Vec::new();
695    let mut prev_key: u64 = 0;
696
697    while buf.has_remaining() {
698        let delta = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
699        let abs_key = add_delta(prev_key, delta)?;
700        prev_key = abs_key;
701
702        let value = if abs_key.is_multiple_of(2) {
703            let v = VarInt::decode_moqt::<Wire>(buf)?;
704            KvpValue::Varint(v)
705        } else {
706            let len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
707            // Draft-20 Section 1.4.3: "The maximum length of a value is 2^16-1
708            // bytes. If an endpoint receives a length larger than the maximum,
709            // it MUST close the session with a PROTOCOL_VIOLATION." The
710            // standalone `KeyValuePair::decode` already enforces this; stating
711            // it here too means the two readers of the same wire shape answer
712            // the same way, rather than this one leaning on the caller having
713            // clipped the buffer to a control message first.
714            if len > MAX_KVP_VALUE_LEN {
715                return Err(KvpError::ValueTooLong(len).into());
716            }
717            let data = read_bytes(buf, len)?;
718            KvpValue::Bytes(data)
719        };
720
721        pairs.push(KeyValuePair { key: VarInt::from_u64_moqt(abs_key), value });
722    }
723    Ok(pairs)
724}
725
726/// Encode delta-encoded KVPs with even/odd convention.
727///
728/// Refuses a list that is not in ascending order by type, for the same reason
729/// [`encode_parameters`] does: the delta is a difference, and a descending pair
730/// wraps it into a nine-byte delta the peer resolves to an unrelated key.
731fn encode_kvp_delta(pairs: &[KeyValuePair], buf: &mut impl BufMut) -> Result<(), CodecError> {
732    let mut prev_key: u64 = 0;
733    for p in pairs {
734        let abs_key = p.key.into_inner();
735        let delta = abs_key
736            .checked_sub(prev_key)
737            .ok_or(CodecError::ParametersOutOfOrder(prev_key, abs_key))?;
738        prev_key = abs_key;
739        VarInt::from_u64_moqt(delta).encode_moqt::<Wire>(buf);
740        match &p.value {
741            KvpValue::Varint(v) => v.encode_moqt::<Wire>(buf),
742            KvpValue::Bytes(b) => {
743                if b.len() > MAX_KVP_VALUE_LEN {
744                    return Err(KvpError::ValueTooLong(b.len()).into());
745                }
746                VarInt::from_usize(b.len()).encode_moqt::<Wire>(buf);
747                buf.put_slice(b);
748            }
749        }
750    }
751    Ok(())
752}
753
754/// Immutable Properties, Property Type 0xB.
755///
756/// Section 12.7: Immutable Properties are "a Track or Object Property that
757/// contains a sequence of Key-Value-Pairs (see Figure 2) that are themselves
758/// Track or Object Properties, respectively". The Type is odd, so its value is
759/// length-prefixed bytes, and those bytes are another delta-typed run starting
760/// from 0.
761const IMMUTABLE_PROPERTIES: u64 = 0x0B;
762
763/// Whether `value` is inside the range draft-20 allows for a Track Property
764/// type that restricts one.
765///
766/// Two types do, and each answers anything outside its range with a session
767/// close. DEFAULT_PUBLISHER_GROUP_ORDER (0x22), Section 12.5: "The allowed
768/// values are Ascending (0x1) or Descending (0x2). If an endpoint receives a
769/// value outside this range, it MUST close the session with
770/// PROTOCOL_VIOLATION." DYNAMIC_GROUPS (0x30), Section 12.6: "The allowed
771/// values are 0 or 1... If an endpoint receives a value larger than 1, it MUST
772/// close the session with PROTOCOL_VIOLATION."
773///
774/// Both are Track Properties, so the list they arrive in is the one carried by
775/// a control message rather than the properties on an object.
776///
777/// DEFAULT_PUBLISHER_PRIORITY (0x0E) is not here. Section 12.4 says
778/// "Priorities above 255 are invalid" and stops, where the two above name a
779/// consequence in the next clause. A range stated without one is not a close.
780///
781/// The numbers belong to the Property registry and not the Message Parameter
782/// one. Type 0x22 is GROUP_ORDER as a parameter and
783/// DEFAULT_PUBLISHER_GROUP_ORDER as a property, and the two happen to permit the
784/// same pair of values while meaning different things — one subscriber's
785/// preference against a property of the track. Reading either table for the
786/// other's types would be right by accident here and wrong at the next entry.
787fn track_property_value_in_range(key: u64, value: u64) -> bool {
788    match key {
789        // DEFAULT_PUBLISHER_GROUP_ORDER (0x22)
790        0x22 => value == 1 || value == 2,
791        // DYNAMIC_GROUPS (0x30)
792        0x30 => value <= 1,
793        _ => true,
794    }
795}
796
797/// Refuse a Track Property whose value falls outside the range its type allows,
798/// wherever in the list it is carried.
799///
800/// # Inside Immutable Properties as well as beside them
801///
802/// The list is walked one level down through Immutable Properties, whose
803/// contents Section 12.7 defines as properties themselves. The draft asks for
804/// this in as many words: "When looking for the value of a property, processors
805/// MUST search both the mutable properties and the contents of Immutable
806/// Properties." A check applied only to the outer list is one a peer opts out of
807/// by moving a pair inside the block, and the block is where an Original
808/// Publisher puts what a relay must not rewrite — which is where a track's group
809/// order and dynamic-group support belong.
810///
811/// Bytes under 0xB that do not parse as a Key-Value-Pair run are left alone
812/// rather than refused. Section 12.7 says relays "MAY decode and view the
813/// Properties in the Key-Value-Pairs", which is a permission and not a
814/// requirement, so a block this codec cannot read is carried to the caller
815/// intact instead of ending the session.
816fn check_track_property_values(properties: &[KeyValuePair]) -> Result<(), CodecError> {
817    for property in properties {
818        let key = property.key.into_inner();
819        match &property.value {
820            KvpValue::Varint(value) => {
821                let value = value.into_inner();
822                if !track_property_value_in_range(key, value) {
823                    return Err(CodecError::TrackPropertyValueOutOfRange { key, value });
824                }
825            }
826            KvpValue::Bytes(bytes) if key == IMMUTABLE_PROPERTIES => {
827                let mut inner = &bytes[..];
828                // A block that is not a Key-Value-Pair run is skipped rather
829                // than refused. See the note above: reading inside it is a
830                // permission, so one that cannot be read is carried.
831                //
832                // Skipped means this block and only this block. The rule the
833                // draft states here is about the block whose pairs will not
834                // parse, and says nothing about its neighbours; ending the
835                // whole walk would let a peer keep an out-of-range property
836                // from being looked at by putting an unparseable block in
837                // front of it.
838                if let Ok(nested) = decode_kvp_delta(&mut inner) {
839                    check_track_property_values(&nested)?;
840                }
841            }
842            KvpValue::Bytes(_) => {}
843        }
844    }
845    Ok(())
846}
847
848/// Decode the Track Properties that fill the tail of a control message.
849///
850/// [`decode_kvp_delta`] with the Property registry's value rules applied. The
851/// two are separate because that function also reads Setup Options, which are a
852/// third namespace numbering its entries independently of this one.
853fn decode_track_properties(buf: &mut impl Buf) -> Result<Vec<KeyValuePair>, CodecError> {
854    let properties = decode_kvp_delta(buf)?;
855    check_track_property_values(&properties)?;
856    Ok(properties)
857}
858
859/// Encode a control message's Track Properties.
860///
861/// Held to the same value ranges as the decoder. A value this codec refuses to
862/// read is one it must not write: the peer that receives it is required to close
863/// the session, so the sender's first sign of trouble would be the session
864/// going.
865fn encode_track_properties(
866    properties: &[KeyValuePair],
867    buf: &mut impl BufMut,
868) -> Result<(), CodecError> {
869    check_track_property_values(properties)?;
870    encode_kvp_delta(properties, buf)
871}
872
873/// The Setup Option types this draft defines.
874///
875/// Section 10.3.1 assigns PATH, AUTHORIZATION TOKEN, MAX_AUTH_TOKEN_CACHE_SIZE, AUTHORITY,
876/// MAX_FILTER_RANGES, MOQT_IMPLEMENTATION and MAX_REQUEST_UPDATES.
877///
878/// The list exists for one rule and one direction. Section 10.3: "Receivers
879/// MUST allow duplicates of unknown Setup Options." A receiver may therefore
880/// refuse a repeat only of a type it can name, and an option outside this list
881/// is one an extension defined and this codec has no business closing a session
882/// over. Nothing else reads it - unknown options are still decoded and carried,
883/// as "Receivers MUST ignore unrecognized Setup Options" requires.
884const KNOWN_SETUP_OPTIONS: &[u64] = &[0x01, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
885
886/// The one Setup Option whose definition allows more than one instance.
887///
888/// Section 10.3.1.4: "The AUTHORIZATION TOKEN Setup Option (Option Type 0x03)
889/// is functionally equivalent to the AUTHORIZATION TOKEN message parameter...
890/// The endpoint can specify one or more tokens in SETUP that the peer can use to
891/// authorize MOQT session establishment." That is the "unless the option
892/// definition explicitly allows multiple instances" carve-out, and it is the
893/// only one on this draft.
894const REPEATABLE_SETUP_OPTION: u64 = 0x03;
895
896/// Decode the Setup Options of a SETUP message.
897///
898/// Section 10.3: "Senders MUST NOT repeat the same Option Type in a message
899/// unless the option definition explicitly allows multiple instances. Receivers
900/// MUST allow duplicates of unknown Setup Options."
901///
902/// The second sentence is why this is not the mirror of
903/// [`encode_setup_options`]: a repeat of a type this draft names is refused, and
904/// a repeat of any other type is carried. Types ascend and are delta-encoded, so
905/// a repeat is always a zero delta against the option before it.
906fn decode_setup_options(buf: &mut impl Buf) -> Result<Vec<KeyValuePair>, CodecError> {
907    let options = decode_kvp_delta(buf)?;
908    for (i, option) in options.iter().enumerate() {
909        let key = option.key.into_inner();
910        if key == REPEATABLE_SETUP_OPTION || !KNOWN_SETUP_OPTIONS.contains(&key) {
911            continue;
912        }
913        if options[..i].iter().any(|earlier| earlier.key == option.key) {
914            return Err(CodecError::DuplicateParameter(key));
915        }
916    }
917    check_authorization_tokens(&options)?;
918    Ok(options)
919}
920
921/// Encode the Setup Options of a SETUP message.
922///
923/// The sender's half of the same sentence, and it is the wider half: "Senders
924/// MUST NOT repeat the same Option Type in a message" names no exception for
925/// types the sender does not recognise, so every repeat is refused here except
926/// the one the draft allows. A caller holding an option this codec has never
927/// heard of still may not send it twice.
928///
929/// The token is in this namespace as well, and is held to its structure here for
930/// the reason [`encode_parameters`] gives.
931fn encode_setup_options(options: &[KeyValuePair], buf: &mut impl BufMut) -> Result<(), CodecError> {
932    check_authorization_tokens(options)?;
933    for (i, option) in options.iter().enumerate() {
934        if option.key.into_inner() == REPEATABLE_SETUP_OPTION {
935            continue;
936        }
937        if options[..i].iter().any(|earlier| earlier.key == option.key) {
938            return Err(CodecError::DuplicateParameter(option.key.into_inner()));
939        }
940    }
941    encode_kvp_delta(options, buf)
942}
943
944// ============================================================
945// Message Types
946// ============================================================
947
948#[derive(Debug, Clone, Copy, PartialEq, Eq)]
949#[repr(u64)]
950pub enum MessageType {
951    RequestUpdate = 0x02,
952    Subscribe = 0x03,
953    SubscribeOk = 0x04,
954    RequestError = 0x05,
955    PublishNamespace = 0x06,
956    /// REQUEST_OK (0x07). Draft-20 Section 10.5 uses PUBLISH_OK as a shorthand
957    /// for a REQUEST_OK sent in response to a PUBLISH.
958    RequestOk = 0x07,
959    Namespace = 0x08,
960    PublishDone = 0x0B,
961    TrackStatus = 0x0D,
962    NamespaceDone = 0x0E,
963    PublishSkipped = 0x0F,
964    GoAway = 0x10,
965    Fetch = 0x16,
966    FetchOk = 0x18,
967    Publish = 0x1D,
968    /// PUBLISH_STATE_NOTIFY (0x22), new in draft-20 (Section 10.10).
969    PublishStateNotify = 0x22,
970    /// SUBSCRIBE_NAMESPACE (renumbered to 0x50 in draft-18).
971    SubscribeNamespace = 0x50,
972    /// SUBSCRIBE_TRACKS (new message in draft-18).
973    SubscribeTracks = 0x51,
974    Setup = 0x2F00,
975}
976
977impl MessageType {
978    pub fn from_id(id: u64) -> Option<Self> {
979        match id {
980            0x02 => Some(MessageType::RequestUpdate),
981            0x03 => Some(MessageType::Subscribe),
982            0x04 => Some(MessageType::SubscribeOk),
983            0x05 => Some(MessageType::RequestError),
984            0x06 => Some(MessageType::PublishNamespace),
985            0x07 => Some(MessageType::RequestOk),
986            0x08 => Some(MessageType::Namespace),
987            0x0B => Some(MessageType::PublishDone),
988            0x0D => Some(MessageType::TrackStatus),
989            0x0E => Some(MessageType::NamespaceDone),
990            0x0F => Some(MessageType::PublishSkipped),
991            0x10 => Some(MessageType::GoAway),
992            0x16 => Some(MessageType::Fetch),
993            0x18 => Some(MessageType::FetchOk),
994            0x1D => Some(MessageType::Publish),
995            0x22 => Some(MessageType::PublishStateNotify),
996            0x50 => Some(MessageType::SubscribeNamespace),
997            0x51 => Some(MessageType::SubscribeTracks),
998            0x2F00 => Some(MessageType::Setup),
999            _ => None,
1000        }
1001    }
1002
1003    pub fn id(&self) -> u64 {
1004        *self as u64
1005    }
1006
1007    /// This type's name in the shared vector corpus: the `message_type` its
1008    /// draft's `codec/messages/*.json` files carry, in `snake_case`.
1009    pub fn name(&self) -> &'static str {
1010        match self {
1011            MessageType::RequestUpdate => "request_update",
1012            MessageType::Subscribe => "subscribe",
1013            MessageType::SubscribeOk => "subscribe_ok",
1014            MessageType::RequestError => "request_error",
1015            MessageType::PublishNamespace => "publish_namespace",
1016            MessageType::RequestOk => "request_ok",
1017            MessageType::Namespace => "namespace",
1018            MessageType::PublishDone => "publish_done",
1019            MessageType::TrackStatus => "track_status",
1020            MessageType::NamespaceDone => "namespace_done",
1021            MessageType::PublishSkipped => "publish_skipped",
1022            MessageType::GoAway => "goaway",
1023            MessageType::Fetch => "fetch",
1024            MessageType::FetchOk => "fetch_ok",
1025            MessageType::Publish => "publish",
1026            MessageType::PublishStateNotify => "publish_state_notify",
1027            MessageType::SubscribeNamespace => "subscribe_namespace",
1028            MessageType::SubscribeTracks => "subscribe_tracks",
1029            MessageType::Setup => "setup",
1030        }
1031    }
1032}
1033
1034// ============================================================
1035// Session Lifecycle Messages
1036// ============================================================
1037
1038/// Unified SETUP (0x2F00).
1039#[derive(Debug, Clone, PartialEq, Eq)]
1040pub struct Setup {
1041    pub options: Vec<KeyValuePair>,
1042}
1043
1044/// GOAWAY (0x10). Draft-20's GOAWAY has no Request ID field, so the
1045/// control-stream and request-stream forms are identical on the wire.
1046/// Draft-18 is the one draft that carries the field, and only when the
1047/// message is sent on the control stream.
1048#[derive(Debug, Clone, PartialEq, Eq)]
1049pub struct GoAway {
1050    pub new_session_uri: Vec<u8>,
1051    pub timeout: VarInt,
1052}
1053
1054// ============================================================
1055// Consolidated Response Messages
1056// ============================================================
1057
1058/// REQUEST_OK (0x07). Used as a generic OK response and as the alias for
1059/// PUBLISH_OK / REQUEST_UPDATE_OK / TRACK_STATUS_OK / SUBSCRIBE_NAMESPACE_OK
1060/// / PUBLISH_NAMESPACE_OK.
1061///
1062/// `track_properties` is only populated for TRACK_STATUS_OK; for every
1063/// other shape it MUST be empty (length implicit from the message length).
1064#[derive(Debug, Clone, PartialEq, Eq)]
1065pub struct RequestOk {
1066    pub parameters: Vec<KeyValuePair>,
1067    pub track_properties: Vec<KeyValuePair>,
1068}
1069
1070/// Optional Redirect structure carried in REQUEST_ERROR with code 0x34.
1071#[derive(Debug, Clone, PartialEq, Eq)]
1072pub struct Redirect {
1073    pub connect_uri: Vec<u8>,
1074    pub track_namespace: TrackNamespace,
1075    pub track_name: Vec<u8>,
1076}
1077
1078/// REQUEST_ERROR (0x05). Adds an optional Redirect structure when
1079/// `error_code` is REDIRECT (0x34).
1080#[derive(Debug, Clone, PartialEq, Eq)]
1081pub struct RequestError {
1082    pub error_code: VarInt,
1083    pub retry_interval: VarInt,
1084    pub reason_phrase: Vec<u8>,
1085    pub redirect: Option<Redirect>,
1086}
1087
1088/// REQUEST_ERROR error codes with dedicated meaning.
1089///
1090/// Drafts 16 through 18 define DUPLICATE_SUBSCRIPTION (0x19) among these
1091/// codes; drafts 19 and 20 do not, because Section 5.1 lets an endpoint hold
1092/// multiple concurrent subscriptions to the same Track, each under its own
1093/// Request ID.
1094pub mod request_error_codes {
1095    /// A Mandatory Track Property the receiver does not understand.
1096    pub const UNSUPPORTED_EXTENSION: u64 = 0x33;
1097    /// Response carries a [`super::Redirect`] structure.
1098    pub const REDIRECT: u64 = 0x34;
1099    /// New in draft-20: SUBSCRIBE_TRACKS filter parameters conflict among too
1100    /// many subscribers to aggregate the subscription upstream.
1101    pub const CONFLICTING_FILTERS: u64 = 0x35;
1102    /// New in draft-20: a Range Filter parameter is invalid or exceeds
1103    /// MAX_FILTER_RANGES.
1104    pub const INVALID_FILTER: u64 = 0x36;
1105}
1106
1107// ============================================================
1108// Subscribe Messages
1109// ============================================================
1110
1111#[derive(Debug, Clone, PartialEq, Eq)]
1112pub struct Subscribe {
1113    pub request_id: VarInt,
1114    pub track_namespace: TrackNamespace,
1115    pub track_name: Vec<u8>,
1116    pub parameters: Vec<KeyValuePair>,
1117}
1118
1119/// SUBSCRIBE_OK (0x04).
1120#[derive(Debug, Clone, PartialEq, Eq)]
1121pub struct SubscribeOk {
1122    pub track_alias: VarInt,
1123    pub parameters: Vec<KeyValuePair>,
1124    pub track_properties: Vec<KeyValuePair>,
1125}
1126
1127#[derive(Debug, Clone, PartialEq, Eq)]
1128pub struct RequestUpdate {
1129    pub request_id: VarInt,
1130    pub parameters: Vec<KeyValuePair>,
1131}
1132
1133// ============================================================
1134// Publish Messages
1135// ============================================================
1136
1137#[derive(Debug, Clone, PartialEq, Eq)]
1138pub struct Publish {
1139    pub request_id: VarInt,
1140    pub track_namespace: TrackNamespace,
1141    pub track_name: Vec<u8>,
1142    pub track_alias: VarInt,
1143    pub parameters: Vec<KeyValuePair>,
1144    pub track_properties: Vec<KeyValuePair>,
1145}
1146
1147/// PUBLISH_DONE (0x0B). The wire layout is unchanged from draft-19; what
1148/// draft-20 changed is the `Stream Count` sentinel, what the count includes,
1149/// and the removal of status code 0x3.
1150#[derive(Debug, Clone, PartialEq, Eq)]
1151pub struct PublishDone {
1152    /// The reason the publisher is ending the subscription.
1153    ///
1154    /// Not validated against the registry, on decode or on encode, and that is
1155    /// the draft's instruction rather than an omission. Draft-20 Section 14:
1156    /// "Receipt of an unknown error code in any error context (Session
1157    /// Termination, REQUEST_ERROR, PUBLISH_DONE, or Data Stream Reset) MUST be
1158    /// treated as equivalent to INTERNAL_ERROR for that context. An endpoint
1159    /// MUST NOT close the session because it received an unknown error code in
1160    /// a REQUEST_ERROR or PUBLISH_DONE." Refusing the frame would take that
1161    /// choice away from the caller, so an unassigned code is carried up and
1162    /// [`super::error_codes::PublishDoneStatusCode::from_u64`] answers `None`
1163    /// for it.
1164    ///
1165    /// That reaches 0x3 in particular. Draft-19 assigned it to
1166    /// `SUBSCRIPTION_ENDED`; draft-20 removed the row and the behaviour behind
1167    /// it together (Section 5.1.2: "A publisher does not end a subscription
1168    /// solely because the Largest Object advances past the end of the current
1169    /// Location Filter"). A draft-20 receiver reads a 0x3 as INTERNAL_ERROR.
1170    pub status_code: VarInt,
1171    /// The number of streams the publisher opened for this subscription.
1172    ///
1173    /// Draft-20 Section 10.12 widens what is counted: the total now includes
1174    /// "streams that contained no Objects (e.g., an empty Subgroup) and
1175    /// including any fill fetch streams (see Section 5.1.3)". Draft-19 counted
1176    /// no fill streams because it had none.
1177    ///
1178    /// See [`publish_done_codes::STREAM_COUNT_UNKNOWN`] for the sentinel.
1179    pub stream_count: VarInt,
1180    pub reason_phrase: Vec<u8>,
1181}
1182
1183/// Numeric values for the [`PublishDone`] fields.
1184pub mod publish_done_codes {
1185    /// Draft-18 onwards: TOO_FAR_BEHIND is 0x05 (was 0x06 in draft-17).
1186    pub const TOO_FAR_BEHIND: u64 = 0x05;
1187    /// Draft-18 onwards: EXPIRED is 0x06 (was 0x05 in draft-17).
1188    pub const EXPIRED: u64 = 0x06;
1189
1190    /// The value [`super::PublishDone::stream_count`] carries when the
1191    /// publisher cannot state an exact count.
1192    ///
1193    /// Draft-20 Section 10.12: "If the publisher is unable to set Stream Count
1194    /// to the exact number of streams opened for the subscription, it MUST set
1195    /// Stream Count to 2^64 - 1." Draft-19 said `2^62 - 1`, which is where the
1196    /// QUIC varint tops out; MoQT's own varint (Section 1.4.1) is a
1197    /// leading-ones-length prefix reaching a full 64 bits in nine bytes, so
1198    /// this value is encodable at all — as `ff` followed by eight `ff` bytes.
1199    ///
1200    /// **In draft-20 the sentinel is indistinguishable from a well-formed
1201    /// exact count.** Draft-19's `2^62 - 1` leaves headroom above the marker;
1202    /// there is none above this one, so a publisher that really opened
1203    /// `2^64 - 1` streams cannot say so and a receiver cannot tell the two
1204    /// apart. The draft does not remark on it. Not a practical problem, and
1205    /// worth knowing before writing a comparison against this constant.
1206    pub const STREAM_COUNT_UNKNOWN: u64 = u64::MAX;
1207}
1208
1209// ============================================================
1210// Publish Namespace Messages
1211// ============================================================
1212
1213#[derive(Debug, Clone, PartialEq, Eq)]
1214pub struct PublishNamespace {
1215    pub request_id: VarInt,
1216    pub track_namespace: TrackNamespace,
1217    pub parameters: Vec<KeyValuePair>,
1218}
1219
1220// ============================================================
1221// Namespace Messages
1222// ============================================================
1223
1224#[derive(Debug, Clone, PartialEq, Eq)]
1225pub struct Namespace {
1226    pub namespace_suffix: TrackNamespace,
1227}
1228
1229#[derive(Debug, Clone, PartialEq, Eq)]
1230pub struct NamespaceDone {
1231    pub namespace_suffix: TrackNamespace,
1232}
1233
1234// ============================================================
1235// Subscribe Namespace / Tracks Messages
1236// ============================================================
1237
1238/// SUBSCRIBE_NAMESPACE (0x50). Subscribes to NAMESPACE / NAMESPACE_DONE
1239/// advertisements for namespaces matching `namespace_prefix`. Only drafts 16
1240/// and 17 carry a `subscribe_options` varint here; on draft-20 a namespace
1241/// subscription only produces NAMESPACE / NAMESPACE_DONE.
1242#[derive(Debug, Clone, PartialEq, Eq)]
1243pub struct SubscribeNamespace {
1244    pub request_id: VarInt,
1245    pub namespace_prefix: TrackNamespace,
1246    pub parameters: Vec<KeyValuePair>,
1247}
1248
1249/// SUBSCRIBE_TRACKS (0x51, new in draft-18). Subscribes to PUBLISH messages
1250/// for tracks whose namespace matches `namespace_prefix`. Carries the FORWARD
1251/// parameter (Section 10.2.18), which on drafts 15 through 17 may appear on
1252/// SUBSCRIBE_NAMESPACE instead.
1253#[derive(Debug, Clone, PartialEq, Eq)]
1254pub struct SubscribeTracks {
1255    pub request_id: VarInt,
1256    pub namespace_prefix: TrackNamespace,
1257    pub parameters: Vec<KeyValuePair>,
1258}
1259
1260// ============================================================
1261// Track Status Messages
1262// ============================================================
1263
1264#[derive(Debug, Clone, PartialEq, Eq)]
1265pub struct TrackStatus {
1266    pub request_id: VarInt,
1267    pub track_namespace: TrackNamespace,
1268    pub track_name: Vec<u8>,
1269    pub parameters: Vec<KeyValuePair>,
1270}
1271
1272// ============================================================
1273// Fetch Messages
1274// ============================================================
1275
1276/// FETCH (0x16), rebuilt in draft-20 (Section 10.13, Figure 16).
1277///
1278/// ```text
1279/// FETCH Message {
1280///   Type (vi64) = 0x16,
1281///   Length (16),
1282///   Request ID (vi64),
1283///   Track Namespace (..),
1284///   Track Name Length (vi64),
1285///   Track Name (..),
1286///   Number of Parameters (vi64),
1287///   Parameters (..) ...
1288/// }
1289/// ```
1290///
1291/// # What went, and why draft-19's shape cannot be ported
1292///
1293/// Draft-19's FETCH opened with a `Fetch Type` that chose between a Standalone
1294/// Fetch — a namespace, a name and an inline `Start Location` / `End Location`
1295/// pair — and a Joining Fetch of two varints. Draft-20 deleted the field, both
1296/// structures, the Fetch Type registry and the whole joining mechanism, and
1297/// promoted the namespace and the name to fields of FETCH itself, in the
1298/// positions they hold inside draft-19's Standalone Fetch. What is left is
1299/// byte-identical to [`Subscribe`] apart from the type code.
1300///
1301/// The range now travels in the `LOCATION_FILTER` parameter (Section 5.1.2). A
1302/// FETCH with none covers `{0,0}` through Largest Object, inclusive.
1303///
1304/// # `INVALID_RANGE` and a relative start
1305///
1306/// Section 10.13 keeps draft-19's rule: "If no Objects have been published for
1307/// the track or Start Location is greater than the Largest Object" then "the
1308/// publisher MUST return REQUEST_ERROR with error code INVALID_RANGE". A
1309/// relative start —
1310/// the one-field `LOCATION_FILTER` with `StartGroup = 0`, which resolves to the
1311/// Next Group — is by construction greater than Largest Object, so read
1312/// literally the rule rejects every relative-start FETCH. That is plainly not
1313/// the intent and the text carves out nothing, so **this codec does not apply
1314/// the Start-greater-than-Largest test to a relative start**, and neither
1315/// should a caller. Nothing here can enforce either reading: the test needs
1316/// Largest Object, which is track state rather than anything in this frame, so
1317/// the decision belongs to the endpoint and is recorded here because this is
1318/// where the filter arrives.
1319///
1320/// **The codepoint did not change.** A draft-19 decoder fed one of these reads
1321/// the `Number of Track Namespace Fields` count as a `Fetch Type` and
1322/// mis-parses without complaint; there is no in-band version signal to catch
1323/// it. That is why draft-20 has a FETCH decoder of its own rather than sharing
1324/// draft-19's.
1325#[derive(Debug, Clone, PartialEq, Eq)]
1326pub struct Fetch {
1327    pub request_id: VarInt,
1328    pub track_namespace: TrackNamespace,
1329    pub track_name: Vec<u8>,
1330    pub parameters: Vec<KeyValuePair>,
1331}
1332
1333/// FETCH_OK (0x18). `end_of_track` is uint8.
1334///
1335/// Byte-identical to draft-19; the field that changed meaning is
1336/// [`FetchOk::end_object`].
1337#[derive(Debug, Clone, PartialEq, Eq)]
1338pub struct FetchOk {
1339    pub end_of_track: u8,
1340    pub end_group: VarInt,
1341    /// The Object ID of the **last Object the response covers**, inclusive.
1342    ///
1343    /// This is the silent off-by-one of the revision, and it is absent from
1344    /// draft-20's own change log. Draft-19 Section 10.13 defined the pair as
1345    /// "the end of the range covered by the FETCH response, using the same
1346    /// encoding as the FETCH request End Location (the last Object, plus 1; or
1347    /// 0 to indicate the entire Group)". Draft-20 Section 10.14 drops that
1348    /// parenthesis entirely, and Section 5.1.2 and Section 10.13 both say the
1349    /// Location filter "specifies an inclusive range of Locations".
1350    ///
1351    /// So both draft-19 conventions are gone: there is no plus one, and an
1352    /// Object of 0 now means object 0 rather than the whole group. The bytes
1353    /// are identical between the two drafts and the meaning is not, and nothing
1354    /// on the wire distinguishes them — an encoder ported forward with its
1355    /// arithmetic intact fetches one object too many, and one whose end lands
1356    /// on object 0 fetches a single object where the same bytes cover a whole
1357    /// group on draft-19.
1358    ///
1359    /// **Ambiguous, and the draft leaves it so.** When the request's filter
1360    /// omitted `EndObject`, so the
1361    /// filter meant "all objects in the End Group", Section 10.14 does not say
1362    /// what to report — and with the `0`-means-whole-group encoding gone there
1363    /// is no way left to spell it. The same applies to a relative start. The
1364    /// reading this codec's corpus takes, and the only sane one, is the Object
1365    /// ID of the last Object actually covered; the draft does not say so, and
1366    /// nothing here can enforce it, because resolving it needs the track rather
1367    /// than the frame.
1368    pub end_object: VarInt,
1369    pub parameters: Vec<KeyValuePair>,
1370    pub track_properties: Vec<KeyValuePair>,
1371}
1372
1373// ============================================================
1374// Publish State Notify
1375// ============================================================
1376
1377/// PUBLISH_STATE_NOTIFY (0x22), new in draft-20 (Section 10.10, Figure 13).
1378///
1379/// ```text
1380/// PUBLISH_STATE_NOTIFY Message {
1381///   Type (vi64) = 0x22,
1382///   Length (16),
1383///   Number of Parameters (vi64),
1384///   Parameters (..) ...
1385/// }
1386/// ```
1387///
1388/// **There is no Request ID field.** The message is identified by the
1389/// subscription's bidirectional request stream it arrives on, the way
1390/// SUBSCRIBE_OK, PUBLISH_DONE and FETCH_OK are.
1391///
1392/// The rules a codec cannot check, because they are about the session rather
1393/// than the frame, and which the caller therefore owns (Section 10.10):
1394///
1395/// * it is sent by the **publisher only**, on a **subscription's** stream.
1396///   Receiving one for any other request type, or from the subscriber, MUST
1397///   close the session with a PROTOCOL_VIOLATION;
1398/// * it is **unilateral** — the receiver does not answer with REQUEST_OK or
1399///   REQUEST_ERROR — and it is not counted against the `MAX_REQUEST_UPDATES`
1400///   Setup Option;
1401/// * it carries only the parameters whose values changed, and an absent
1402///   parameter is unchanged;
1403/// * a publisher MUST NOT use it to change a subscriber-controlled parameter
1404///   unless the subscriber asked for the change;
1405/// * the publisher **MUST** include `LARGEST_OBJECT` (0x09) if known, so the
1406///   subscriber can locate the point in the track where the change took
1407///   effect. Nothing here enforces that: a missing required parameter is not
1408///   something this decoder detects, and a message that omits it is still a
1409///   well-formed frame.
1410#[derive(Debug, Clone, PartialEq, Eq)]
1411pub struct PublishStateNotify {
1412    pub parameters: Vec<KeyValuePair>,
1413}
1414
1415// ============================================================
1416// Publish Skipped
1417// ============================================================
1418
1419/// PUBLISH_SKIPPED (0x0F). Drafts 17 and 18 name this codepoint
1420/// PUBLISH_BLOCKED; the wire layout — track namespace suffix then track name —
1421/// is the same on all four drafts that carry the message.
1422#[derive(Debug, Clone, PartialEq, Eq)]
1423pub struct PublishSkipped {
1424    pub namespace_suffix: TrackNamespace,
1425    pub track_name: Vec<u8>,
1426}
1427
1428// ============================================================
1429// Unified Message Enum
1430// ============================================================
1431
1432#[derive(Debug, Clone, PartialEq, Eq)]
1433pub enum ControlMessage {
1434    Setup(Setup),
1435    GoAway(GoAway),
1436    RequestOk(RequestOk),
1437    RequestError(RequestError),
1438    Subscribe(Subscribe),
1439    SubscribeOk(SubscribeOk),
1440    RequestUpdate(RequestUpdate),
1441    Publish(Publish),
1442    PublishStateNotify(PublishStateNotify),
1443    PublishDone(PublishDone),
1444    PublishNamespace(PublishNamespace),
1445    Namespace(Namespace),
1446    NamespaceDone(NamespaceDone),
1447    SubscribeNamespace(SubscribeNamespace),
1448    SubscribeTracks(SubscribeTracks),
1449    TrackStatus(TrackStatus),
1450    Fetch(Fetch),
1451    FetchOk(FetchOk),
1452    PublishSkipped(PublishSkipped),
1453}
1454
1455// Draft-20 has no range check on a control message, and the absence is the
1456// draft's rather than an omission here.
1457//
1458// Draft-19 carried one: its FETCH held a `Start Location` and an `End Location`
1459// inline, and draft-19 Section 10.12.3 said "End Location MUST specify the
1460// same or a larger Location than Start Location for Standalone and Absolute
1461// Joining
1462// Fetches". Draft-20 deleted both fields with the rest of the FETCH rewrite
1463// (Section 10.13), so there is no pair left in any message to compare.
1464//
1465// What replaced them cannot express the malformation either. A `LOCATION_FILTER`
1466// (Section 5.1.2) states its end as an unsigned `EndGroupDelta` added to
1467// `StartGroup`, so the end group can never precede the start group; and within
1468// one group draft-20 states no rule about an `EndObject` below `StartObject`.
1469// Section 5.1.2 says the opposite for subscriptions — "A Location Filter on a
1470// subscription is always valid, even if it specifies a range entirely before
1471// Largest Object" — so refusing one would close sessions over a sentence that
1472// is not there.
1473//
1474// The one backwards-range rule draft-20 does keep is in Section 10.14: "If End
1475// Location is smaller than the Start Location in the corresponding FETCH the
1476// receiver MUST close the session with a PROTOCOL_VIOLATION." It compares a
1477// FETCH_OK against the FETCH it answers, which is session state and not
1478// anything one frame holds, so it belongs to the caller.
1479
1480/// Refuse a message whose discriminator disagrees with the fields beside it.
1481///
1482/// One draft-20 message carries a field that says which of the following fields
1483/// are on the wire: REQUEST_ERROR's Error Code, whose REDIRECT value (0x34) is
1484/// what puts the Redirect structure on the wire. This codec holds the
1485/// alternative in an `Option`, so a value can say one thing in its
1486/// discriminator and another in its body, and the two sides of the codec
1487/// resolve that differently — the encoder writes whatever the body holds, and
1488/// the decoder reads whatever the discriminator announces.
1489///
1490/// A REQUEST_ERROR with code REDIRECT and no Redirect body encodes to a message
1491/// that ends where the decoder expects a Connect URI length, so the peer reads
1492/// the redirect out of whatever follows or runs off the end. The mirror case is
1493/// quieter and no better: a Redirect body under any other error code is written
1494/// out and then skipped by a decoder that was never told to look for it, so the
1495/// sender believes it redirected a peer that never saw a redirect.
1496///
1497/// Draft-19 had a second discriminator here, FETCH's `Fetch Type`, choosing
1498/// between a standalone body and a joining pair. Draft-20 deleted the field and
1499/// both bodies (Section 10.13), so FETCH has nothing left to disagree with
1500/// itself about.
1501///
1502/// Refusing at the encoder keeps the two readings from ever diverging on the
1503/// wire.
1504fn check_discriminators(message: &ControlMessage) -> Result<(), CodecError> {
1505    // One arm, where drafts 17 to 19 have two, so an `if let` rather than a
1506    // one-armed `match`; a second discriminator would make it a `match`.
1507    if let ControlMessage::RequestError(m) = message {
1508        let code_is_redirect = m.error_code.into_inner() == request_error_codes::REDIRECT;
1509        if code_is_redirect != m.redirect.is_some() {
1510            return Err(CodecError::InvalidField);
1511        }
1512    }
1513    Ok(())
1514}
1515
1516/// Whether draft-20 lets Message Parameter `key` appear in `message`.
1517///
1518/// Section 10.2.1: "Each Message Parameter definition indicates the message
1519/// types in which it can appear. If it appears in some other type of message,
1520/// the receiving endpoint MUST close the connection with a PROTOCOL_VIOLATION."
1521/// One arm per entry in the Message Parameters registry (Section 15.7),
1522/// carrying the message types that entry's own definition names.
1523///
1524/// Four things about this draft the arms below fold in:
1525///
1526/// * Six of the names are one wire type. Section 10.5: "This document uses the
1527///   shorthand PUBLISH_OK, REQUEST_UPDATE_OK, TRACK_STATUS_OK,
1528///   SUBSCRIBE_NAMESPACE_OK, SUBSCRIBE_TRACKS_OK and PUBLISH_NAMESPACE_OK to
1529///   refer to a REQUEST_OK sent in response to the corresponding request type".
1530///   Which one a given REQUEST_OK is depends on the request its Request ID
1531///   answers, which is session state and not in the frame, so each of those
1532///   names widens the same arm and a REQUEST_OK is held to their union.
1533/// * The five Range Filters state their scope in Section 5.1.4 — draft-19's
1534///   Section 5.1.3 — rather than in their own subsections: the Track Property
1535///   filter "MAY appear multiple times in a SUBSCRIBE_TRACKS message or
1536///   REQUEST_UPDATE for it", and "all other filter parameters MAY appear
1537///   multiple times in a FETCH, SUBSCRIBE, SUBSCRIBE_TRACKS, or REQUEST_UPDATE
1538///   (on a subscription, from the subscriber only) message". Draft-19 listed
1539///   PUBLISH_OK in that second sentence and draft-20 removed it.
1540/// * **SUBSCRIBE_TRACKS takes the parameters whose own definitions name it,
1541///   plus `LOCATION_FILTER` (0x21) and `FILL_PARAMETERS` (0x23), and the two
1542///   extra are a decision this codec makes.** Section 10.20.1: "Any Parameter
1543///   that can be specified on a Subscription (ie: in SUBSCRIBE) is valid in
1544///   SUBSCRIBE_TRACKS, unless otherwise specified." The definitions are that
1545///   "otherwise": `AUTHORIZATION_TOKEN`, `FORWARD`, `GROUP_ORDER`,
1546///   `INCLUDE_PROPERTIES` and the Range Filters name SUBSCRIBE_TRACKS, and
1547///   `OBJECT_DELIVERY_TIMEOUT` (0x02), `RENDEZVOUS_TIMEOUT` (0x04),
1548///   `SUBGROUP_DELIVERY_TIMEOUT` (0x06), `SUBSCRIBER_PRIORITY` (0x20) and
1549///   `NEW_GROUP_REQUEST` (0x32) leave it out, so those five are refused there
1550///   under Section 10.2.1. The same section then closes: "To join Tracks
1551///   initiated via the resulting PUBLISHes, the subscriber can specify a
1552///   Location Filter and optionally include FILL_PARAMETERS" — two parameters
1553///   whose definitions also leave this message out. On those two alone the
1554///   section and the definitions with Section 10.2.1's rule conflict, from
1555///   draft-20 on. This codec follows the section for them: it is the one
1556///   sentence telling a subscriber what to put in this message, and a scope
1557///   miss ends the session.
1558/// * **`PUBLISH_OK` is gone from six definitions.** `OBJECT_DELIVERY_TIMEOUT`
1559///   (0x02), `SUBGROUP_DELIVERY_TIMEOUT` (0x06), `FORWARD` (0x10),
1560///   `SUBSCRIBER_PRIORITY` (0x20), `LOCATION_FILTER` (0x21) and
1561///   `NEW_GROUP_REQUEST` (0x32) each dropped it, and several gained `PUBLISH`
1562///   instead; the Range Filters dropped it via Section 5.1.4. `EXPIRES` (0x08)
1563///   is the only parameter that still names it. A subscriber that wants to
1564///   change something now sends a REQUEST_UPDATE after the PUBLISH_OK, and
1565///   sending any of the six on a PUBLISH_OK is a Section 10.2.1 violation.
1566///   Because PUBLISH_OK and REQUEST_OK are one wire type, this table cannot
1567///   see the difference: `M::RequestOk` is admitted wherever any of the six OK
1568///   names is, so the practical effect here is that the six lose their
1569///   `M::RequestOk` arm entirely.
1570///
1571/// FETCH_OK has no arm in the table below, and that is the draft's doing rather
1572/// than an omission here: Section 10.14 gives it a Parameters field and no
1573/// parameter definition names it, so every type this draft defines is "some
1574/// other type of message" there.
1575///
1576/// PUBLISH_STATE_NOTIFY is admitted by exactly three parameters, and treating
1577/// that list as closed is **a decision this codec makes**. Section 10.10 says
1578/// only "The semantics of each parameter, including whether it may appear in
1579/// PUBLISH_STATE_NOTIFY, are defined by the parameter", and `LARGEST_OBJECT`
1580/// (0x09), `FORWARD` (0x10) and `LOCATION_FILTER` (0x21) are the three whose
1581/// definitions name it. The draft implies the closure and never states it, so
1582/// anything else there is refused under Section 10.2.1 on that reading.
1583///
1584/// The table decides scope only. A type this draft does not define has no scope
1585/// to be outside of and is answered by [`CodecError::UnknownMessageParameter`],
1586/// which is why the final arm carries rather than refuses.
1587pub fn parameter_in_scope(key: u64, message: MessageType) -> bool {
1588    use MessageType as M;
1589    // SUBSCRIBE_TRACKS appears only in the arms whose definitions name it, and
1590    // in 0x21 and 0x23, which Section 10.20.1 names; see the doc comment above.
1591    match key {
1592        // Section 10.2.4 OBJECT_DELIVERY_TIMEOUT: "It MAY appear in a
1593        // SUBSCRIBE, PUBLISH, or REQUEST_UPDATE message." Draft-19 said
1594        // PUBLISH_OK where this says PUBLISH.
1595        0x02 => matches!(message, M::Subscribe | M::Publish | M::RequestUpdate),
1596        // Section 10.2.2 AUTHORIZATION TOKEN: "It MAY appear in a PUBLISH,
1597        // SUBSCRIBE, REQUEST_UPDATE, SUBSCRIBE_NAMESPACE, SUBSCRIBE_TRACKS,
1598        // PUBLISH_NAMESPACE, TRACK_STATUS or FETCH message." Unchanged from
1599        // draft-19; what draft-20 added is the sentence after it, "This
1600        // Parameter MUST NOT be copied from a SUBSCRIBE_TRACKS to the resulting
1601        // PUBLISH message Parameters", which is a rule about two messages and
1602        // so belongs to the caller rather than to this table.
1603        0x03 => matches!(
1604            message,
1605            M::Publish
1606                | M::Subscribe
1607                | M::RequestUpdate
1608                | M::SubscribeNamespace
1609                | M::SubscribeTracks
1610                | M::PublishNamespace
1611                | M::TrackStatus
1612                | M::Fetch
1613        ),
1614        // Section 10.2.6 RENDEZVOUS TIMEOUT: it "MAY appear in a SUBSCRIBE
1615        // message".
1616        0x04 => matches!(message, M::Subscribe),
1617        // Section 10.2.3 SUBGROUP_DELIVERY_TIMEOUT: "It MAY appear in a
1618        // SUBSCRIBE, PUBLISH, or REQUEST_UPDATE message." Draft-19 said
1619        // PUBLISH_OK where this says PUBLISH.
1620        0x06 => matches!(message, M::Subscribe | M::Publish | M::RequestUpdate),
1621        // Section 10.2.16 EXPIRES: "It MAY appear in SUBSCRIBE_OK, PUBLISH,
1622        // PUBLISH_OK, SUBSCRIBE_NAMESPACE_OK, SUBSCRIBE_TRACKS_OK,
1623        // PUBLISH_NAMESPACE_OK, or REQUEST_UPDATE_OK." Five of those seven are
1624        // a REQUEST_OK. The one parameter that still names PUBLISH_OK.
1625        0x08 => matches!(message, M::SubscribeOk | M::Publish | M::RequestOk),
1626        // Section 10.2.17 LARGEST OBJECT: "It MAY appear in SUBSCRIBE_OK,
1627        // PUBLISH, REQUEST_UPDATE_OK, TRACK_STATUS_OK, or
1628        // PUBLISH_STATE_NOTIFY." The last is new in draft-20.
1629        0x09 => {
1630            matches!(message, M::SubscribeOk | M::Publish | M::RequestOk | M::PublishStateNotify)
1631        }
1632        // Section 10.2.5 FILL TIMEOUT: it "MAY appear in a FETCH message, or
1633        // inside a FILL_PARAMETERS parameter (see Section 10.2.15) in a
1634        // SUBSCRIBE or REQUEST_UPDATE (for a subscription), where it applies to
1635        // the fill fetch stream." The nested half is not a scope this table can
1636        // answer — a nested parameter is not in the enclosing message at all,
1637        // per Section 10.2.15 — so it is enforced by
1638        // [`decode_fill_parameters`] against Table 6 instead.
1639        0x0A => matches!(message, M::Fetch),
1640        // Section 10.2.18 FORWARD: "It MAY appear in SUBSCRIBE, REQUEST_UPDATE
1641        // (for a subscription or a SUBSCRIBE_TRACKS request), PUBLISH,
1642        // SUBSCRIBE_TRACKS and PUBLISH_STATE_NOTIFY." Draft-19 listed
1643        // PUBLISH_OK and had no PUBLISH_STATE_NOTIFY.
1644        0x10 => matches!(
1645            message,
1646            M::Subscribe
1647                | M::RequestUpdate
1648                | M::Publish
1649                | M::SubscribeTracks
1650                | M::PublishStateNotify
1651        ),
1652        // Section 10.2.7 SUBSCRIBER PRIORITY: "It MAY appear in a SUBSCRIBE,
1653        // PUBLISH, FETCH, or REQUEST_UPDATE (for a subscription or FETCH)."
1654        // Draft-19 said PUBLISH_OK where this says PUBLISH.
1655        0x20 => matches!(message, M::Subscribe | M::Publish | M::Fetch | M::RequestUpdate),
1656        // Section 10.2.9 LOCATION FILTER: "It MAY appear in a FETCH, SUBSCRIBE,
1657        // PUBLISH, REQUEST_UPDATE (for a subscription) or PUBLISH_STATE_NOTIFY
1658        // message." Draft-19 admitted SUBSCRIBE, PUBLISH_OK and REQUEST_UPDATE
1659        // and no FETCH, because a draft-19 FETCH carried its range in the
1660        // message instead. SUBSCRIBE_TRACKS is admitted on top of that list by
1661        // Section 10.20.1's closing sentence, as for FILL_PARAMETERS below.
1662        0x21 => matches!(
1663            message,
1664            M::Fetch
1665                | M::Subscribe
1666                | M::Publish
1667                | M::RequestUpdate
1668                | M::PublishStateNotify
1669                | M::SubscribeTracks
1670        ),
1671        // Section 10.2.8 GROUP ORDER: "It MAY appear in a SUBSCRIBE, PUBLISH,
1672        // SUBSCRIBE_TRACKS, or FETCH, or inside a FILL_PARAMETERS parameter".
1673        // The nested half is Table 6's, as for FILL_TIMEOUT above.
1674        0x22 => matches!(message, M::Subscribe | M::Publish | M::SubscribeTracks | M::Fetch),
1675        // Section 10.2.15 FILL_PARAMETERS, new in draft-20: it "MAY appear in a
1676        // SUBSCRIBE or REQUEST_UPDATE (for a subscription) message."
1677        //
1678        // SUBSCRIBE_TRACKS is admitted on top of those two by Section 10.20.1's
1679        // closing sentence, which tells the subscriber it "can specify a
1680        // Location Filter and optionally include FILL_PARAMETERS" there; see
1681        // the doc comment above for why that sentence wins over this list.
1682        //
1683        // FETCH is refused, and that is the case the corpus pins: a fill fetch
1684        // stream is something a subscription opens, and a FETCH already is one.
1685        0x23 => matches!(message, M::Subscribe | M::RequestUpdate | M::SubscribeTracks),
1686        // Section 5.1.4: "All other filter parameters MAY appear multiple times
1687        // in a FETCH, SUBSCRIBE, SUBSCRIBE_TRACKS, or REQUEST_UPDATE (on a
1688        // subscription, from the subscriber only) message." SUBGROUP_FILTER
1689        // (Section 10.2.10), OBJECTID_FILTER (10.2.11), PRIORITY_FILTER
1690        // (10.2.12) and OBJECT_PROPERTY_FILTER (10.2.13) are those four.
1691        // Draft-19's sentence also listed PUBLISH_OK.
1692        0x25..=0x28 => {
1693            matches!(message, M::Fetch | M::Subscribe | M::SubscribeTracks | M::RequestUpdate)
1694        }
1695        // Section 5.1.4, of TRACK_PROPERTY_FILTER (Section 10.2.14) alone: it
1696        // "MAY appear multiple times in a SUBSCRIBE_TRACKS message or
1697        // REQUEST_UPDATE for it". It selects tracks rather than objects, which
1698        // is why it is the one filter a SUBSCRIBE may not carry and the one
1699        // Table 6 keeps out of FILL_PARAMETERS.
1700        0x29 => matches!(message, M::SubscribeTracks | M::RequestUpdate),
1701        // Section 10.2.19 NEW GROUP REQUEST: "It MAY appear in SUBSCRIBE or
1702        // REQUEST_UPDATE for a subscription." Draft-19 also listed PUBLISH_OK.
1703        0x32 => matches!(message, M::Subscribe | M::RequestUpdate),
1704        // Section 10.2.20 TRACK_NAMESPACE_PREFIX: "It MAY appear in
1705        // REQUEST_UPDATE for a SUBSCRIBE_NAMESPACE or SUBSCRIBE_TRACKS
1706        // request." The two named there are the request being updated, not two
1707        // more places the parameter may be written.
1708        0x34 => matches!(message, M::RequestUpdate),
1709        // Section 10.2.21 INCLUDE_PROPERTIES, new in draft-20: "It MAY appear
1710        // in SUBSCRIBE, TRACK_STATUS, FETCH or SUBSCRIBE_TRACKS."
1711        0x35 => matches!(message, M::Subscribe | M::TrackStatus | M::Fetch | M::SubscribeTracks),
1712        _ => true,
1713    }
1714}
1715
1716/// Refuse a message carrying a Message Parameter its own definition does not
1717/// place there.
1718///
1719/// Section 10.2.1 answers this with a close, which the drafts below do not.
1720/// Draft-16 Section 9.2.2, and drafts 07 through 15 under the older name
1721/// Version Specific Parameters, end the same sentence "it MUST be ignored" —
1722/// so this check belongs to drafts 17 and later and to no draft before them.
1723///
1724/// Applied on both sides. A parameter outside its scope is one the peer must
1725/// close the session over, so writing one is a way to end a session rather than
1726/// a way to ask for anything.
1727fn check_parameter_scope(message: &ControlMessage) -> Result<(), CodecError> {
1728    let parameters = match message {
1729        ControlMessage::RequestOk(m) => &m.parameters,
1730        ControlMessage::Subscribe(m) => &m.parameters,
1731        ControlMessage::SubscribeOk(m) => &m.parameters,
1732        ControlMessage::RequestUpdate(m) => &m.parameters,
1733        ControlMessage::Publish(m) => &m.parameters,
1734        ControlMessage::PublishStateNotify(m) => &m.parameters,
1735        ControlMessage::PublishNamespace(m) => &m.parameters,
1736        ControlMessage::SubscribeNamespace(m) => &m.parameters,
1737        ControlMessage::SubscribeTracks(m) => &m.parameters,
1738        ControlMessage::TrackStatus(m) => &m.parameters,
1739        ControlMessage::Fetch(m) => &m.parameters,
1740        ControlMessage::FetchOk(m) => &m.parameters,
1741        // No Message Parameters field. SETUP is named here rather than left to
1742        // a wildcard because the draft says why it can never have one: Section
1743        // 10.2.1 notes that "since Setup Options use a separate namespace, it
1744        // is impossible for Message Parameters to appear in Setup messages",
1745        // and this codec keeps the two namespaces in separate fields.
1746        ControlMessage::Setup(_)
1747        | ControlMessage::GoAway(_)
1748        | ControlMessage::RequestError(_)
1749        | ControlMessage::PublishDone(_)
1750        | ControlMessage::Namespace(_)
1751        | ControlMessage::NamespaceDone(_)
1752        | ControlMessage::PublishSkipped(_) => return Ok(()),
1753    };
1754
1755    let message_type = message.message_type();
1756    for parameter in parameters {
1757        let key = parameter.key.into_inner();
1758        if !parameter_in_scope(key, message_type) {
1759            return Err(CodecError::ParameterOutOfScope { key, message_type: message_type.id() });
1760        }
1761    }
1762    Ok(())
1763}
1764
1765impl ControlMessage {
1766    pub fn encode(&self, buf: &mut impl BufMut) -> Result<(), CodecError> {
1767        check_discriminators(self)?;
1768        check_parameter_scope(self)?;
1769        let mut body = Vec::with_capacity(256);
1770        self.encode_body(&mut body)?;
1771
1772        if body.len() > MAX_MESSAGE_LENGTH {
1773            return Err(CodecError::MessageTooLong(body.len()));
1774        }
1775
1776        let msg_type = self.message_type();
1777        VarInt::from_usize(msg_type.id() as usize).encode_moqt::<Wire>(buf);
1778        // Draft-20: 16-bit length (big-endian)
1779        buf.put_u16(body.len() as u16);
1780        buf.put_slice(&body);
1781        Ok(())
1782    }
1783
1784    pub fn decode(buf: &mut impl Buf) -> Result<Self, CodecError> {
1785        let type_id = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
1786        let msg_type =
1787            MessageType::from_id(type_id).ok_or(CodecError::UnknownMessageType(type_id))?;
1788        // Draft-20: 16-bit length (big-endian)
1789        if buf.remaining() < 2 {
1790            return Err(CodecError::UnexpectedEnd);
1791        }
1792        let body_len = buf.get_u16() as usize;
1793        if buf.remaining() < body_len {
1794            return Err(CodecError::UnexpectedEnd);
1795        }
1796        let body_bytes = buf.copy_to_bytes(body_len);
1797        let mut body = &body_bytes[..];
1798        let msg = match Self::decode_body(msg_type, &mut body) {
1799            Ok(msg) => msg,
1800            // The fields wanted more bytes than the Length allowed. This buffer
1801            // is already bounded by that Length, so running out inside it cannot
1802            // mean the message is still arriving - which is what the same error
1803            // means everywhere else, and why a reader loops on it rather than
1804            // closing. Here there is nothing left to arrive.
1805            Err(
1806                CodecError::UnexpectedEnd
1807                | CodecError::Kvp(crate::kvp::KvpError::UnexpectedEnd)
1808                | CodecError::Kvp(crate::kvp::KvpError::VarInt(
1809                    crate::varint::VarIntError::UnexpectedEnd,
1810                ))
1811                | CodecError::VarInt(crate::varint::VarIntError::UnexpectedEnd),
1812            ) => {
1813                return Err(CodecError::ControlMessageLengthMismatch {
1814                    declared: body_len,
1815                    detail: "its fields ran past the end",
1816                });
1817            }
1818            Err(e) => return Err(e),
1819        };
1820        check_parameter_scope(&msg)?;
1821        // Draft-20 Section 10: "If the length does not match the length of the
1822        // Message Body, the receiver MUST close the session with a
1823        // PROTOCOL_VIOLATION." A body parser that stops short leaves bytes
1824        // here; without this the surplus is discarded and a truncated or
1825        // mis-framed field looks like a well-formed message.
1826        if body.has_remaining() {
1827            return Err(CodecError::ControlMessageLengthMismatch {
1828                declared: body_len,
1829                detail: "its fields left bytes unread",
1830            });
1831        }
1832        Ok(msg)
1833    }
1834
1835    fn encode_body(&self, buf: &mut impl BufMut) -> Result<(), CodecError> {
1836        match self {
1837            ControlMessage::Setup(m) => {
1838                encode_setup_options(&m.options, buf)?;
1839            }
1840            ControlMessage::GoAway(m) => {
1841                if m.new_session_uri.len() > MAX_GOAWAY_URI_LENGTH {
1842                    return Err(CodecError::GoAwayUriTooLong);
1843                }
1844                VarInt::from_usize(m.new_session_uri.len()).encode_moqt::<Wire>(buf);
1845                buf.put_slice(&m.new_session_uri);
1846                m.timeout.encode_moqt::<Wire>(buf);
1847            }
1848            ControlMessage::RequestOk(m) => {
1849                encode_parameters(&m.parameters, buf)?;
1850                encode_track_properties(&m.track_properties, buf)?;
1851            }
1852            ControlMessage::RequestError(m) => {
1853                if m.reason_phrase.len() > MAX_REASON_PHRASE_LENGTH {
1854                    return Err(CodecError::ReasonPhraseTooLong);
1855                }
1856                m.error_code.encode_moqt::<Wire>(buf);
1857                m.retry_interval.encode_moqt::<Wire>(buf);
1858                VarInt::from_usize(m.reason_phrase.len()).encode_moqt::<Wire>(buf);
1859                buf.put_slice(&m.reason_phrase);
1860                if let Some(r) = &m.redirect {
1861                    r.track_namespace.validate_moqt()?;
1862                    check_full_track_name(&r.track_namespace, &r.track_name)?;
1863                    VarInt::from_usize(r.connect_uri.len()).encode_moqt::<Wire>(buf);
1864                    buf.put_slice(&r.connect_uri);
1865                    r.track_namespace.encode_moqt::<Wire>(buf);
1866                    VarInt::from_usize(r.track_name.len()).encode_moqt::<Wire>(buf);
1867                    buf.put_slice(&r.track_name);
1868                }
1869            }
1870            ControlMessage::Subscribe(m) => {
1871                m.track_namespace.validate_moqt()?;
1872                check_full_track_name(&m.track_namespace, &m.track_name)?;
1873                m.request_id.encode_moqt::<Wire>(buf);
1874                m.track_namespace.encode_moqt::<Wire>(buf);
1875                VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1876                buf.put_slice(&m.track_name);
1877                encode_parameters(&m.parameters, buf)?;
1878            }
1879            ControlMessage::SubscribeOk(m) => {
1880                m.track_alias.encode_moqt::<Wire>(buf);
1881                encode_parameters(&m.parameters, buf)?;
1882                encode_track_properties(&m.track_properties, buf)?;
1883            }
1884            ControlMessage::RequestUpdate(m) => {
1885                m.request_id.encode_moqt::<Wire>(buf);
1886                encode_parameters(&m.parameters, buf)?;
1887            }
1888            ControlMessage::Publish(m) => {
1889                m.track_namespace.validate_moqt()?;
1890                check_full_track_name(&m.track_namespace, &m.track_name)?;
1891                m.request_id.encode_moqt::<Wire>(buf);
1892                m.track_namespace.encode_moqt::<Wire>(buf);
1893                VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1894                buf.put_slice(&m.track_name);
1895                m.track_alias.encode_moqt::<Wire>(buf);
1896                encode_parameters(&m.parameters, buf)?;
1897                encode_track_properties(&m.track_properties, buf)?;
1898            }
1899            // Section 10.10, Figure 13: parameter count, then parameters,
1900            // and nothing else. No Request ID — the subscription's stream is
1901            // what identifies the message.
1902            ControlMessage::PublishStateNotify(m) => {
1903                encode_parameters(&m.parameters, buf)?;
1904            }
1905            ControlMessage::PublishDone(m) => {
1906                if m.reason_phrase.len() > MAX_REASON_PHRASE_LENGTH {
1907                    return Err(CodecError::ReasonPhraseTooLong);
1908                }
1909                m.status_code.encode_moqt::<Wire>(buf);
1910                m.stream_count.encode_moqt::<Wire>(buf);
1911                VarInt::from_usize(m.reason_phrase.len()).encode_moqt::<Wire>(buf);
1912                buf.put_slice(&m.reason_phrase);
1913            }
1914            ControlMessage::PublishNamespace(m) => {
1915                m.track_namespace.validate_moqt()?;
1916                m.request_id.encode_moqt::<Wire>(buf);
1917                m.track_namespace.encode_moqt::<Wire>(buf);
1918                encode_parameters(&m.parameters, buf)?;
1919            }
1920            ControlMessage::Namespace(m) => {
1921                m.namespace_suffix.validate_moqt()?;
1922                m.namespace_suffix.encode_moqt::<Wire>(buf);
1923            }
1924            ControlMessage::NamespaceDone(m) => {
1925                m.namespace_suffix.validate_moqt()?;
1926                m.namespace_suffix.encode_moqt::<Wire>(buf);
1927            }
1928            ControlMessage::SubscribeNamespace(m) => {
1929                m.namespace_prefix.validate_moqt()?;
1930                m.request_id.encode_moqt::<Wire>(buf);
1931                m.namespace_prefix.encode_moqt::<Wire>(buf);
1932                encode_parameters(&m.parameters, buf)?;
1933            }
1934            ControlMessage::SubscribeTracks(m) => {
1935                m.namespace_prefix.validate_moqt()?;
1936                m.request_id.encode_moqt::<Wire>(buf);
1937                m.namespace_prefix.encode_moqt::<Wire>(buf);
1938                encode_parameters(&m.parameters, buf)?;
1939            }
1940            ControlMessage::TrackStatus(m) => {
1941                m.track_namespace.validate_moqt()?;
1942                check_full_track_name(&m.track_namespace, &m.track_name)?;
1943                m.request_id.encode_moqt::<Wire>(buf);
1944                m.track_namespace.encode_moqt::<Wire>(buf);
1945                VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1946                buf.put_slice(&m.track_name);
1947                encode_parameters(&m.parameters, buf)?;
1948            }
1949            // Section 10.13, Figure 16. Byte-identical to SUBSCRIBE above:
1950            // no Fetch Type, no inline range, and the namespace and name where
1951            // draft-19 put them inside its Standalone Fetch.
1952            ControlMessage::Fetch(m) => {
1953                m.track_namespace.validate_moqt()?;
1954                check_full_track_name(&m.track_namespace, &m.track_name)?;
1955                m.request_id.encode_moqt::<Wire>(buf);
1956                m.track_namespace.encode_moqt::<Wire>(buf);
1957                VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1958                buf.put_slice(&m.track_name);
1959                encode_parameters(&m.parameters, buf)?;
1960            }
1961            ControlMessage::FetchOk(m) => {
1962                buf.put_u8(m.end_of_track);
1963                m.end_group.encode_moqt::<Wire>(buf);
1964                m.end_object.encode_moqt::<Wire>(buf);
1965                encode_parameters(&m.parameters, buf)?;
1966                encode_track_properties(&m.track_properties, buf)?;
1967            }
1968            ControlMessage::PublishSkipped(m) => {
1969                m.namespace_suffix.validate_moqt()?;
1970                check_full_track_name(&m.namespace_suffix, &m.track_name)?;
1971                m.namespace_suffix.encode_moqt::<Wire>(buf);
1972                VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1973                buf.put_slice(&m.track_name);
1974            }
1975        }
1976        Ok(())
1977    }
1978
1979    fn decode_body(msg_type: MessageType, buf: &mut impl Buf) -> Result<Self, CodecError> {
1980        match msg_type {
1981            MessageType::Setup => {
1982                let options = decode_setup_options(buf)?;
1983                Ok(ControlMessage::Setup(Setup { options }))
1984            }
1985            MessageType::GoAway => {
1986                let uri_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
1987                // Draft-20 Section 10.4: an endpoint that receives a New
1988                // Session URI Length above the maximum MUST close the session
1989                // with a PROTOCOL_VIOLATION. Checked here as well as on encode
1990                // so an oversized URI never reaches the application.
1991                if uri_len > MAX_GOAWAY_URI_LENGTH {
1992                    return Err(CodecError::GoAwayUriTooLong);
1993                }
1994                let uri = read_bytes(buf, uri_len)?;
1995                let timeout = VarInt::decode_moqt::<Wire>(buf)?;
1996                Ok(ControlMessage::GoAway(GoAway { new_session_uri: uri, timeout }))
1997            }
1998            MessageType::RequestOk => {
1999                let parameters = decode_parameters(buf)?;
2000                let track_properties = decode_track_properties(buf)?;
2001                Ok(ControlMessage::RequestOk(RequestOk { parameters, track_properties }))
2002            }
2003            MessageType::RequestError => {
2004                let error_code = VarInt::decode_moqt::<Wire>(buf)?;
2005                let retry_interval = VarInt::decode_moqt::<Wire>(buf)?;
2006                let reason_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2007                // Draft-20 Section 1.4.4: a received reason phrase length above
2008                // the maximum MUST close the session with a PROTOCOL_VIOLATION.
2009                if reason_len > MAX_REASON_PHRASE_LENGTH {
2010                    return Err(CodecError::ReasonPhraseTooLong);
2011                }
2012                let reason_phrase = read_bytes(buf, reason_len)?;
2013                let redirect = if error_code.into_inner() == request_error_codes::REDIRECT {
2014                    let uri_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2015                    let connect_uri = read_bytes(buf, uri_len)?;
2016                    let track_namespace = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2017                    let name_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2018                    let track_name = read_bytes(buf, name_len)?;
2019                    check_full_track_name(&track_namespace, &track_name)?;
2020                    Some(Redirect { connect_uri, track_namespace, track_name })
2021                } else {
2022                    None
2023                };
2024                Ok(ControlMessage::RequestError(RequestError {
2025                    error_code,
2026                    retry_interval,
2027                    reason_phrase,
2028                    redirect,
2029                }))
2030            }
2031            MessageType::Subscribe => {
2032                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2033                let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2034                let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2035                let track_name = read_bytes(buf, tn_len)?;
2036                check_full_track_name(&track_namespace, &track_name)?;
2037                let parameters = decode_parameters(buf)?;
2038                Ok(ControlMessage::Subscribe(Subscribe {
2039                    request_id,
2040                    track_namespace,
2041                    track_name,
2042                    parameters,
2043                }))
2044            }
2045            MessageType::SubscribeOk => {
2046                let track_alias = VarInt::decode_moqt::<Wire>(buf)?;
2047                let parameters = decode_parameters(buf)?;
2048                let track_properties = decode_track_properties(buf)?;
2049                Ok(ControlMessage::SubscribeOk(SubscribeOk {
2050                    track_alias,
2051                    parameters,
2052                    track_properties,
2053                }))
2054            }
2055            MessageType::RequestUpdate => {
2056                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2057                let parameters = decode_parameters(buf)?;
2058                Ok(ControlMessage::RequestUpdate(RequestUpdate { request_id, parameters }))
2059            }
2060            MessageType::Publish => {
2061                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2062                let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2063                let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2064                let track_name = read_bytes(buf, tn_len)?;
2065                let track_alias = VarInt::decode_moqt::<Wire>(buf)?;
2066                check_full_track_name(&track_namespace, &track_name)?;
2067                let parameters = decode_parameters(buf)?;
2068                let track_properties = decode_track_properties(buf)?;
2069                Ok(ControlMessage::Publish(Publish {
2070                    request_id,
2071                    track_namespace,
2072                    track_name,
2073                    track_alias,
2074                    parameters,
2075                    track_properties,
2076                }))
2077            }
2078            MessageType::PublishStateNotify => {
2079                let parameters = decode_parameters(buf)?;
2080                Ok(ControlMessage::PublishStateNotify(PublishStateNotify { parameters }))
2081            }
2082            MessageType::PublishDone => {
2083                // The Status Code is carried up whatever it is. Section 14
2084                // forbids closing the session over an unknown one and requires
2085                // it to be read as INTERNAL_ERROR, so refusing the frame here
2086                // would take a choice away from the caller that the draft gives
2087                // it. See [`PublishDone::status_code`].
2088                let status_code = VarInt::decode_moqt::<Wire>(buf)?;
2089                let stream_count = VarInt::decode_moqt::<Wire>(buf)?;
2090                let reason_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2091                // Draft-20 Section 1.4.4, same bound as REQUEST_ERROR above.
2092                if reason_len > MAX_REASON_PHRASE_LENGTH {
2093                    return Err(CodecError::ReasonPhraseTooLong);
2094                }
2095                let reason_phrase = read_bytes(buf, reason_len)?;
2096                Ok(ControlMessage::PublishDone(PublishDone {
2097                    status_code,
2098                    stream_count,
2099                    reason_phrase,
2100                }))
2101            }
2102            MessageType::PublishNamespace => {
2103                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2104                let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2105                let parameters = decode_parameters(buf)?;
2106                Ok(ControlMessage::PublishNamespace(PublishNamespace {
2107                    request_id,
2108                    track_namespace,
2109                    parameters,
2110                }))
2111            }
2112            MessageType::Namespace => {
2113                let namespace_suffix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2114                Ok(ControlMessage::Namespace(Namespace { namespace_suffix }))
2115            }
2116            MessageType::NamespaceDone => {
2117                let namespace_suffix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2118                Ok(ControlMessage::NamespaceDone(NamespaceDone { namespace_suffix }))
2119            }
2120            MessageType::SubscribeNamespace => {
2121                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2122                let namespace_prefix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2123                let parameters = decode_parameters(buf)?;
2124                Ok(ControlMessage::SubscribeNamespace(SubscribeNamespace {
2125                    request_id,
2126                    namespace_prefix,
2127                    parameters,
2128                }))
2129            }
2130            MessageType::SubscribeTracks => {
2131                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2132                let namespace_prefix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2133                let parameters = decode_parameters(buf)?;
2134                Ok(ControlMessage::SubscribeTracks(SubscribeTracks {
2135                    request_id,
2136                    namespace_prefix,
2137                    parameters,
2138                }))
2139            }
2140            MessageType::TrackStatus => {
2141                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2142                let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2143                let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2144                let track_name = read_bytes(buf, tn_len)?;
2145                check_full_track_name(&track_namespace, &track_name)?;
2146                let parameters = decode_parameters(buf)?;
2147                Ok(ControlMessage::TrackStatus(TrackStatus {
2148                    request_id,
2149                    track_namespace,
2150                    track_name,
2151                    parameters,
2152                }))
2153            }
2154            MessageType::Fetch => {
2155                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2156                let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2157                let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2158                let track_name = read_bytes(buf, tn_len)?;
2159                check_full_track_name(&track_namespace, &track_name)?;
2160                let parameters = decode_parameters(buf)?;
2161                Ok(ControlMessage::Fetch(Fetch {
2162                    request_id,
2163                    track_namespace,
2164                    track_name,
2165                    parameters,
2166                }))
2167            }
2168            MessageType::FetchOk => {
2169                if buf.remaining() < 1 {
2170                    return Err(CodecError::UnexpectedEnd);
2171                }
2172                let end_of_track = buf.get_u8();
2173                let end_group = VarInt::decode_moqt::<Wire>(buf)?;
2174                let end_object = VarInt::decode_moqt::<Wire>(buf)?;
2175                let parameters = decode_parameters(buf)?;
2176                let track_properties = decode_track_properties(buf)?;
2177                Ok(ControlMessage::FetchOk(FetchOk {
2178                    end_of_track,
2179                    end_group,
2180                    end_object,
2181                    parameters,
2182                    track_properties,
2183                }))
2184            }
2185            MessageType::PublishSkipped => {
2186                let namespace_suffix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2187                let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2188                let track_name = read_bytes(buf, tn_len)?;
2189                check_full_track_name(&namespace_suffix, &track_name)?;
2190                Ok(ControlMessage::PublishSkipped(PublishSkipped { namespace_suffix, track_name }))
2191            }
2192        }
2193    }
2194
2195    pub fn message_type(&self) -> MessageType {
2196        match self {
2197            ControlMessage::Setup(_) => MessageType::Setup,
2198            ControlMessage::GoAway(_) => MessageType::GoAway,
2199            ControlMessage::RequestOk(_) => MessageType::RequestOk,
2200            ControlMessage::RequestError(_) => MessageType::RequestError,
2201            ControlMessage::Subscribe(_) => MessageType::Subscribe,
2202            ControlMessage::SubscribeOk(_) => MessageType::SubscribeOk,
2203            ControlMessage::RequestUpdate(_) => MessageType::RequestUpdate,
2204            ControlMessage::Publish(_) => MessageType::Publish,
2205            ControlMessage::PublishStateNotify(_) => MessageType::PublishStateNotify,
2206            ControlMessage::PublishDone(_) => MessageType::PublishDone,
2207            ControlMessage::PublishNamespace(_) => MessageType::PublishNamespace,
2208            ControlMessage::Namespace(_) => MessageType::Namespace,
2209            ControlMessage::NamespaceDone(_) => MessageType::NamespaceDone,
2210            ControlMessage::SubscribeNamespace(_) => MessageType::SubscribeNamespace,
2211            ControlMessage::SubscribeTracks(_) => MessageType::SubscribeTracks,
2212            ControlMessage::TrackStatus(_) => MessageType::TrackStatus,
2213            ControlMessage::Fetch(_) => MessageType::Fetch,
2214            ControlMessage::FetchOk(_) => MessageType::FetchOk,
2215            ControlMessage::PublishSkipped(_) => MessageType::PublishSkipped,
2216        }
2217    }
2218}
2219
2220#[cfg(test)]
2221mod tests {
2222    use super::*;
2223
2224    /// Frame `body` as a draft-20 control message of `type_id`, declaring
2225    /// `declared_len` rather than the body's real length. Used to build the
2226    /// mismatched frame the length rule is about.
2227    fn frame_with_declared_len(type_id: u64, declared_len: u16, body: &[u8]) -> Vec<u8> {
2228        let mut out = Vec::new();
2229        VarInt::from_u64_moqt(type_id).encode_moqt::<Wire>(&mut out);
2230        out.put_u16(declared_len);
2231        out.put_slice(body);
2232        out
2233    }
2234
2235    fn frame(type_id: u64, body: &[u8]) -> Vec<u8> {
2236        frame_with_declared_len(type_id, body.len() as u16, body)
2237    }
2238
2239    /// A SUBSCRIBE body: request id 1, namespace ("a"), track name "b", and
2240    /// `params` already encoded.
2241    fn subscribe_body(params: &[u8]) -> Vec<u8> {
2242        let mut body = vec![0x01, 0x01, 0x01, b'a', 0x01, b'b'];
2243        body.extend_from_slice(params);
2244        body
2245    }
2246
2247    /// Draft-20 Section 10: "If the length does not match the length of the
2248    /// Message Body, the receiver MUST close the session with a
2249    /// PROTOCOL_VIOLATION."
2250    ///
2251    /// Fails if `decode` parses this SUBSCRIBE and lets the two surplus bytes
2252    /// vanish.
2253    #[test]
2254    fn a_message_body_shorter_than_the_declared_length_is_refused() {
2255        let body = subscribe_body(&[0x00]);
2256        let mut junked = body.clone();
2257        junked.extend_from_slice(&[0xff, 0xff]);
2258        let bytes = frame_with_declared_len(0x03, (body.len() + 2) as u16, &junked);
2259
2260        let mut buf = &bytes[..];
2261        assert_eq!(
2262            ControlMessage::decode(&mut buf),
2263            Err(CodecError::ControlMessageLengthMismatch {
2264                declared: (body.len() + 2),
2265                detail: "its fields left bytes unread",
2266            })
2267        );
2268
2269        // The same body with an honest length still decodes, so the guard
2270        // rejects the mismatch and not the message.
2271        let honest = frame(0x03, &body);
2272        let mut buf = &honest[..];
2273        assert!(ControlMessage::decode(&mut buf).is_ok());
2274    }
2275
2276    /// Draft-20 Section 1.4.4: "The reason phrase length has a maximum value of
2277    /// 1024 bytes. If an endpoint receives a length exceeding the maximum, it
2278    /// MUST close the session with a PROTOCOL_VIOLATION".
2279    ///
2280    /// Fails if the 2000-byte phrase is handed to the application.
2281    #[test]
2282    fn an_over_long_reason_phrase_is_refused_on_decode() {
2283        for (type_id, prefix) in [(0x05u64, vec![0x01, 0x00]), (0x0B, vec![0x01, 0x00])] {
2284            let mut body = prefix;
2285            let over = MAX_REASON_PHRASE_LENGTH + 976;
2286            VarInt::from_usize(over).encode_moqt::<Wire>(&mut body);
2287            body.extend(std::iter::repeat_n(b'x', over));
2288            let bytes = frame(type_id, &body);
2289
2290            let mut buf = &bytes[..];
2291            assert_eq!(
2292                ControlMessage::decode(&mut buf),
2293                Err(CodecError::ReasonPhraseTooLong),
2294                "message type 0x{type_id:x}"
2295            );
2296        }
2297    }
2298
2299    /// Draft-20 Section 10.4: "The maximum length of the New Session URI is
2300    /// 8,192 bytes. If an endpoint receives a length exceeding the maximum, it
2301    /// MUST close the session with a PROTOCOL_VIOLATION."
2302    ///
2303    /// Fails if the oversized URI reaches the application, where a migrating
2304    /// endpoint would follow it.
2305    #[test]
2306    fn an_over_long_goaway_uri_is_refused_on_decode() {
2307        let over = MAX_GOAWAY_URI_LENGTH + 808;
2308        let mut body = Vec::new();
2309        VarInt::from_usize(over).encode_moqt::<Wire>(&mut body);
2310        body.extend(std::iter::repeat_n(b'u', over));
2311        body.push(0x00); // timeout
2312        let bytes = frame(0x10, &body);
2313
2314        let mut buf = &bytes[..];
2315        assert_eq!(ControlMessage::decode(&mut buf), Err(CodecError::GoAwayUriTooLong));
2316    }
2317
2318    /// Draft-20 Section 10.2.8 (GROUP_ORDER): "The allowed values are Ascending
2319    /// (0x1) or Descending (0x2). If an endpoint receives a value outside this
2320    /// range, it MUST close the session with PROTOCOL_VIOLATION." Section
2321    /// 10.2.17 says the same of FORWARD with the values 0 and 1.
2322    ///
2323    /// Fails if the out-of-range byte is handed up as an ordinary parameter.
2324    #[test]
2325    fn a_uint8_parameter_outside_its_range_is_refused() {
2326        // key, rejected value, accepted value
2327        let cases = [(0x22u8, 7u8, 2u8), (0x10, 9, 1)];
2328        for (key, bad, good) in cases {
2329            let bytes = frame(0x03, &subscribe_body(&[0x01, key, bad]));
2330            let mut buf = &bytes[..];
2331            assert_eq!(
2332                ControlMessage::decode(&mut buf),
2333                Err(CodecError::ParameterValueOutOfRange { key: key as u64, value: bad as u64 }),
2334                "parameter 0x{key:x} value {bad}"
2335            );
2336
2337            let bytes = frame(0x03, &subscribe_body(&[0x01, key, good]));
2338            let mut buf = &bytes[..];
2339            assert!(
2340                ControlMessage::decode(&mut buf).is_ok(),
2341                "parameter 0x{key:x} value {good} should still decode"
2342            );
2343        }
2344    }
2345
2346    /// SUBSCRIBER_PRIORITY (0x20) is a uint8 with no restricted range, so it
2347    /// must keep accepting the whole 0-255 span. This is the negative half of
2348    /// the range check: a table that over-reached would fail here.
2349    #[test]
2350    fn subscriber_priority_still_accepts_the_whole_byte_range() {
2351        for value in [0u8, 1, 2, 128, 255] {
2352            let bytes = frame(0x03, &subscribe_body(&[0x01, 0x20, value]));
2353            let mut buf = &bytes[..];
2354            assert!(ControlMessage::decode(&mut buf).is_ok(), "priority {value}");
2355        }
2356    }
2357
2358    fn param(key: u64, value: &[u8]) -> KeyValuePair {
2359        KeyValuePair { key: VarInt::from_u64_moqt(key), value: KvpValue::Bytes(value.to_vec()) }
2360    }
2361
2362    /// Draft-20 Section 10.2.16: "The LARGEST_OBJECT parameter (Parameter Type
2363    /// 0x9) is a Location." Section 10.2 defines Location as "Two consecutive
2364    /// varints (Group, Object)" — the value carries no length of its own.
2365    ///
2366    /// The frame below is built from the draft rather than from this encoder:
2367    /// REQUEST_OK, four body bytes, one parameter, type delta `0x09`, then the
2368    /// two varints `0x0a` and `0x03` for Location (10, 3). A length-prefixed
2369    /// spelling would need a fifth byte.
2370    ///
2371    /// Fails if `0x09` is read as Length-prefixed: the group varint `0x0a` then
2372    /// reads as a value length of 10 and runs off the end of a four-byte body.
2373    #[test]
2374    fn largest_object_is_two_bare_varints() {
2375        let body = [0x01, 0x09, 0x0a, 0x03];
2376        let bytes = frame(0x07, &body);
2377
2378        let msg = ControlMessage::decode(&mut &bytes[..]).expect("spec-correct frame must decode");
2379        let ControlMessage::RequestOk(ok) = &msg else {
2380            panic!("expected REQUEST_OK, got {msg:?}")
2381        };
2382        assert_eq!(ok.parameters, vec![param(0x09, &[0x0a, 0x03])]);
2383        assert!(ok.track_properties.is_empty(), "the four body bytes are all parameter");
2384
2385        let mut out = Vec::new();
2386        msg.encode(&mut out).expect("re-encode");
2387        assert_eq!(out, bytes, "the value must go back out as the two bare varints it came in as");
2388    }
2389
2390    /// A Location value the encoder was handed but the decoder could not read
2391    /// back is refused on the way out, not written.
2392    ///
2393    /// LARGEST_OBJECT carries no length of its own — that is the whole point
2394    /// of the encoding — so `encode_parameters` writes its bytes verbatim. A
2395    /// value built in memory rather than decoded is under no obligation to be
2396    /// two varints, and without this check the codec answers `Ok(())` and puts
2397    /// a frame on the wire that `ControlMessage::decode` then refuses. One
2398    /// varint short and one varint long are the two ways to get it wrong.
2399    ///
2400    /// Fails if this draft's encode arm loses its `is_location_value` guard;
2401    /// the check is per-draft, not inherited from shared code.
2402    #[test]
2403    fn a_location_value_that_is_not_two_varints_is_refused_on_encode() {
2404        for (label, value) in
2405            [("one varint", vec![0x0a]), ("three varints", vec![0x0a, 0x03, 0x05])]
2406        {
2407            let msg = ControlMessage::RequestOk(RequestOk {
2408                parameters: vec![param(0x09, &value)],
2409                track_properties: Vec::new(),
2410            });
2411            let mut out = Vec::new();
2412            assert!(
2413                msg.encode(&mut out).is_err(),
2414                "LARGEST_OBJECT of {label} must not encode: the decoder cannot read it back"
2415            );
2416        }
2417
2418        // The well-formed value still goes out, so the check refuses the
2419        // malformed case and not the encoding itself.
2420        let msg = ControlMessage::RequestOk(RequestOk {
2421            parameters: vec![param(0x09, &[0x0a, 0x03])],
2422            track_properties: Vec::new(),
2423        });
2424        let mut out = Vec::new();
2425        msg.encode(&mut out).expect("a Location of exactly two varints must still encode");
2426        ControlMessage::decode(&mut &out[..]).expect("and must decode back");
2427    }
2428
2429    /// The same Location read through a message that carries other fields
2430    /// after it, so a stray length byte cannot hide in a trailing block.
2431    ///
2432    /// SUBSCRIBE_OK is track alias `0x05`, then the parameters, then the track
2433    /// properties. With LARGEST_OBJECT (10, 3) and one property
2434    /// (OBJECT_DELIVERY_TIMEOUT, type `0x02`, 5000ms as the two-byte varint
2435    /// `0x93 0x88`), the body is `05 01 09 0a 03 02 93 88`.
2436    #[test]
2437    fn a_location_does_not_eat_the_block_that_follows_it() {
2438        let body = [0x05, 0x01, 0x09, 0x0a, 0x03, 0x02, 0x93, 0x88];
2439        let bytes = frame(0x04, &body);
2440
2441        let msg = ControlMessage::decode(&mut &bytes[..]).expect("spec-correct frame must decode");
2442        let ControlMessage::SubscribeOk(ok) = &msg else {
2443            panic!("expected SUBSCRIBE_OK, got {msg:?}")
2444        };
2445        assert_eq!(ok.parameters, vec![param(0x09, &[0x0a, 0x03])]);
2446        assert_eq!(
2447            ok.track_properties,
2448            vec![KeyValuePair {
2449                key: VarInt::from_u64_moqt(0x02),
2450                value: KvpValue::Varint(VarInt::from_u64_moqt(5000)),
2451            }]
2452        );
2453
2454        let mut out = Vec::new();
2455        msg.encode(&mut out).expect("re-encode");
2456        assert_eq!(out, bytes);
2457    }
2458
2459    /// Draft-20 Section 10.2.20: the TRACK_NAMESPACE_PREFIX parameter
2460    /// (Parameter Type 0x34) "uses the Track Namespace encoding described in
2461    /// Section 2.4.1" — a varint field count followed by that many
2462    /// length-prefixed fields, and nothing in front of it. That encoding is not
2463    /// one of the four Section 10.2 lists, so it cannot be assumed to be
2464    /// Length-prefixed by default.
2465    ///
2466    /// The frame below is built from Section 2.4.1: REQUEST_UPDATE for request
2467    /// `7`, one parameter, type delta `0x34`, then the namespace ("live",
2468    /// "sports") as `02 04 "live" 06 "sports"`. Sixteen body bytes; a
2469    /// length-prefixed spelling would need a seventeenth for the outer length.
2470    ///
2471    /// Fails if `0x34` is read as Length-prefixed: the field count `0x02` then
2472    /// reads as an outer length of two bytes, leaving eleven bytes of namespace
2473    /// unread. Draft-20's Section 10 body-length check refuses this frame, but
2474    /// where the surplus lands inside the declared body, as in
2475    /// [`an_empty_track_namespace_prefix_is_one_zero_byte`], the misread is
2476    /// silent.
2477    #[test]
2478    fn track_namespace_prefix_is_a_bare_track_namespace() {
2479        let namespace: Vec<u8> = [&[0x02, 0x04][..], b"live", &[0x06][..], b"sports"].concat();
2480        assert_eq!(namespace.len(), 13);
2481
2482        let body: Vec<u8> = [&[0x07, 0x01, 0x34][..], &namespace].concat();
2483        assert_eq!(body.len(), 16);
2484        let bytes = frame(0x02, &body);
2485
2486        let msg = ControlMessage::decode(&mut &bytes[..]).expect("spec-correct frame must decode");
2487        let ControlMessage::RequestUpdate(update) = &msg else {
2488            panic!("expected REQUEST_UPDATE, got {msg:?}")
2489        };
2490        assert_eq!(update.request_id.into_inner(), 7);
2491        assert_eq!(update.parameters, vec![param(0x34, &namespace)]);
2492
2493        let mut out = Vec::new();
2494        msg.encode(&mut out).expect("re-encode");
2495        assert_eq!(out, bytes, "no outer length may appear in front of the Track Namespace");
2496    }
2497
2498    /// An empty prefix is a legal Track Namespace: Section 2.4.1 puts one at
2499    /// "between 0 and 32 Track Namespace Fields". On the wire that is the
2500    /// single byte `0x00`, and it must not be confused with a length-prefixed
2501    /// value of zero bytes.
2502    #[test]
2503    fn an_empty_track_namespace_prefix_is_one_zero_byte() {
2504        let body = [0x07, 0x01, 0x34, 0x00];
2505        let bytes = frame(0x02, &body);
2506
2507        let msg = ControlMessage::decode(&mut &bytes[..]).expect("empty prefix must decode");
2508        let ControlMessage::RequestUpdate(update) = &msg else {
2509            panic!("expected REQUEST_UPDATE, got {msg:?}")
2510        };
2511        assert_eq!(update.parameters, vec![param(0x34, &[0x00])]);
2512
2513        let mut out = Vec::new();
2514        msg.encode(&mut out).expect("re-encode");
2515        assert_eq!(out, bytes);
2516    }
2517}